问题
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