简体   繁体   中英

How to play a wav file and make your code continue running in python?

I have this code that plays a video, and detects something on it. Whenever it detects something in the video, I want to hear something, here is the code:

import cv2
import os
video_capture = cv2.VideoCapture('video')
while True:
    _, frame = video_capture.read()
    found = detect_something(frame)
    if found :
        os.system("aplay 'alarm'")
    cv2.imshow('Video',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()

The problem is that, whenever it plays the alarm, the video freezes. I want the alarm to be played as a background sound. How can I do that?

What it needs is a tread:

import cv2
import os
from threading import Thread # Import Thread here
video_capture = cv2.VideoCapture('video')

def music(): # Define a function to go in the Thread
    os.system("aplay 'alarm'")

while True:
    _, frame = video_capture.read()
    found = detect_something(frame)
    if found :
        mus = Thread(target=music) # Create a Thread each time found
        mus.start() # Start the Thread as soon as created
    cv2.imshow('Video',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()

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