Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7655787
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T12:36:11+00:00 2026-05-31T12:36:11+00:00

I’m using opencv (for object recognition) combined with portaudio to play sounds based on

  • 0

I’m using opencv (for object recognition) combined with portaudio to play sounds based on video input. Essentially, my goal is to play a sine wave tone of a certain pitch/frequency at different rates. It works, but the outcome is very unpredictable. Sometimes audioplayback works (program runs slowly, but it works), other times no audio playback occurs. In a nutshell/flow this is what my program does:

Start webcam feed -> Acquire webcam image -> Choose Region in Image -> Return to video feed -> while(frame exists) -> Track object position -> Initialize Port Audio tools -> Play sound based on position -> Terminate Portaudio tools

I can’t seem to figure out why audio playback is inconsistent. Do you all have any tips? I’ve been reading around, and my thinking is that this a latency issue, but I’m really not experienced in the matter. When I use portaudio without opencv, no latency issues occur, so I know it has to do with combining the two. Any help is appreciated.

while (frame)
{
    cvCopyImage(frame, drawImg);

    // process
    track(frame);

    // get result
    CvRect r;
    float  confidence;
    bool   valid;
    /* getRoi tells us if the region being tracked on the screen
     * is the same region that we chose prior to entering this while loop
     */
    getRoi(&r, &confidence, &valid); 

    // show
    cvDrawRect(drawImg, cvPoint(r.x, r.y), 
        cvPoint(r.x + r.width - 1, r.y + r.height - 1),
        valid ? cvScalar(0, 255, 0) : cvScalar(0, 255, 255),
        2
    );
    writeLogo(drawImg,"USC-IRIS");
    int xpos = r.x;
    int ypos = r.y;



    cvShowImage("Tracking", drawImg);
    cout << "valid " << valid << endl;
    cout << "conf val " << confidence << endl;
    cout << "xpos, ypos " << xpos << ", " << ypos << endl;
            //If the region on the screen is the region we chose
            //then we should play specific sounds
    if(valid){

        sI->soundWrite(xpos, ypos);
        float freq = sI->getFreq();
        int amp = sI->getAmp();
        float pulse = sI->getPulse();

        switch(amp){
            case 0:
                //printf("Hear sound in both ears.\n");
                data.targetBalance = .5;
                break;
            case 1:
                //printf("Hear sound in left ear.\n");
                data.targetBalance = 0;
                break;
            case 2:
                //printf("Hear sound in right ear.\n");
                data.targetBalance = 1;
                break;
            default:
                //printf("Incorrect value for amp (left/right sound indicator)");
                data.targetBalance = .5;
                break;
        }



        err = Pa_Initialize(); //scan for available devices i.e. audio jack, headphones
        if(err != paNoError) {
            printf("init\n");
            goto error;
        }
        //open the sound stream for processing
        err =  Pa_OpenDefaultStream( &stream, 0, 2, paFloat32, SAMPLE_RATE, 
            256, patestCallback, &data ); //open the sound stream for processing
        if( err != paNoError ) {
            printf("open\n");
            goto error;
        }

        //start the stream (i.e. play sound) if no errors
        err = Pa_StartStream(stream);
        if(err != paNoError) {
            printf("start\n");
            goto error;
        }

        //check which ear(s) the sound should be played to



        //hold that tone for a certain amount of time (pulse*200 millisec)
        Pa_Sleep(pulse*200);
        cout << "pulse: " << pulse <<  endl << "freq: " << freq << endl;
        cout << "amp: " << amp << endl;

        //stop the stream (i.e. stop playing sound)
        err = Pa_StopStream(stream);
        if(err != paNoError) {
            printf("stop\n");
            goto error;
        }

        err = Pa_CloseStream( stream );
        if( err != paNoError ) {
            printf("close\n");
            goto error;
        }

        err = Pa_Terminate();
        if( err != paNoError ) {
            printf("term\n");
            goto error;
        }
    }
    int key = cvWaitKey(1);
    // write
    if (output_txt)
        fprintf(output_txt, "%d %d %d %d\n", r.x, r.y, r.width, r.height);
    if (output_avi)
        cvWriteFrame(output_avi, drawImg);

    // next
    if (key == 'q'||key=='Q')
        break;
    frame = cvQueryFrame(capture);
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T12:36:12+00:00Added an answer on May 31, 2026 at 12:36 pm

    It seems that the inconsistent audio playback was due to another segment of code not displayed in my question above. That incorrect code is below. I believe the error has to do with the first if statement and last forloop in this function. I think that the variable framesToCalc wasn’t being calculated correctly. Thus, the first for loop wasn’t placing any data into the outputBuffer/out variable. Then, at the end I’m zeroing out the remaining unused buffer space. Hence, no sound because of a zeroed buffer. My solution was to remove the first if else, and the last forloop. Additionally, I did the first for loop from i=0 to framesPerBuffer. Now it works perfectly.

    static int patestCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData){
    paTestData *data = (paTestData*)userData;
    SAMPLE_t *out = (SAMPLE_t *)outputBuffer;
    int i;
    int framesToCalc;
    int finished = 0;
    (void) inputBuffer; 
    int left_phase = data->left_phase;
    int right_phase = data->right_phase;
    
    
    if( data->framesToGo < framesPerBuffer )
    {
        framesToCalc = data->framesToGo;
        data->framesToGo = 0;
        finished = 1;
    }
    else
    {
        framesToCalc = framesPerBuffer;
        data->framesToGo -= framesPerBuffer;
    }
    
    for( i=0; i<framesToCalc; i++ )
    {
        if( data->currentBalance < data->targetBalance )
        {
            data->currentBalance += BALANCE_DELTA;
        }
        else if( data->currentBalance > data->targetBalance )
        {
            data->currentBalance -= BALANCE_DELTA;
        }
        left_phase += (LEFT_FREQ / SAMPLE_RATE);
        right_phase += (RIGHT_FREQ / SAMPLE_RATE);
        if( fabs(data->currentBalance - .5)  < .001){
            //left_phase += (double)(LEFT_FREQ / SAMPLE_RATE);
            if( left_phase > 1.0) left_phase -= 1.0;
    
            *out++ = DOUBLE_TO_SAMPLE( AMPLITUDE * sin( (left_phase * M_PI * 2. )));
    
            //right_phase += (double)(RIGHT_FREQ / SAMPLE_RATE);
            if( right_phase > 1.0) right_phase -= 1.0;
            *out++ = DOUBLE_TO_SAMPLE( AMPLITUDE * sin( (right_phase * M_PI * 2. )));
        }else{
            //left_phase += (double)(LEFT_FREQ / SAMPLE_RATE);
            if( left_phase > 1.0) left_phase -= 1.0;
    
            *out++ = DOUBLE_TO_SAMPLE( AMPLITUDE * sin( (left_phase * M_PI * 2. ))*(1.0 - data->currentBalance));
    
            //right_phase += (double)(RIGHT_FREQ / SAMPLE_RATE);
            if( right_phase > 1.0) right_phase -= 1.0;
            *out++ = DOUBLE_TO_SAMPLE( AMPLITUDE * sin( (right_phase * M_PI * 2. ))*data->currentBalance);
        }
    
    }
        // zero remainder of final buffer
        for( ; i<(int)framesPerBuffer; i++ )
        {
            *out++ = SAMPLE_ZERO; //left
            *out++ = SAMPLE_ZERO; //right
        }
        data->left_phase = left_phase;
        data->right_phase = right_phase;
        return finished;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I want use html5's new tag to play a wav file (currently only supported
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.