/* convert to WAV audio encoding handles only 8000 Hz. 16-bit single channel data R. Perry, March 2014 */ #include #include #include #include #include #include "audio.h" /* global argv[0] for error messages */ char *progname; /* input buffer for encoding */ double *buf = NULL; int size = 0; int n = 0; int push( double s) { if( n == size) { int newsize = 1.5*size + 65536; if( newsize > 1048576) { fprintf( stderr, "%s: buffer limit reached\n", progname); return 1; } double *newbuf = realloc( buf, newsize*sizeof(double)); if( newbuf == NULL) { fprintf( stderr, "%s: realloc() failed\n", progname); exit(1); } size = newsize; buf = newbuf; } buf[n++] = s; return 0; } /* convert text/PCM samples to WAV file */ void do_encode( void) { double s; while( scanf( "%lf", &s) == 1) if( push(s)) break; if( n == 0) { fprintf( stderr, "%s: empty input\n", progname); exit(2); } int *data = malloc( n * sizeof(int)); if( data == NULL) { fprintf( stderr, "%s: malloc() failed\n", progname); exit(3); } double max = fabs( buf[0]); for( int i = 1; i < n; ++i) { double t = fabs( buf[i]); if( t > max) max = t; } if( max == 0) max = 1; for( int i = 0; i < n; ++i) { double t = 32767.0*(buf[i]/max); if( t > 0) t += 0.5; else t -= 0.5; data[i] = t; } write_wav( n, data, 8000); } int main( int argc, char *argv[]) { progname = argv[0]; do_encode(); return 0; }