Reputation: 149
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.
Upvotes: 8
Views: 8264
Reputation: 309
If you don't want to get confused by threading stuff Nava could be a better option for you. You can just do
from nava import play
play("beep.wav", async_mode=True)
Up until now it supports mp3
only for MacOS (but supports wav
for other OSs). You can always convert your mp3
to wav
.
Upvotes: 0
Reputation: 81
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.
Upvotes: 8
Reputation: 2557
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()
Upvotes: 2
Reputation: 172
Use threading library :
from threading import Thread
T = Thread(target=playy) # create thread
T.start() # Launch created thread
Upvotes: 5