Unable to play sound asynchronously in webcam opencv c++ (LINUX)

Im trying to play a sound in C++ opencv webcam.

What I have tried : Webcam in opencv,C++. It play a wav file but since ive added "&" , therefore it keeps playing several instances , rather than wait for the first playback to finish. Thus creating an overlapping echo effect.

What I want : The sound playback shouldnt halt/slow down webcam (it should be asynchronous). A mechanism to know if the sound is being played already, and wait for it to finish. The library or mechanism should work on linux.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <opencv2/opencv.hpp>
#include<iostream>
#include <future>

using namespace cv;
using namespace std;
Mat frame;

int play (string audio_file) { 
string str1= "aplay " ;
str1 = str1 + audio_file + " &";
const char *command = str1.c_str();
system(command);
}

int main()
{
    VideoCapture cap(1);
    cap >> frame;//get the first frame
    imshow("Video", frame);

    while (1)
    {
        cap >> frame;//capture second frame
        imshow("Video", frame);
        auto handle = std::async(std::launch::async, play , "Powerup5.wav");
        if (waitKey(30) >= 0)
            break;
    }
    return 0;
}


#Compiling

g++ cam_sound.cpp -lpthread `pkg-config --cflags --libs opencv` -o cam_sound
https://www.cplusplus.com/reference/future/future/valid/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int play (string audio_file) { 
  string str1= "aplay " ;
  str1 = str1 + audio_file;
  const char *command = str1.c_str();
  system(command);
  return 0;
}

int main()
{
    VideoCapture cap(1);
    cap >> frame;//get the first frame
    imshow("Video", frame);
    std::future<int> handle;
    bool first = true;

    while (1)
    {
        cap >> frame;//capture second frame
        imshow("Video", frame);
        // If this is the first time, or
        // the previous instance has finished and returned an async result, then...
        if ( first || handle.valid() ) {
            handle = std::async(std::launch::async, play , "Powerup5.wav");
            first = false;
        }
        if (waitKey(30) >= 0)
            break;
    }
    // you should do something with handle here
    return 0;
}


Using system() to do work is crusty. It might be the quickest way to get going, but it should only be an interim fix rather than a solution.

It would be better to make use of some code and say the ALSA sound library.
https://duckduckgo.com/?q=linux+sound+alsa+api+play+wav&atb=v296-1&ia=web
Topic archived. No new replies allowed.