-
Notifications
You must be signed in to change notification settings - Fork 307
Tips_CPlusPlus
You do not need to use any special bindings to use PortAudio in C++ code. The only difficulty most people have is creating a callback function. The best way to do that is to use a static function, which appears to the compiler a a normal C function, and have the static function call a non-static function. (You can assign a pointer to your class as the userData argument when creating a stream).
For example, your .h file might look like this:
class MyPortaudioClass
{
[snip]
int myMemberCallback(const void *input, void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags);
static int myPaCallback(
const void *input, void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
return ((MyPortaudioClass*)userData)
->myMemberCallback(input, output, frameCount, timeInfo, statusFlags);
}
[snip]
};
and your .cpp file might look like this:
int MyPortaudioClass::myMemberCallback(const void *input, void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags)
{
// Do what you need (having access to every part of MyPortaudioClass)
return paContinue;
}
Once that's setup, you can open your stream using "this" as your userData:
PaError pa_error = Pa_OpenStream(
[snip]...
&MyPortaudioClass::myPaCallback, // streamCallback
this); // userData
You could also just use a reference to your class in your static function like (make sure the static function is a member of the class so that you have access to "private" declared variables):
MyPortaudioClass* pThis = (MyPortaudioClass*)userData;
but this adds some complexity to the code.
This topic is covered on many C++ web sites, so try googling for the following terms: function pointer C++ static
Thanks to Robert Bielik for the sample code.