#include "portaudio.h"
Before we begin, it's important to realize that the callback is a delicate place. This is because some systems perform the callback in a special thread, or interrupt handler, and it is rarely treated the same as the rest of your code. In addition, if you want your audio to reach the speakers on time, you'll need to make sure whatever code you run in the callback runs quickly. What is safe or not safe will vary from platform to platform, but as a rule of thumb, don't do anything like allocating or freeing memory, reading or writing files, printf(), or anything else that might take an unbounded amount of time or rely on the OS or require a context switch. Ed: is this still true?: Also do not call any PortAudio functions in the callback except for Pa_StreamTime() and Pa_GetCPULoad().
Your callback function must return an int and accept the exact parameters specified in this typedef:
typedef int PaStreamCallback( const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) ;
typedef struct { float left_phase; float right_phase; } paTestData; /* This routine will be called by the PortAudio engine when audio is needed. It may called at interrupt level on some machines so don't do anything that could mess up the system like calling malloc() or free(). */ static int patestCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) { /* Cast data passed through stream to our structure. */ paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; unsigned int i; (void) inputBuffer; /* Prevent unused variable warning. */ for( i=0; i<framesPerBuffer; i++ ) { *out++ = data->left_phase; /* left */ *out++ = data->right_phase; /* right */ /* Generate simple sawtooth phaser that ranges between -1.0 and 1.0. */ data->left_phase += 0.01f; /* When signal reaches top, drop back down. */ if( data->left_phase >= 1.0f ) data->left_phase -= 2.0f; /* higher pitch so we can distinguish left and right. */ data->right_phase += 0.03f; if( data->right_phase >= 1.0f ) data->right_phase -= 2.0f; } return 0; }
Previous: PortAudio Tutorials | Next: Initializing PortAudio