Python execute playsound in separate thread

╄→尐↘猪︶ㄣ 提交于 2021-02-18 11:42:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!