Playing sound C++ linux aplay : device or resource busy

  asynchronous, audio, c++, linux

Im trying to play a small audio (.wav) file whenever a face is detected in a camera using opencv in C++.

if (face_recognized) {

string str1= "aplay" ;
str1 = str1 + "-Dhw:0,3 alarm.wav" + " & ";
const char *command = str1.c_str();
system(command)
} 

Now whats happening is that whenever a person stays longer in front of the camera, the camera keeps detecting face and sound file keeps trying to play but due to device already busy playing the sound, its giving error on console. Ofcourse I can hear the alarm, but how to stop simultaneous playing of alarm when an alarm is already playing or how to make them wait before the sound file finishes.
This constant call to sound file play is slowing down the code also. How to fix this error and optimize the audio play so that it doesnt stress the cpu ?

Error :-

aplay : audio open error: Device or resource busy

Source: Windows Questions C++

LEAVE A COMMENT