问题
I need to play sound in my python program so that 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 thread need to stop
回答1:
Use threading library :
from threading import Thread
T = Thread(target=playy) # create thread
T.start() # Launch created thread
回答2:
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.
回答3:
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()
来源:https://stackoverflow.com/questions/53246933/python-execute-playsound-in-separate-thread