2

I made a Morse code translator which works fine. Then I wanted to make beep sounds corresponding to the encoded message. I tried the winsound module. But it isn't playing any sound. I collected the dots and dashes sound from an online Morse Code Translator. The sound works fine if played by audio player. But it doesn't work with PlaySound().

from winsound import PlaySound
import pyperclip as pc

morse_code_dictionary = {'A': '.-', 'B': '-...',
                         'C': '-.-.', 'D': '-..', 'E': '.',
                         'F': '..-.', 'G': '--.', 'H': '....',
                         'I': '..', 'J': '.---', 'K': '-.-',
                         'L': '.-..', 'M': '--', 'N': '-.',
                         'O': '---', 'P': '.--.', 'Q': '--.-',
                         'R': '.-.', 'S': '...', 'T': '-',
                         'U': '..-', 'V': '...-', 'W': '.--',
                         'X': '-..-', 'Y': '-.--', 'Z': '--..',
                         '1': '.----', '2': '..---', '3': '...--',
                         '4': '....-', '5': '.....', '6': '-....',
                         '7': '--...', '8': '---..', '9': '----.',
                         '0': '-----', ', ': '--..--', '.': '.-.-.-',
                         '?': '..--..', '/': '-..-.', '-': '-....-',
                         '(': '-.--.', ')': '-.--.-', ' ': '/', '': ''}

morse_code_to_alphabet_dictionary = {
    x: y for y, x in morse_code_dictionary.items()}

md, mad = morse_code_dictionary, morse_code_to_alphabet_dictionary


def valid_morse(message):
    char_code_list = message.split(" ")
    return all(char_code in mad for char_code in char_code_list)


def encode():
    text = input("Please input your text here.\n=")
    result = ""
    try:
        for char in text.upper():
            result += md[char] + " "
    except KeyError:
        result = "invalid charecter input!!!"

    return result


def decode():
    code = input("Enter your code here.\n=")
    result = ""
    if not valid_morse(code):
        result = "Your code was not valid or not in my knowladge. Please try again!!!"

    for single_char in code.split(" "):
        result += mad[single_char]

    return result.capitalize()


while True:
    ask = input(
        "Do you want to encode or decode?\nTo encode press 1\nTo decode press 2\n=")

    if ask.isdigit():
        ask = int(ask)

        if ask not in [1, 2]:
            print("Invalid inpput!!!\nTry Again!!!")
            continue

        elif ask == 1:
            result = encode()

        elif ask == 2:
            result = decode()
    break


print(result)
print("Result copied in ClipBoard")
pc.copy(result)

path = "*/"

for i in result:
    if i == ".":
        PlaySound(path+"morse_dot.ogg", 3)
    elif i == "-":
        PlaySound(path + "morse_dash.ogg", 3)
    elif i == "/":
        PlaySound(path + "morse_dash.ogg", 3)


 input("Press Enter To Exit()")
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Can you play any sound at all with `PlaySound`? – mkrieger1 Aug 31 '22 at 22:18
  • @mkrieger1 No, I can't. I winsound or "playsound" module doesn't work at all. – Safayat Ibrahim Aug 31 '22 at 22:24
  • What did you intend the `, 3` to mean? – mkrieger1 Aug 31 '22 at 22:49
  • @mkrieger1 amm... at first I got this error **"TypeError: PlaySound() missing required argument 'flags' (pos 2)"** . so I tried to give the second parameter, value "4" or "2" threw error. **Value 2 = "Runtime Error: Failed to play sound"** and **value 4 = "TypeError: a bytes-like object is required, not 'str'"** and **"0"** just played **default windows error sound** so I used **"3"**.. I don't exactly know what this parameter called "flags" do.... I didn't find any docs about it – Safayat Ibrahim Aug 31 '22 at 23:05

1 Answers1

0

You passed 3 as the flags parameter for PlaySound which amounts to SND_ASYNC | SND_NODEFAULT(1)

This combination of flags doesn't make sense in your case.

  • By SND_NODEFAULT you are telling PlaySound to omit the default sound if playing the sound file failed. This is bad because you don't notice if playing any sound works at all.

  • SND_ASYNC isn't needed in your case.

Since the first argument you have passed is a filename, you have to use the flag SND_FILENAME.

In the simplest case you should be able to use PlaySound(path+"morse_dot.ogg", winsound.SND_FILENAME) (after adding import winsound at the top).

If this plays a default "beep" sound then you know that winsound is able to play a sound, but it couldn't play the sound from the file you have specified.

One reason this could fail is that */morse_dot.ogg isn't a valid file path. Did you mean ./morse_dot.ogg? Another reason might be that the documentation states that PlaySound plays WAV files, but you specified an .ogg file.


(1) The numeric values of the flags aren't listed in the documentation but you can easily get them with a line of code: import winsound; print({k: v for k, v in vars(winsound).items() if k.startswith('SND_')}).

mkrieger1
  • 19,194
  • 5
  • 54
  • 65