void SoundDevice::close() { if(aInStream) CloseAudioStream( aInStream); aInStream = NULL; if(aOutStream) CloseAudioStream( aOutStream); aOutStream = NULL; }
int main(void) { int i; PaError err; PABLIO_Stream *aInStream; PABLIO_Stream *aOutStream; int index; printf("Full duplex sound test using PABLIO\n"); fflush(stdout); /* Open simplified blocking I/O layer on top of PortAudio. */ /* Open input first so it can start to fill buffers. */ err = OpenAudioStream( &aInStream, SAMPLE_RATE, SAMPLE_TYPE, (PABLIO_READ | PABLIO_STEREO) ); if( err != paNoError ) goto error; /* printf("opened input\n"); fflush(stdout); /**/ err = OpenAudioStream( &aOutStream, SAMPLE_RATE, SAMPLE_TYPE, (PABLIO_WRITE | PABLIO_STEREO) ); if( err != paNoError ) goto error; /* printf("opened output\n"); fflush(stdout); /**/ /* Process samples in the foreground. */ index = 0; for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i++ ) { /* Write old frame of data to output. */ /* samples[index][1] = (i&256) * (1.0f/256.0f); /* sawtooth */ WriteAudioStream( aOutStream, &samples[index][0], 1 ); /* Read one frame of data into sample array for later output. */ ReadAudioStream( aInStream, &samples[index][0], 1 ); index += 1; if( index >= NUM_ECHO_FRAMES ) index = 0; if( (i & 0xFFFF) == 0 ) printf("i = %d\n", i ); fflush(stdout); /**/ } CloseAudioStream( aOutStream ); CloseAudioStream( aInStream ); printf("R/W echo sound test complete.\n" ); fflush(stdout); return 0; error: fprintf( stderr, "An error occured while using PortAudio\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return -1; }
int main(int argc, char *argv[]) { PABLIO_Stream *outStream; double theta = 0.0; double theta1 = 0.0; double delta, delta1; double frequency1 = FREQUENCY1; double attenuation = 0.1; if (argc > 1) frequency1 = atof(argv[1]); if (argc > 2) attenuation = atof(argv[2]); delta = FREQUENCY * 2.0 * 3.1415 / (double) SAMPLE_RATE; delta1 = frequency1 * 2.0 * 3.1415 / (double) SAMPLE_RATE; OpenAudioStream(&outStream, SAMPLE_RATE, paFloat32, PABLIO_WRITE|PABLIO_MONO); int x; while(1) { // synthesize and output samples forever for(x= 0; x<NUM_FRAMES; x++) { // synthesize a buffer full of samples buffer[x] = sin(theta) * 0.9 + sin(theta1) * attenuation; theta+= delta; theta1+= delta1; } // blocking write provides flow control WriteAudioStream(outStream, buffer, NUM_FRAMES); } CloseAudioStream(outStream); }
UINT CFlvUtils::Clear() { HRESULT hr = S_OK; _tprintf(_T("CFlvUtils::Clear()\n")); // Free audio/video stream if (m_pAVStreamVideo) CloseVideoStream(); m_pAVStreamVideo = NULL; if (m_pAVStreamAudio) CloseAudioStream(); m_pAVStreamAudio = NULL; // Free the AV context streams & AV format context if (m_pAVFormatContext) { for (int i = 0; i < m_pAVFormatContext->nb_streams; i++) { av_freep(&m_pAVFormatContext->streams[i]); } av_free(m_pAVFormatContext); } m_pAVFormatContext = NULL; // Free AV output format if (m_pAVOutputFormat) av_free(m_pAVOutputFormat); m_pAVOutputFormat = NULL; return hr; }
PaError StartAudioStream( PASTREAMIO_Stream *aStream) { PaError err; err = Pa_StartStream( aStream->stream ); if( err != paNoError ) goto error; return paNoError; error: CloseAudioStream( aStream ); return err; }
static int start_audio(){ err = StartAudioStream(aOutStream); if( err != paNoError ) goto error; return err; error: CloseAudioStream( aOutStream ); printf( "An error occured while opening the portaudio stream\n" ); printf( "Error number: %d\n", err ); printf( "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
static int audio_close(void){ err = CloseAudioStream( aOutStream ); if( err != paNoError ) goto error; free(samples); return err; error: Pa_Terminate(); printf( "An error occured while closing the portaudio stream\n" ); printf( "Error number: %d\n", err ); printf( "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
int main(void) { int i,j; PaError err; PABLIO_Stream *aOutStream; printf("Generate sawtooth waves using PABLIO.\n"); fflush(stdout); /* Open simplified blocking I/O layer on top of PortAudio. */ err = OpenAudioStream( &aOutStream, SAMPLE_RATE, paFloat32, (PABLIO_WRITE | PABLIO_STEREO) ); if( err != paNoError ) goto error; /* Initialize oscillator phases. */ phases[0] = 0.0; phases[1] = 0.0; for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i += FRAMES_PER_BLOCK ) { /* Generate sawtooth waveforms in a block for efficiency. */ for( j=0; j<FRAMES_PER_BLOCK; j++ ) { /* Generate a sawtooth wave by incrementing a variable. */ phases[0] += PHASE_INCREMENT; /* The signal range is -1.0 to +1.0 so wrap around if we go over. */ if( phases[0] > 1.0f ) phases[0] -= 2.0f; samples[j][0] = phases[0]; /* On the second channel, generate a sawtooth wave a fifth higher. */ phases[1] += PHASE_INCREMENT * (3.0f / 2.0f); if( phases[1] > 1.0f ) phases[1] -= 2.0f; samples[j][1] = phases[1]; } /* Write samples to output. */ WriteAudioStream( aOutStream, samples, FRAMES_PER_BLOCK ); } CloseAudioStream( aOutStream ); printf("Sawtooth sound test complete.\n" ); fflush(stdout); return 0; error: fprintf( stderr, "An error occured while using PABLIO\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return -1; }
int main(void) { int i,j; PaError err; PABLIO_Stream *aOutStream; printf("Generate unsigned 8 bit sawtooth waves using PABLIO.\n"); fflush(stdout); /* Open simplified blocking I/O layer on top of PortAudio. */ err = OpenAudioStream( &aOutStream, SAMPLE_RATE, paUInt8, (PABLIO_WRITE | PABLIO_STEREO) ); if( err != paNoError ) goto error; /* Initialize oscillator phases to "ground" level for paUInt8. */ phases[0] = 128; phases[1] = 128; for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i += FRAMES_PER_BLOCK ) { /* Generate sawtooth waveforms in a block for efficiency. */ for( j=0; j<FRAMES_PER_BLOCK; j++ ) { /* Generate a sawtooth wave by incrementing a variable. */ phases[0] += 1; /* We don't have to do anything special to wrap when using paUint8 because * 8 bit arithmetic automatically wraps. */ samples[j][0] = phases[0]; /* On the second channel, generate a higher sawtooth wave. */ phases[1] += 3; samples[j][1] = phases[1]; } /* Write samples to output. */ WriteAudioStream( aOutStream, samples, FRAMES_PER_BLOCK ); } CloseAudioStream( aOutStream ); printf("Sawtooth sound test complete.\n" ); fflush(stdout); return 0; error: fprintf( stderr, "An error occured while using PABLIO\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return -1; }
int32 ad_close (ad_rec_t *handle) { if (handle->recording) if (ad_stop_rec(handle) < 0) return AD_ERR_GEN; if (CloseAudioStream( handle->stream ) < 0) return AD_ERR_GEN; free(handle); #ifdef AD_PA_DEBUG fprintf(stderr, "A/D Closed\n"); #endif return 0; }
int main(void) { int i, j, k, dlength, bufferIndex=0; float scale[8] = // E scale frequencies {164.81,184.99,207.65,220.00, 246.94,277.18,311.12,329.62}; short wg_l[DMAX], wg_r[DMAX]; // Waveguide delay lines short output; long temp; PABLIO_Stream *outStream; short buffer[NUM_FRAMES]; OpenAudioStream(&outStream, SAMPLE_RATE, paInt16, PABLIO_WRITE|PABLIO_MONO); for (j=0;j<8;j++) { // Play up the scale dlength = SAMPLE_RATE / scale[j] / 2; // Setup waveguide length for (k=0;k<=dlength/2;k++) { // Setup pluck temp = 20000 * (long) k * 2; temp /= dlength; wg_l[k] = temp; wg_l[dlength-k] = temp; wg_r[k] = temp; wg_r[dlength-k] = temp; } for (i=0;i<SAMPLE_RATE;i++) { // Play each note for 1 second temp = wg_l[0]; // stash delay outputs output = wg_r[0]; for (k=0;k<dlength-1;k++) { // Do delay lines wg_l[k] = wg_l[k+1]; wg_r[k] = wg_r[k+1]; } wg_l[dlength-1] = output*-0.99; // Do reflections wg_r[dlength-1] = -temp; buffer[bufferIndex++] = output; if (bufferIndex >= NUM_FRAMES){ WriteAudioStream(outStream, buffer, NUM_FRAMES); bufferIndex = 0; } } } if (bufferIndex > 0) WriteAudioStream(outStream, buffer, bufferIndex+1); CloseAudioStream(outStream); }
bool SoundDevice::pablio_input(bool state) { if(state && !aInStream) { err = OpenAudioStream( &aInStream, SAMPLE_RATE, PA_SAMPLE_TYPE, (PABLIO_READ | PABLIO_STEREO) ); if( err != paNoError) { Pa_Terminate(); error("error opening input sound device: %s",Pa_GetErrorText( err ) ); return false; } else info_input = Pa_GetDeviceInfo( Pa_GetDefaultInputDeviceID() ); } else if(!state && aInStream) { CloseAudioStream(aInStream); aInStream = NULL; info_input = NULL; } return true; }
void outputAudio( double sampleRate, double duration, Source& source, Sequencer& sequencer ){ static const int length = 64; float output[length]; double secondsPerVector = (double)length / sampleRate; sequencer.beginPlayback(); PABLIO_Stream *stream; OpenAudioStream( &stream, sampleRate, paFloat32, PABLIO_WRITE | PABLIO_MONO ); unsigned long count = (sampleRate / length) * duration; for( unsigned long i=0; i<count; ++i ){ std::fill_n( output, length, 0.f ); // zero output source.synthesize( output, length ); sequencer.update( secondsPerVector ); WriteAudioStream( stream, output, length ); } CloseAudioStream( stream ); }
int main(void) { int i; SAMPLE samples[SAMPLES_PER_FRAME * FRAMES_PER_BLOCK]; PaError err; PABLIO_Stream *aStream; printf("Full duplex sound test using PortAudio and RingBuffers\n"); fflush(stdout); /* Open simplified blocking I/O layer on top of PortAudio. */ err = OpenAudioStream( &aStream, SAMPLE_RATE, SAMPLE_TYPE, (PABLIO_READ_WRITE | PABLIO_STEREO) ); if( err != paNoError ) goto error; /* Process samples in the foreground. */ for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i += FRAMES_PER_BLOCK ) { /* Read one block of data into sample array from audio input. */ ReadAudioStream( aStream, samples, FRAMES_PER_BLOCK ); /* Write that same block of data to output. */ WriteAudioStream( aStream, samples, FRAMES_PER_BLOCK ); } CloseAudioStream( aStream ); printf("Full duplex sound test complete.\n" ); fflush(stdout); return 0; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return -1; }
static int open_audio(){ /* this will open one circular audio stream */ /* build on top of portaudio routines */ /* implementation based on file pastreamio.c */ int numSamples; int numBytes; int minNumBuffers; int numFrames; minNumBuffers = 2 * Pa_GetMinNumBuffers( FRAMES_PER_BUFFER, vi.rate ); numFrames = minNumBuffers * FRAMES_PER_BUFFER; numFrames = RoundUpToNextPowerOf2( numFrames ); numSamples = numFrames * vi.channels; numBytes = numSamples * sizeof(SAMPLE); samples = (SAMPLE *) malloc( numBytes ); /* store our latency calculation here */ latency_sec = (double) numFrames / vi.rate / vi.channels; printf( "Latency: %.04f\n", latency_sec ); err = OpenAudioStream( &aOutStream, vi.rate, PA_SAMPLE_TYPE, (PASTREAMIO_WRITE | PASTREAMIO_STEREO) ); if( err != paNoError ) goto error; return err; error: CloseAudioStream( aOutStream ); printf( "An error occured while opening the portaudio stream\n" ); printf( "Error number: %d\n", err ); printf( "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
/************************************************************ * Opens a PortAudio stream with default characteristics. * Allocates PABLIO_Stream structure. * */ PaError OpenAudioStream(PABLIO_Stream ** rwblPtr, const PaStreamParameters * inputParameters, const PaStreamParameters * outputParameters, double sampleRate, PaStreamFlags streamFlags, long samples_per_packet, int do_dual) { long bytesPerSample = 2; PaError err; PABLIO_Stream *aStream; long numFrames; //long numBytes; int c = 0; int channels = 1; if (!(inputParameters || outputParameters)) { return -1; } /* Allocate PABLIO_Stream structure for caller. */ aStream = (PABLIO_Stream *) malloc(sizeof(PABLIO_Stream)); switch_assert(aStream); memset(aStream, 0, sizeof(PABLIO_Stream)); if (inputParameters) { channels = inputParameters->channelCount; } else if (outputParameters) { channels = outputParameters->channelCount; } numFrames = RoundUpToNextPowerOf2(samples_per_packet * 5); aStream->bytesPerFrame = bytesPerSample; aStream->channelCount = channels; /* Initialize Ring Buffers */ if (inputParameters) { for (c = 0; c < channels; c++) { err = PABLIO_InitFIFO(&aStream->inFIFOs[c], numFrames, aStream->bytesPerFrame); if (err != paNoError) { goto error; } } aStream->has_in = 1; } if (outputParameters) { for (c = 0; c < channels; c++) { err = PABLIO_InitFIFO(&aStream->outFIFOs[c], numFrames, aStream->bytesPerFrame); if (err != paNoError) { goto error; } } aStream->has_out = 1; } /* Open a PortAudio stream that we will use to communicate with the underlying * audio drivers. */ aStream->do_dual = do_dual; if (aStream->do_dual) { err = Pa_OpenStream(&aStream->istream, inputParameters, NULL, sampleRate, samples_per_packet, streamFlags, iblockingIOCallback, aStream); if (err != paNoError) { goto error; } err = Pa_OpenStream(&aStream->ostream, NULL, outputParameters, sampleRate, samples_per_packet, streamFlags, oblockingIOCallback, aStream); if (err != paNoError) { goto error; } } else { err = Pa_OpenStream(&aStream->iostream, inputParameters, outputParameters, sampleRate, samples_per_packet, streamFlags, ioblockingIOCallback, aStream); } if (err != paNoError) { goto error; } if (aStream->do_dual) { err = Pa_StartStream(aStream->istream); if (err != paNoError) { goto error; } err = Pa_StartStream(aStream->ostream); if (err != paNoError) { goto error; } } else { err = Pa_StartStream(aStream->iostream); } if (err != paNoError) { goto error; } *rwblPtr = aStream; switch_yield(500000); return paNoError; error: CloseAudioStream(aStream); *rwblPtr = NULL; return err; }
static void *SWITCH_THREAD_FUNC read_stream_thread(switch_thread_t *thread, void *obj) { portaudio_stream_source_t *source = obj; portaudio_stream_context_t *cp; int samples = 0; int bused, bytesToWrite; switch_mutex_lock(globals.mutex); globals.threads++; switch_mutex_unlock(globals.mutex); if (!source->prebuf) { source->prebuf = DEFAULT_PREBUFFER_SIZE; } switch_mutex_lock(globals.mutex); switch_core_hash_insert(globals.source_hash, source->sourcename, source); switch_mutex_unlock(globals.mutex); switch_thread_rwlock_create(&source->rwlock, source->pool); if (engage_device(source, 0) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, " Dev %d cant be engaged !\n", (int) source->sourcedev); } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, " Dev %d engaged at %d rate!\n", (int) source->sourcedev, (int) source->rate); if (globals.running && !source->stopped) { source->ready = 1; if (!source->audio_stream) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No Audio Stream wops!\n"); source->stopped = 0; source->ready = 0; } else { while (globals.running && !source->stopped) { samples = 0; switch_mutex_lock(source->device_lock); samples = ReadAudioStream(source->audio_stream, source->databuf, source->read_codec.implementation->samples_per_packet, 0, &source->timer); switch_mutex_unlock(source->device_lock); if (samples) { bytesToWrite = source->samples; if (samples < bytesToWrite) { bytesToWrite = samples; } bytesToWrite *= source->audio_stream->bytesPerFrame; if (source->total) { switch_mutex_lock(source->mutex); for (cp = source->context_list; cp; cp = cp->next) { switch_mutex_lock(cp->audio_mutex); bused = switch_buffer_inuse(cp->audio_buffer); if (bused > source->samples * 768) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Leaking stream handle! [%s() %s:%d] %d used %d max\n", cp->func, cp->file, cp->line, (int) bused, (int) (source->samples * 768)); switch_buffer_zero(cp->audio_buffer); } else { switch_buffer_write(cp->audio_buffer, source->databuf, bytesToWrite); } switch_mutex_unlock(cp->audio_mutex); } switch_mutex_unlock(source->mutex); } } } } } } source->ready = 0; switch_mutex_lock(globals.mutex); switch_core_hash_delete(globals.source_hash, source->sourcename); switch_mutex_unlock(globals.mutex); switch_thread_rwlock_wrlock(source->rwlock); switch_thread_rwlock_unlock(source->rwlock); switch_mutex_lock(source->device_lock); CloseAudioStream(source->audio_stream); if (switch_core_codec_ready(&source->read_codec)) { switch_core_codec_destroy(&source->read_codec); switch_core_codec_destroy(&source->write_codec); } if (switch_core_codec_ready(&source->write_codec)) { switch_core_codec_destroy(&source->write_codec); } switch_mutex_unlock(source->device_lock); switch_core_destroy_memory_pool(&source->pool); switch_mutex_lock(globals.mutex); globals.threads--; switch_mutex_unlock(globals.mutex); switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, " thread ending succesfully !\n"); switch_thread_exit(thread, SWITCH_STATUS_SUCCESS); return NULL; }
/************************************************************ * Opens a PortAudio stream with default characteristics. * Allocates PABLIO_Stream structure. * * flags parameter can be an ORed combination of: * PABLIO_READ, PABLIO_WRITE, or PABLIO_READ_WRITE */ PaError OpenAudioStream( PABLIO_Stream **rwblPtr, double sampleRate, PaSampleFormat format, int inchannels, int outchannels, int framesperbuf, int nbuffers, int indeviceno, int outdeviceno) /* MSP */ { long bytesPerSample; long doRead = 0; long doWrite = 0; PaError err; PABLIO_Stream *aStream; long minNumBuffers; long numFrames; //#ifdef PA19 // PaStreamParameters instreamparams, outstreamparams; /* MSP */ //#endif /* fprintf(stderr, "open %lf fmt %d flags %d ch: %d fperbuf: %d nbuf: %d devs: %d %d\n", sampleRate, format, flags, nchannels, framesperbuf, nbuffers, indeviceno, outdeviceno); */ if (indeviceno < 0) /* MSP... */ { //#ifdef PA19 // indeviceno = Pa_GetDefaultInputDevice(); //#else indeviceno = Pa_GetDefaultInputDeviceID(); //#endif fprintf(stderr, "using default input device number: %d\n", indeviceno); } if (outdeviceno < 0) { //#ifdef PA19 // outdeviceno = Pa_GetDefaultOutputDevice(); //#else outdeviceno = Pa_GetDefaultOutputDeviceID(); //#endif fprintf(stderr, "using default output device number: %d\n", outdeviceno); } /* fprintf(stderr, "nchan %d, flags %d, bufs %d, framesperbuf %d\n", nchannels, flags, nbuffers, framesperbuf); */ /* ...MSP */ /* Allocate PABLIO_Stream structure for caller. */ aStream = (PABLIO_Stream *) malloc( sizeof(PABLIO_Stream) ); if( aStream == NULL ) return paInsufficientMemory; memset( aStream, 0, sizeof(PABLIO_Stream) ); /* Determine size of a sample. */ bytesPerSample = Pa_GetSampleSize( format ); if( bytesPerSample < 0 ) { fprintf(stderr, "error bytes per sample: %i\n", bytesPerSample); err = (PaError) bytesPerSample; goto error; } aStream->insamplesPerFrame = inchannels; /* MSP */ aStream->inbytesPerFrame = bytesPerSample * aStream->insamplesPerFrame; aStream->outsamplesPerFrame = outchannels; aStream->outbytesPerFrame = bytesPerSample * aStream->outsamplesPerFrame; /* Initialize PortAudio */ err = Pa_Initialize(); if( err != paNoError ) goto error; //#ifdef PA19 // numFrames = nbuffers * framesperbuf; /* ...MSP */ // instreamparams.device = indeviceno; /* MSP... */ // instreamparams.channelCount = inchannels; // instreamparams.sampleFormat = format; // instreamparams.suggestedLatency = nbuffers*framesperbuf/sampleRate; // instreamparams.hostApiSpecificStreamInfo = 0; // outstreamparams.device = outdeviceno; // outstreamparams.channelCount = outchannels; // outstreamparams.sampleFormat = format; // outstreamparams.suggestedLatency = nbuffers*framesperbuf/sampleRate; // outstreamparams.hostApiSpecificStreamInfo = 0; /* ... MSP */ //#else /* Warning: numFrames must be larger than amount of data processed per interrupt inside PA to prevent glitches. */ /* MSP */ minNumBuffers = Pa_GetMinNumBuffers(framesperbuf, sampleRate); if (minNumBuffers > nbuffers) fprintf(stderr, "warning: number of buffers %d less than recommended minimum %d\n", (int)nbuffers, (int)minNumBuffers); //#endif numFrames = nbuffers * framesperbuf; /* fprintf(stderr, "numFrames %d\n", numFrames); */ /* Initialize Ring Buffers */ doRead = (inchannels != 0); doWrite = (outchannels != 0); if(doRead) { err = PABLIO_InitFIFO( &aStream->inFIFO, numFrames, aStream->inbytesPerFrame ); if( err != paNoError ) { fprintf(stderr, "error doRead PABLIO_InitFIFO \n"); goto error; } } if(doWrite) { long numBytes; err = PABLIO_InitFIFO( &aStream->outFIFO, numFrames, aStream->outbytesPerFrame ); if( err != paNoError ) { fprintf(stderr, "error doWrite PABLIO_InitFIFO \n"); goto error; } /* Make Write FIFO appear full initially. */ numBytes = RingBuffer_GetWriteAvailable( &aStream->outFIFO ); RingBuffer_AdvanceWriteIndex( &aStream->outFIFO, numBytes ); } /* Open a PortAudio stream that we will use to communicate with the underlying * audio drivers. */ //#ifdef PA19 // err = Pa_OpenStream( // &aStream->stream, // (doRead ? &instreamparams : 0), /* MSP */ // (doWrite ? &outstreamparams : 0), /* MSP */ // sampleRate, // framesperbuf, /* MSP */ // paNoFlag, /* MSP -- portaudio will clip for us */ // blockingIOCallback, // aStream ); //#else // err = Pa_OpenStream( // &aStream->stream, // (doRead ? indeviceno : paNoDevice), /* MSP */ // (doRead ? aStream->insamplesPerFrame : 0 ), // format, // NULL, // (doWrite ? outdeviceno : paNoDevice), /* MSP */ // (doWrite ? aStream->outsamplesPerFrame : 0 ), // format, // NULL, // sampleRate, // framesperbuf, /* MSP */ // nbuffers, /* MSP */ // paNoFlag, /* MSP -- portaudio will clip for us */ // blockingIOCallback, // aStream ); // #endif PortAudioStream *stream; err = Pa_OpenDefaultStream( stream, 0, 2, paFloat32, 44100, 256, 0, blockingIOCallback, stream ); if( err != paNoError ){ fprintf(stderr, "error Pa_OpenStream \n"); goto error; } err = Pa_StartStream( aStream->stream ); if( err != paNoError ) /* MSP */ { fprintf(stderr, "Pa_StartStream failed; closing audio stream...\n"); CloseAudioStream( aStream ); goto error; } *rwblPtr = aStream; return paNoError; error: *rwblPtr = NULL; return err; }
int main(int argc, char* argv[]) { unsigned char TuneSelection; unsigned char CurrentOctave; unsigned char ScriptIndex; unsigned char BassDrumIsOn; unsigned short BassDrumPointerIncrement; unsigned char BassDrumDurationCount; unsigned short BassDrumOutput; unsigned char CurrentNoteEvent; unsigned char NoteDurationCount; unsigned char NoteIndex; unsigned short NotePointerIncrement; unsigned short NoteWavePointer; unsigned short NoteAndBDOutput; unsigned char NoteSynthOutput; unsigned short TempoCounter; unsigned short OverFlow; unsigned char *WaveRAM; unsigned char WaveINDEX; unsigned char temp1 = 255; signed char temp2; short buffer[NUM_FRAMES]; PABLIO_Stream *outStream; if (argc != 2){ //printf("RockGuitar: Needs number 0-5\n"); exit; } temp2 = temp1; //wave table data for note synthesizer has the routine variables as its origin WaveRAM = &TuneSelection; OpenAudioStream(&outStream, SAMPLE_RATE, paInt16, PABLIO_WRITE|PABLIO_MONO); printf("Starting Synthesis!\n"); //client input, tune selector Jukebox TuneSelection = (unsigned char) atoi (argv[1]); printf("Selected Tune Script is %d\n",TuneSelection); //first time initialization CurrentOctave = 3; //octave state ScriptIndex = 0; //index to Tune script elements BassDrumIsOn = 0xff; //0xff = True, 0x00 = False BassDrumPointerIncrement = 0x07ff; //pitch for first bass drum event BassDrumDurationCount = 0x30; //duration for Bass Drum event CurrentNoteEvent = TuneScripts[TuneSelection][ScriptIndex++]; //prime pump, Sequencer gets first script element while(CurrentNoteEvent != 0xff){ //0xff is the end of script element if( ((CurrentNoteEvent & 0xf0)) == 0xf0){ // control element only octave is currently defined if( (CurrentNoteEvent & 0x0f) < 8){ // if note event CurrentOctave = CurrentNoteEvent & 0x0f; CurrentOctave = 7 - CurrentOctave; //invert it no division for top octave } } else { // note event, set it up and synthesize //number of ticks for this note event NoteDurationCount = Durations[ (CurrentNoteEvent & 0x0f)]; NoteIndex = (CurrentNoteEvent&0xf0)>>4; NotePointerIncrement = PitchIncrements[NoteIndex] >> CurrentOctave; while(NoteDurationCount){ //synthesis loop|PABLIO_MONO //synthesize bass drum BassDrumSynthesizer(&BassDrumPointerIncrement,&BassDrumOutput, &BassDrumIsOn); NoteAndBDOutput = BassDrumOutput; //FuzzGuitar tone generator NoteWavePointer += NotePointerIncrement; WaveINDEX = NoteWavePointer >> 8; NoteSynthOutput = *(WaveRAM+(WaveINDEX)); //power of two mixing NoteAndBDOutput += NoteSynthOutput >> 1; //write 8 bit unsigned raw Output to file for 6000 kHz playback sampling rate buffer[0] = (short)((NoteAndBDOutput - 0x7F)<<8); WriteAudioStream(outStream, buffer, 1); //scale tick to provide tempo control OverFlow = TempoCounter; TempoCounter += 0x0301; if(TempoCounter < OverFlow){ //OverFlow overflowed so a tick has occurred if(--BassDrumDurationCount == 0){ //time for new bass drum BassDrumDurationCount = 0x30; BassDrumIsOn = 0xFF; BassDrumPointerIncrement = 0x07FF; } //2 tick separation of each note event if(NoteDurationCount == 2) NotePointerIncrement = 0; NoteDurationCount--; } } }// note event, set it up and synthesize //get next script element CurrentNoteEvent = TuneScripts[TuneSelection][ScriptIndex++]; } //end of CurrentNoteEvent != 0xff CloseAudioStream(outStream); return 0; }
/************************************************************ * Opens a PortAudio stream with default characteristics. * Allocates PABLIO_Stream structure. * * flags parameter can be an ORed combination of: * PABLIO_READ, PABLIO_WRITE, or PABLIO_READ_WRITE */ PaError OpenAudioStream( PABLIO_Stream **rwblPtr, double sampleRate, PaSampleFormat format, int inchannels, int outchannels, int framesperbuf, int nbuffers, int indeviceno, int outdeviceno) /* MSP */ { long bytesPerSample; long doRead = 0; long doWrite = 0; PaError err; PABLIO_Stream *aStream; long numFrames; PaStreamParameters instreamparams, outstreamparams; /* MSP */ /* fprintf(stderr, "open %lf fmt %d flags %d ch: %d fperbuf: %d nbuf: %d devs: %d %d\n", sampleRate, format, flags, nchannels, framesperbuf, nbuffers, indeviceno, outdeviceno); */ if (indeviceno < 0) /* MSP... */ { indeviceno = Pa_GetDefaultInputDevice(); fprintf(stderr, "using default input device number: %d\n", indeviceno); } if (outdeviceno < 0) { outdeviceno = Pa_GetDefaultOutputDevice(); fprintf(stderr, "using default output device number: %d\n", outdeviceno); } /* fprintf(stderr, "nchan %d, flags %d, bufs %d, framesperbuf %d\n", nchannels, flags, nbuffers, framesperbuf); */ /* ...MSP */ /* Allocate PABLIO_Stream structure for caller. */ aStream = (PABLIO_Stream *) malloc( sizeof(PABLIO_Stream) ); if( aStream == NULL ) return paInsufficientMemory; memset( aStream, 0, sizeof(PABLIO_Stream) ); /* Determine size of a sample. */ bytesPerSample = Pa_GetSampleSize( format ); if( bytesPerSample < 0 ) { err = (PaError) bytesPerSample; goto error; } aStream->insamplesPerFrame = inchannels; /* MSP */ aStream->inbytesPerFrame = bytesPerSample * aStream->insamplesPerFrame; aStream->outsamplesPerFrame = outchannels; aStream->outbytesPerFrame = bytesPerSample * aStream->outsamplesPerFrame; /* Initialize PortAudio */ err = Pa_Initialize(); if( err != paNoError ) goto error; numFrames = nbuffers * framesperbuf; /* ...MSP */ instreamparams.device = indeviceno; /* MSP... */ instreamparams.channelCount = inchannels; instreamparams.sampleFormat = format; instreamparams.suggestedLatency = nbuffers*framesperbuf/sampleRate; instreamparams.hostApiSpecificStreamInfo = 0; outstreamparams.device = outdeviceno; outstreamparams.channelCount = outchannels; outstreamparams.sampleFormat = format; outstreamparams.suggestedLatency = nbuffers*framesperbuf/sampleRate; outstreamparams.hostApiSpecificStreamInfo = 0; /* ... MSP */ numFrames = nbuffers * framesperbuf; /* fprintf(stderr, "numFrames %d\n", numFrames); */ /* Initialize Ring Buffers */ doRead = (inchannels != 0); doWrite = (outchannels != 0); if(doRead) { err = PABLIO_InitFIFO( &aStream->inFIFO, numFrames, aStream->inbytesPerFrame ); if( err != paNoError ) goto error; } if(doWrite) { long numBytes; err = PABLIO_InitFIFO( &aStream->outFIFO, numFrames, aStream->outbytesPerFrame ); if( err != paNoError ) goto error; /* Make Write FIFO appear full initially. */ numBytes = sys_ringbuf_GetWriteAvailable( &aStream->outFIFO ); sys_ringbuf_AdvanceWriteIndex( &aStream->outFIFO, numBytes ); } /* Open a PortAudio stream that we will use to communicate with the underlying * audio drivers. */ err = Pa_OpenStream( &aStream->stream, (doRead ? &instreamparams : 0), /* MSP */ (doWrite ? &outstreamparams : 0), /* MSP */ sampleRate, framesperbuf, /* MSP */ paNoFlag, /* MSP -- portaudio will clip for us */ blockingIOCallback, aStream ); if( err != paNoError ) goto error; err = Pa_StartStream( aStream->stream ); if( err != paNoError ) /* MSP */ { fprintf(stderr, "Pa_StartStream failed; closing audio stream...\n"); CloseAudioStream( aStream ); goto error; } *rwblPtr = aStream; return paNoError; error: *rwblPtr = NULL; return err; }
int main(int argc, char *argv[]) { PABLIO_Stream *outStream; double theta = 0.0; double delta = 2.0 * 3.1415 / (double)SAMPLE_RATE; double frequency, attenuation = 1.0; char scale = '\0'; int x,y; frequency = 440.0; // default frequency double power = pow(2., 1./12.); // 12th root of 2 double pythag = 0.0; double cents, oldcents = 0.0; switch(argc) { case 1: break; case 2: if (argv[1][0]=='-') scale = argv[1][1]; break; default: printf("usage: %s [-h(armonic),p(ythagorean)]\n", argv[1]); exit(-1); } OpenAudioStream(&outStream, SAMPLE_RATE, paFloat32, PABLIO_WRITE|PABLIO_MONO); while(1) { // synthesize and output samples forever for(y= 0; y<26; y++) { for(x= 0; x<NUM_FRAMES; x++) { // synthesize a buffer full of samples buffer[x] = attenuation * sin(theta); theta += frequency * delta; } // blocking write provides flow control WriteAudioStream(outStream, buffer, NUM_FRAMES); cents = 1200. * log(frequency/440.) / log(2.); printf("note: %-2s frequency: %7.3f cents: %8.3f step: %7.3f\n",strings[y<13?y:25-y],frequency,cents,cents-oldcents); oldcents = cents; if (y < 12) if (scale == 'h') frequency = 440. * harmonics[y+1]; else if (scale == 'p') { pythag = (pythag <= 5 ? pythag + 7 : pythag - 5); frequency = 440. * pow(3./2., pythag); // 3/2 to the 7th while (frequency > 893.0) frequency /= 2.; } else frequency *= power; else if (y > 12 && y < 25) if (scale == 'h') frequency = 440.0 * harmonics[24-y]; else if (scale == 'p') { pythag = (pythag < 7 ? pythag + 5 : pythag - 7); frequency = 440. * pow(3./2., pythag); // 3/2 to the 7th while (frequency > 893.0) frequency /= 2.; } else frequency /= power; } } CloseAudioStream(outStream); }
/************************************************************ * Opens a PortAudio stream with default characteristics. * Allocates PASTREAMIO_Stream structure. * * flags parameter can be an ORed combination of: * PABLIO_WRITE, * and either PABLIO_MONO or PABLIO_STEREO */ PaError OpenAudioStream( PASTREAMIO_Stream **rwblPtr, double sampleRate, PaSampleFormat format, long flags ) { long bytesPerSample; long doWrite = 0; PaError err; PASTREAMIO_Stream *aStream; long minNumBuffers; long numFrames; /* Allocate PASTREAMIO_Stream structure for caller. */ aStream = (PASTREAMIO_Stream *) malloc( sizeof(PASTREAMIO_Stream) ); if( aStream == NULL ) return paInsufficientMemory; memset( aStream, 0, sizeof(PASTREAMIO_Stream) ); /* Determine size of a sample. */ bytesPerSample = Pa_GetSampleSize( format ); if( bytesPerSample < 0 ) { err = (PaError) bytesPerSample; goto error; } aStream->samplesPerFrame = ((flags&PASTREAMIO_MONO) != 0) ? 1 : 2; aStream->bytesPerFrame = bytesPerSample * aStream->samplesPerFrame; /* Initialize PortAudio */ err = Pa_Initialize(); if( err != paNoError ) goto error; /* Warning: numFrames must be larger than amount of data processed per interrupt * inside PA to prevent glitches. Just to be safe, adjust size upwards. */ minNumBuffers = 2 * Pa_GetMinNumBuffers( FRAMES_PER_BUFFER, sampleRate ); numFrames = minNumBuffers * FRAMES_PER_BUFFER; numFrames = RoundUpToNextPowerOf2( numFrames ); /* Initialize Ring Buffer */ doWrite = ((flags & PASTREAMIO_WRITE) != 0); if(doWrite) { err = PASTREAMIO_InitFIFO( &aStream->outFIFO, numFrames, aStream->bytesPerFrame ); if( err != paNoError ) goto error; /* Make Write FIFO appear full initially. numBytes = RingBuffer_GetWriteAvailable( &aStream->outFIFO ); RingBuffer_AdvanceWriteIndex( &aStream->outFIFO, numBytes );*/ } /* Open a PortAudio stream that we will use to communicate with the underlying * audio drivers. */ err = Pa_OpenStream( &aStream->stream, paNoDevice, 0 , format, NULL, Pa_GetDefaultOutputDeviceID() , aStream->samplesPerFrame , format, NULL, sampleRate, FRAMES_PER_BUFFER, minNumBuffers, paClipOff, /* we won't output out of range samples so don't bother clipping them */ audioIOCallback, aStream ); if( err != paNoError ) goto error; *rwblPtr = aStream; return paNoError; error: CloseAudioStream( aStream ); *rwblPtr = NULL; return err; }