微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python:中断终端铃声/系统铃声以模拟莫尔斯电码 DOT/DASH 消息

如何解决Python:中断终端铃声/系统铃声以模拟莫尔斯电码 DOT/DASH 消息

我正在编写一个脚本,该脚本通过触发认系统铃声来模拟莫尔斯电码声音,从而在终端中模拟莫尔斯电码。 DASH 声音是通过让钟声运行 0.80 秒产生的,DOT 声音是通过只让钟声产生运行 0.20 秒(通过中断它)。

我正在尝试使其成为独立于操作系统的脚本,因此不打算使用任何特定于操作系统的库。但我目前使用的是 Windows。

我非常接近!当我的代码在终端中运行时,DASH 听起来工作正常,但是如果一个字符(例如 'b')以点结尾,则该字符的最后 DOT 声音不会被打断,而是听起来像 DASH, 导致声音错误

我获得 DOT/DASH 声音的方法是用另一个铃声(通过线程)中断铃声

例如:如果消息是“ab”,声音应该是:

  • "DOT-DASH {SMALL_PAUSE} DASH-DOT-DOT-DOT"

我的代码输出(声音方面)是:

  • "DOT-DASH {SMALL_PAUSE} DASH-DOT-DOT-DASH"

我需要以某种方式打断最后的铃声,这样它只持续 0.2 秒,而且我不知道如何在不调用一个铃声的情况下做到这一点。

如何正确控制声音的持续时间?

代码(工作 - 没有第 3 方库):

import sys
import threading
import time

# Allows message inputs to convert to morse by making system beep

# Morse codes: char: [beep_1,beep_2,beep_n....]

DASH = 0.80  # only run the bell for this duration before interrupting
DOT = 0.20  # only run the bell for this duration before interrupting
CHAR_PAUSE = 1.5  # run no bells for this duration
SPACE_PAUSE = 3.5  # run no bells for this duration

# ISSUE: if the character ends in a DOT,it sounds like a dash with my current script.
# Note I've only translated up to 'e' currently
morse = {
    'a': [DOT,DASH],# Sounds Fine as last character is a DASH
    'b': [DASH,DOT,DOT],# Sounds right till last DOT (sounds like dash)
    'c': [DASH,DASH,# Sounds right till last DOT (sounds like dash)
    'd': [DASH,# Sounds right till last DOT (sounds like dash)
    'e': [DOT],# Will sound like a DASH - not good
        }

def beep_function(char,beep):
    """play system beep sound for {beep} duration before interruption"""
    sys.stdout.write('\a')
    sys.stdout.flush()
    time.sleep(beep)


threads = []
message = 'ab'  # You'll notice the last beep in 'b' is not right
message = message.lower()
for char in message:
    if char != ' ':
        for beep in morse[char]:
            t = threading.Thread(target=beep_function(char,beep))
            threads.append(beep)
            t.start()
        time.sleep(CHAR_PAUSE)
    if char == ' ':
        time.sleep(SPACE_PAUSE)  # For when I eventually have an entire message

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。