TheGainadl
TheGainadl

Reputation: 653

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?

Upvotes: 2

Views: 383

Answers (1)

Red
Red

Reputation: 27577

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

Upvotes: 1

Related Questions