Python execute playsound in separate thread

7.5k Views Asked by At

I need to play a sound in my Python program so I used playsound module for that:

def playy():
    playsound('beep.mp3')

How can I modify this to run inside main method as a new thread? I need to run this method inside the main method if a condition is true. When it is false the thread needs to stop.

3

There are 3 best solutions below

0
On BEST ANSWER

Use threading library :

from threading import Thread
T = Thread(target=playy) # create thread
T.start() # Launch created thread
4
On

As python multi-threading is not really multi-threading (more on this here), I would suggest using a multi-process for it:

from multiprocessing import Process

def playy():
    playsound('beep.mp3')


P = Process(name="playsound",target=playy)
P.start() # Inititialize Process

can be terminated at will with P.terminate()

1
On

You may not have to worry about using a thread. You can simply call playsound as follows:

def playy():  
    playsound('beep.mp3', block = False)

This will allow the program to keep running without waiting for the sound play to finish.