Python 在单独的线程中执行播放声音
Python execute playsound in separate thread
我需要在我的 Python 程序中播放声音,所以我为此使用了 playsound 模块:
def playy():
playsound('beep.mp3')
如何在 main 方法中将其修改为 运行 作为新线程?
如果条件为真,我需要在主方法中 运行 这个方法。当它为 false 时,线程需要停止。
使用线程库:
from threading import Thread
T = Thread(target=playy) # create thread
T.start() # Launch created thread
由于python多线程并不是真正的多线程(more on this here),我建议使用多进程:
from multiprocessing import Process
def playy():
playsound('beep.mp3')
P = Process(name="playsound",target=playy)
P.start() # Inititialize Process
可以用P.terminate()
随意终止
您可能不必担心使用线程。您可以简单地调用 playsound 如下:
def playy():
playsound('beep.mp3', block = False)
这将允许程序保持 运行,而无需等待声音播放完成。
我需要在我的 Python 程序中播放声音,所以我为此使用了 playsound 模块:
def playy():
playsound('beep.mp3')
如何在 main 方法中将其修改为 运行 作为新线程? 如果条件为真,我需要在主方法中 运行 这个方法。当它为 false 时,线程需要停止。
使用线程库:
from threading import Thread
T = Thread(target=playy) # create thread
T.start() # Launch created thread
由于python多线程并不是真正的多线程(more on this here),我建议使用多进程:
from multiprocessing import Process
def playy():
playsound('beep.mp3')
P = Process(name="playsound",target=playy)
P.start() # Inititialize Process
可以用P.terminate()
您可能不必担心使用线程。您可以简单地调用 playsound 如下:
def playy():
playsound('beep.mp3', block = False)
这将允许程序保持 运行,而无需等待声音播放完成。