在Python中异步播放声音

And*_*rej 5 python multithreading python-3.x

我while loop的相机(带有 opencv)可以在物体移动时拍照。我也想调用一个函数来播放声音。但是当我调用并播放它时,它将在该执行时间内停止循环。我尝试过,ThreadPoolExecutor但不知道如何将它与我的代码混合,因为我没有将任何内容传递给函数。只需从循环中调用它即可。顺便提一句。something如果循环中出现多个代码,我希望能够多次播放它(执行时多次执行)

相机脚本

from play_it import alert

while True:
    #do something in cv2
    if "something":
        alert() # Here it slowing the loop
Run Code Online (Sandbox Code Playgroud)

和我的play_it剧本

from playsound import playsound
import concurrent.futures

def alert():
    playsound('ss.mp3')


def PlayIt():
    with concurrent.futures.ThreadPoolExecutor() as exe:
        exe.map(alert, ???) # not sure what to insert here
Run Code Online (Sandbox Code Playgroud)

nne*_*neo 11

我不知道playsound它运行的线程有什么要求,但最简单、最容易做的事情可能就是生成一个线程来播放声音:

import threading
def alert():
    threading.Thread(target=playsound, args=('ss.mp3',), daemon=True).start()
Run Code Online (Sandbox Code Playgroud)

daemon=True这里将线程作为守护线程启动,这意味着它不会阻止程序退出。(在 Python 2 上,您可以使用 dot = threading.Thread(...); t.daemon = True; t.start()来代替。)