简体   繁体   English

在 Python 中异步播放声音

[英]Play sound asynchronously in Python

I have a while loop for my cameras(with opencv) to take a photos when something moves.我的相机(使用opencv)有一个while loop ,可以在物体移动时拍照。 I would like to call a function to play a sound as well.我也想调用一个函数来播放声音。 But when I call and play it, it will stop looping for that execution time.但是当我调用并播放它时,它将在该执行时间内停止循环。 I tried ThreadPoolExecutor but had no idea how could I blend it with my code, because I'm not passing anything to the function.我尝试了ThreadPoolExecutor但不知道如何将它与我的代码混合,因为我没有向函数传递任何东西。 Just calling it from loop.只是从循环中调用它。 Btw.顺便提一句。 I would like to be able to play it multiple times (multiple executions in time of execution) if multiple something in code appears from loop我希望能够(在执行的时候多次执行)如果多个多次玩something在代码回路出现

camera script相机脚本

from play_it import alert

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

and my play_it script和我的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

I don't know what requirements playsound has for the thread it runs on, but the simplest and easiest thing to do is probably just to spawn off a thread to play the sound:我不知道playsound对它运行的线程有什么要求,但最简单和最容易做的事情可能只是产生一个线程来播放声音:

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

daemon=True here starts the thread as a daemon thread, meaning that it won't block the program from exiting. daemon=True此处将线程作为守护线程启动,这意味着它不会阻止程序退出。 (On Python 2, you have do t = threading.Thread(...); t.daemon = True; t.start() instead.) (在 Python 2 上,您可以使用t = threading.Thread(...); t.daemon = True; t.start()代替。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM