Python中异步播放声音

5
我有一个针对我的摄像头(使用OpenCV)的while循环,可以在有物体移动时拍照。我还想调用一个播放声音的函数。但当我调用并播放它时,它会停止循环来执行该函数。我尝试过使用ThreadPoolExecutor,但不知道如何将其与我的代码结合起来,因为我没有向函数传递任何参数,只是在循环中调用它。顺便说一下,如果从循环中出现多个something,我希望能够多次播放它(在执行时间内进行多次执行)。
摄像头脚本
from play_it import alert

while True:
    #do something in cv2
    if "something":
        alert() # Here it slowing the loop

以及我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

文档中得知:有一个可选的第二个参数block,默认设置为True。将其设置为False可以使函数异步运行。你尝试过playsound('ss.mp3', block=False)吗? - nneonneo
谢谢你的回答,我按照你说的尝试了,但是出现了这个错误:“block=False 不能在此平台上使用” - Andrejovic Andrej
值得一提的是:playsound现在似乎在所有平台上都支持block=False了 - Linux支持已经合并到https://github.com/TaylorSMarks/playsound/pull/72中。因此,不再需要使用线程。 - nneonneo
1个回答

10

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

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

在这里,daemon=True将线程作为守护线程启动,这意味着它不会阻止程序退出。(在Python 2中,您需要这样做 t = threading.Thread(...); t.daemon = True; t.start()。)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接