main.c (2992B)
1 /* 2 * This program uses the PortAudio Portable Audio Library and contains code adapted from PortAudio examples. 3 * Copyright (c) 1999–2000 Ross Bencina and Phil Burk 4 * Licensed under the MIT License – see licenses/portaudio.txt 5 */ 6 7 #include <stdio.h> 8 #include <math.h> 9 #include "portaudio.h" 10 #include "osc.h" 11 #include "dsp.h" 12 #include "control.h" 13 14 #define SAMPLE_RATE (44100) 15 #define FRAMES_PER_BUFFER (128) 16 17 static int audio_callback( 18 const void *inputBuffer, 19 void *outputBuffer, 20 unsigned long framesPerBuffer, 21 const PaStreamCallbackTimeInfo* timeInfo, 22 PaStreamCallbackFlags statusFlags, 23 void *userData 24 ) { 25 synthesizer *synth = (synthesizer*)userData; 26 float *out = (float*)outputBuffer; 27 28 // Prevent unused variable warnings 29 (void) timeInfo; (void) statusFlags; 30 (void) inputBuffer; 31 32 for (unsigned long i=0; i<framesPerBuffer; i++) { 33 float s = next_sample(synth); 34 35 s *= 0.2; 36 37 if (s > 1.0) s = 1.0; 38 if (s < -1.0) s = -1.0; 39 *out++ = s; 40 *out++ = s; 41 } 42 43 return paContinue; 44 } 45 46 static int run_app(synthesizer *synth) 47 { 48 PaStreamParameters outputParameters; 49 PaStream *stream = NULL; 50 PaError paerr; 51 52 paerr = Pa_Initialize(); 53 if( paerr != paNoError ) goto cleanup; 54 55 outputParameters.device = Pa_GetDefaultOutputDevice(); 56 if (outputParameters.device == paNoDevice) { 57 fprintf(stderr,"Error: No default output device.\n"); 58 paerr = paNoDevice; 59 goto cleanup; 60 } 61 62 /* stereo output */ 63 outputParameters.channelCount = 2; 64 /* 32 bit floating point output */ 65 outputParameters.sampleFormat = paFloat32; 66 outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; 67 outputParameters.hostApiSpecificStreamInfo = NULL; 68 69 paerr = Pa_OpenStream( 70 &stream, 71 NULL, /* no input */ 72 &outputParameters, 73 SAMPLE_RATE, 74 FRAMES_PER_BUFFER, 75 paClipOff, 76 audio_callback, 77 synth ); 78 if( paerr != paNoError ) goto cleanup; 79 80 paerr = Pa_StartStream( stream ); 81 if( paerr != paNoError ) goto cleanup; 82 83 // start the control interface and let the stream run until control_run() returns 84 int control_err = 0; 85 control_err = control_run(synth); 86 87 goto cleanup; 88 89 cleanup: 90 if (stream) { 91 Pa_StopStream( stream ); 92 Pa_CloseStream( stream ); 93 } 94 95 Pa_Terminate(); 96 97 if (paerr != paNoError) { 98 fprintf( stderr, "An error occurred while using the portaudio stream\n" ); 99 fprintf( stderr, "Error number: %d\n", paerr ); 100 fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( paerr ) ); 101 return 1; 102 } 103 104 return control_err; 105 } 106 107 int main(void) 108 { 109 synthesizer *synth = synth_create(SAMPLE_RATE); 110 if (!synth) return 1; 111 int err = run_app(synth); 112 synth_destroy(synth); 113 return err; 114 }