Play sound asynchronously in Python

随声附和 提交于 2021-02-11 13:36:54

问题


I have a while loop for my cameras(with opencv) to take a photos when something moves. 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. 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

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

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

回答1:


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:

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. (On Python 2, you have do t = threading.Thread(...); t.daemon = True; t.start() instead.)



来源:https://stackoverflow.com/questions/59042397/play-sound-asynchronously-in-python

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