pythonpython-playsound

How to play sound after printing to the screen?


I am trying to write a program that plays the Morse code sound while showing the Morse code.

The problem that I have is sound plays before showing the Morse code in the program. The program has a UI based on tkinter:

   for item in self.morse_code:
        self.output_text_area.config(state="normal")
        self.output_text_area.insert(END, item)
        self.output_text_area.config(state="disable")
    play_sound(self.morse_code)

I am using the playsound library and below is the the function in charge of playing the sound:

from playsound import playsound

def play_sound(morse_code: list):
    print(morse_code)
    for code in morse_code:
        print(code)
        for char in code:
            if char == '-':
                playsound('sound/morse_line.mp3')
            elif char == '.':
                playsound('sound/morse_dot.mp3')
            elif char == '|':
                continue
            time.sleep(0.05)
        time.sleep(1)

How can I get the program to show the Morse Code first , then play Morse Code sound? Currently, even though the code for updating the text_area executes first, the sound plays first then after it is done it will show the Morse Code.


Solution

  • This is because the playsound function has a "block" argument, that blocks executing until the sound has completed execution. By default, this argument is "True". Change it to "False", and you're good to go:

    from playsound import playsound
    
    def play_sound(morse_code: list):
    print(morse_code)
    for code in morse_code:
        print(code)
        for char in code:
            if char == '-':
                playsound('sound/morse_line.mp3', block=False)
            elif char == '.':
                playsound('sound/morse_dot.mp3', block=False)
            elif char == '|':
                continue
            time.sleep(0.05)
        time.sleep(1)
    

    You may, however, want to print and play the sound at the same time, in which case just iterate over each letter of the string, print it individually and play the sound as well, instead of printing it all together at the start of the function.

    Source: Playsound Documentation at https://pypi.org/project/playsound/

    Relevant part: The playsound module contains only one thing - the function (also named) playsound.

    It requires one argument - the path to the file with the sound you’d like to play. This may be a local file, or a URL.

    There’s an optional second argument, block, which is set to True by default. Setting it to False makes the function run asynchronously.