Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 526
Andrejovic Andrej Avatar asked Aug 31 '26 06:08

Andrejovic Andrej


1 Answers

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

like image 181
nneonneo Avatar answered Sep 02 '26 21:09

nneonneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!