//----------------------------------------------------------------------------- // name: Delayed.h // desc: sample file for Karplus Strong example (v2) // // Music 256a, Fall 2009, Stanford University // http://ccrma.stanford.edu/courses/256a-fall-2009/ //----------------------------------------------------------------------------- #include "RtAudio.h" #include #include #include #include using namespace std; #include "ksvoice.h" #define MY_PIE 3.14159265358979 #define MY_SRATE 44100 // max voices #define MAX_VOICES 10 // array KSVoice * g_voice[MAX_VOICES]; // buffer SAMPLE * g_theOtherBuffer = NULL; // callback int callme( char * buffer, int buffer_size, void * user_data ) { // cast to buffer SAMPLE * buffy = (SAMPLE *)buffer; // cast to voice pointer KSVoice ** voice = (KSVoice **)user_data; // zero out the output buffer memset( buffy, 0, buffer_size*sizeof(SAMPLE) ); for( int i = 0; i < MAX_VOICES; i++ ) { // synthesize voice[i]->synthesize( g_theOtherBuffer, buffer_size ); // accumulate for( int j = 0; j < buffer_size; j++ ) { buffy[j] += g_theOtherBuffer[j] / MAX_VOICES; } } return 0; } // get console input void getInput() { string command; static int which = 0; while( true ) { // read cin >> command; // check switch( command[0] ) { case 'q': // quit cerr << "bye!" << endl; return; default: // pluck cerr << "pluck: " << which << endl; g_voice[which++]->pluck(); which %= MAX_VOICES; break; } } } // entry point int main( int argc, char ** argv ) { // RtAudio pointer RtAudio * audio = NULL; // buffer size int buffer_size = 512; // create the RtAudio try { audio = new RtAudio( 0, // device number of output 1, // number of output channels 0, // device number for input 1, // number of input channels RTAUDIO_FLOAT64, // format MY_SRATE, // sample rate &buffer_size, // buffer size 8 // number of buffers ); } catch( RtError & err ) { err.printMessage(); exit(1); } // instantiate for( int i = 0; i < MAX_VOICES; i++ ) { g_voice[i] = new KSVoice(); g_voice[i]->init( 250 + 100 * (i+1) ); } // instantiate the other buffer g_theOtherBuffer = new SAMPLE[buffer_size]; // set the callback try { audio->setStreamCallback( &callme, g_voice ); audio->startStream(); } catch( RtError & err ) { // do stuff err.printMessage(); goto cleanup; } // something needs to happen here getInput(); // if we get here, then stop! try { audio->stopStream(); } catch( RtError & err ) { // do stuff err.printMessage(); } cleanup: audio->closeStream(); delete audio; return 0; }