Martin Tuskevicius
Martin Tuskevicius

Reputation: 2630

Determine the number of samples in audio buffer

I am writing a small program to perform real-time ambient noise removal using PortAudio. To do some of the necessary calculations (like Fourier transforms), I need to supply the sample data, but I also need to know exactly how many samples I am working with at a given time.

How can I determine the number of audio samples in a buffer?

When attempting to solve this myself, two variables seemed particularly relevant and useful, namely: the sampling rate and the frames per buffer. When I attempted to calculate the number of samples using the sampling rate, I ran into the issue of miscalculating the time between each callback invocation.

int ambienceCallback(const void * inputBuffer,
            void * outputBuffer,
            unsigned long framesPerBuffer,
            const PaStreamCallbackTimeInfo * timeInfo,
            PaStreamCallbackFlags statusFlags,
            void * userData)
{
    const SAMPLE * in = (const SAMPLE *) inputBuffer;
    PaStreamParameters * inputParameters = (PaStreamParameters *) userData;
    PaTime time = timeInfo->inputBufferAdcTime;
    int sampleCount = (time - callbackTime) * Pa_GetDeviceInfo(inputParameters->device)->defaultSampleRate;
    callbackTime = time;
    // extraneous ...
}

where callbackTime is a variable declared in the header file, and initialized upon starting the audio input stream.

// extraneous ...
error = Pa_StartStream(stream);
callbackTime = Pa_GetStreamTime(stream);
// extraneous ...

However, the calculated time would always be zero. As a result, I could not make my idea to simply multiply the sampling rate by the elapsed time work. The other variable, framesPerBuffer seemed like it could be useful for calculating the sample count if I could find how many samples were in a frame but, I flat out could not manage do that.

Again, how can I determine how many samples are in the buffer? As a disclaimer, I am new to audio programming. I am probably mixing up some terms or concepts, causing the more experienced to scratch their heads. (I apologize!)

Upvotes: 0

Views: 1382

Answers (1)

dmitri
dmitri

Reputation: 3294

Get the number of samples from the callback parameters! :)

framesPerBuffer gives you number of frames. A frame is a set of samples that occur simultaneously. For a stereo stream, a frame is two samples.

Timestamps are not useful for your purpose, e.g. Pa_GetStreamTime() returns the stream's current time in seconds. This resolution won't allow you to calculate the number of samples.

Upvotes: 1

Related Questions