//------------------------------------------------------------------- // sinewave.cpp // // This program will play a pure sine wave tone for one second. // // programmer: ALLAN CRUSE // written on: 19 SEP 2005 //------------------------------------------------------------------- #include // for printf(), perror() #include // for open() #include // for exit() #include // for write(), close() #include // for sin() #include // for ioctl() #include #define SAMPLE_RATE 8000 #define NUM_SAMPLES SAMPLE_RATE #define TWO_PI (3.14159 * 2.0) unsigned char pulsecode[ NUM_SAMPLES ]; int main( int argc, char **argv ) { // generate the pulse-code modulation data double frequency = 220.0; // cycles-per-second double angle = (TWO_PI / SAMPLE_RATE) * frequency; int amplitude = 64, silence = 128; for (int sample = 0; sample < NUM_SAMPLES; sample++) { double x = angle * sample; double y = sin( x ) * amplitude; pulsecode[ sample ] = silence + (int)y; } // open the audio device and set its playback parameters int bits = 8, chns = 1, rate = SAMPLE_RATE; int dev = open( "/dev/audio", O_WRONLY ); if ( dev < 0 ) { perror( "/dev/audio" ); exit(1); } if (( ioctl( dev, SNDCTL_DSP_SETFMT, &bits ) < 0 ) ||( ioctl( dev, SNDCTL_DSP_CHANNELS, &chns ) < 0 ) ||( ioctl( dev, SNDCTL_DSP_SPEED, &rate ) < 0 )) { perror( "audio format not supported\n" ); exit(1); } // now playback the sound int morebytes = NUM_SAMPLES; unsigned char *pcm = pulsecode; while ( morebytes > 0 ) { int nbytes = write( dev, pcm, morebytes ); morebytes -= nbytes; pcm += nbytes; } close( dev ); // close the audio playback device }