//------------------------------------------------------------------- // makeA440.cpp // // Creates a .wav file for a sine-wave of frequency 440 HZ for // a duration of one second stereo at a sample-rate of 32-kHz, // suitable for playback on the Logitech Z305 stereo speakers. // // programmer: ALLAN CRUSE // written on: 28 SEP 2011 //------------------------------------------------------------------- #include // for printf(), perror() #include // for open() #include // for exit() #include // for lseek() #include // for sin() #define SAMPLE_RATE 32000 #define PI 3.14158625 typedef struct {short L, R; } Sample; const int size_Sample = sizeof( Sample ); Sample sample[ SAMPLE_RATE ]; int main( int argc, char **argv ) { //------------------------------------------------- // initialize the PCM data in the 'sample[]' array //------------------------------------------------- double pitch = 440.0; double volume = 20000.0; double inc = pitch * ((2.0 * PI) / (double)SAMPLE_RATE ); for (int i = 0; i < SAMPLE_RATE; i++) { double x = i * inc; double y = sin( x ); Sample s; s.L = y * volume; s.R = y * volume; sample[ i ] = s; } //----------------------------------------- // setup the .wav file's audio parameters //----------------------------------------- short formatTag = 1; short nChannels = 2; int samplesPerSec = SAMPLE_RATE; int avBytesPerSec = samplesPerSec * size_Sample; short blockAlignmnt = size_Sample; short bitsPerSample = 8 * blockAlignmnt; int dataChunkSize = SAMPLE_RATE * size_Sample; int fmt_ChunkSize = 16; int riffChunkSize = 4 + (8 + fmt_ChunkSize) + (8 + dataChunkSize); //----------------------------------- // write the PCM data in a .wav file //----------------------------------- // open the wav-file for writing char wavname[] = "a440.wav"; int wav = open( wavname, O_CREAT | O_RDWR | O_TRUNC, 0666 ); if ( wav < 0 ) { perror( wavname ); exit(1); } // output the RIFF chunk write( wav, "RIFF", 4 ); write( wav, &riffChunkSize, 4 ); write( wav, "WAVE", 4 ); // output the FORMAT chunk write( wav, "fmt ", 4 ); write( wav, &fmt_ChunkSize, 4 ); write( wav, &formatTag, 2 ); write( wav, &nChannels, 2 ); write( wav, &samplesPerSec, 4 ); write( wav, &avBytesPerSec, 4 ); write( wav, &blockAlignmnt, 2 ); write( wav, &bitsPerSample, 2 ); // write the DATA chunk write( wav, "data", 4 ); write( wav, &dataChunkSize, 4 ); char *wp = (char*)&sample[0]; int bytes_to_file = lseek( wav, 0L, SEEK_CUR ); int bytes_to_save = dataChunkSize; while ( bytes_to_save > 0 ) { int wbytes = write( wav, wp, bytes_to_save ); if ( wbytes < 0 ) break; bytes_to_save -= wbytes; bytes_to_file += wbytes; wp += wbytes; } close( wav ); printf( "Written %d bytes to \'%s\' \n", bytes_to_file, wavname ); //display_UHCI_registers(); printf( "\nDONE\n\n" ); }