简体   繁体   中英

Play sound asynchronously in Python

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

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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