如何在触发时在后台播放音频但仍运行代码

问题描述 投票:0回答:1

因此,每次满足 if 语句时,代码都会发送音频警报。但是,代码将暂停约 3 秒(音频文件长度),并暂停 While 循环,使 OpenCV 视频停止。 顺便说一句,我正在将其部署到 Flask 中。这是代码:

while True:
            ret, frame = self.video.read()
            results = self.model.track(frame)
            frame_result = results[0].plot()

            for r in results:
        
                boxes = r.boxes
                for box in boxes:
            
                    c = box.cls
                    if model.names[int(c)] == 'cell phone':
                        playsound('audio.mp3') #i want this to play in background while code is still runninng
            ret, jpeg = cv2.imencode('.jpg', frame_result)
            frame = jpeg.tobytes()
            yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

我在浏览时看到了线程和异步?唉,我仍然不熟悉如何在这种情况下实现它们。

python opencv asynchronous audio playsound
1个回答
0
投票

可以在后台运行音频而不停止主循环,您可以在以下条件下使用线程

import threading
from playsound import playsound
import cv2

def play_audio():
playsound('audio.mp3')

  while True:
   ret, frame = self.video.read()
   results = self.model.track(frame)
   frame_result = results[0].plot()

  for r in results:
    boxes = r.boxes
    for box in boxes:
        c = box.cls
        if model.names[int(c)] == 'cell phone':
            audio_thread = threading.Thread(target=play_audio)
            audio_thread.start()
            
  ret, jpeg = cv2.imencode('.jpg', frame_result)
  frame = jpeg.tobytes()
  yield (b'--frame\r\n'
         b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')'

根据我的说法,通过使用线程,play_audio函数将在单独的线程中运行,因此在播放音频时主循环不会停止。

© www.soinside.com 2019 - 2024. All rights reserved.