Nguyen  Minh Binh
Nguyen Minh Binh

Reputation: 24443

How to loop a wav file using PortAudio?

Using PortAudio and SndFile to read WAV file content, writing directly into the output stream to play the sound is doable as in the sample wavplayer.c here, but does anyone know how to make the sound loops infinitely until we close the stream?

static
int
callback
    (const void                     *input
    ,void                           *output
    ,unsigned long                   frameCount
    ,const PaStreamCallbackTimeInfo *timeInfo
    ,PaStreamCallbackFlags           statusFlags
    ,void                           *userData
    )
{
    float           *out;
    callback_data_s *p_data = (callback_data_s*)userData;
    sf_count_t       num_read;

    out = (float*)output;
    p_data = (callback_data_s*)userData;

    /* clear output buffer */
    memset(out, 0, sizeof(float) * frameCount * p_data->info.channels);

    /* read directly into output buffer */
    num_read = sf_read_float(p_data->file, out, frameCount * p_data->info.channels);
    
    /*  If we couldn't read a full frameCount of samples we've reached EOF */
    if (num_read < frameCount)
    {
        return paComplete;
    }
    
    return paContinue;
}

Upvotes: 0

Views: 99

Answers (1)

Nguyen  Minh Binh
Nguyen Minh Binh

Reputation: 24443

at the same time posting the question here, I sought help from the code owners and they replied with a perfect solution:

As it's written, the stream will close at the end of the file but this doesn't have to happen. When the end of file is reached you could use sf_seek(p_data->file, 0, SF_SEEK_SET) to rewind back to the beginning of the file.

For creating a breaking event, you could add a member done int; to callback_data_s and initialize it to 0. Then when you'd like the break to occur you could set it to 1. Then inside the callback you just check whether p_data->done == 1 and exit.

Upvotes: 0

Related Questions