How to avoid audio lag using threading with OpenCV and Python?

359 Views Asked by At

I am implementing and alarm system with OpenCV and Python.

I have the following:

import cv2
import winsound
import threading

# Tracker and camera configuration
# ...


def beep():
    winsound.Beep(frequency=2500, duration=1000)


try:
    while True:
        # Grab frame from webcam
        # ...

        success, bbox = tracker.update(colorFrame)

        # Draw bounding box
        if success:
            # Tracking success
            (x, y, w, h) = [int(p) for p in bbox]
            cv2.rectangle(colorFrame, (x, y), (x + w, y + h), (0, 255, 0), 2, 1)
         
            if alarm_condition(x, y, w, h):   # if bbox coordinates are touching restricted area
                text = "Alarm"
                threading.Thread(beep())

        # Show images
        cv2.imshow('Color Frame', colorFrame)

        # Record if the user presses a key
        key = cv2.waitKey(1) & 0xFF

        # if the `q` key is pressed, break from the lop
        if key == ord("q"):
            break

finally:

    # cleanup the camera and close any open windows
    vid.release()
    cv2.destroyAllWindows()

The alarm detection is working fine. However, I tried to play a beep alarm sound in addition to the alarm text. However, when the person touches the restricted rectangle area, there is so much lag in the audio playing because it is played in every iteration if the person keeps touching the area.

I have read that threading could help, but I am not able to make it work.

1

There are 1 best solutions below

0
On

Your problem is that it is played continuously so thats why its lagging. You can do one thing, you can use datetime and check that if the sound is played recently and play if after a minute or something.

Example

import datetime
import threading
import winsound

def beep():
    winsound.Beep(frequency=2500, duration=1000)

recently = []
if(condition):
    c_time = datetime.datetime.now().strftime('%M')
    if not recently:
        recently.append(c_time)
        threading.Thread(beep())
    elif recently[-1] == c_time:
        continue
    else:
        recently.append(c_time)
        threading.Thread(beep())

Sorry if there's any mistake