/* sound_write.c -- Write samples to a SoundStream. */ #include #include #include "sound.h" short encode_sample( double sample ) { unsigned short y, msb, lsb; /* Samples in AIFF and WAVE files are 16-bit signed. (y is a short to let me "/ 256" to get the msb.) This way of encoding doubles means that Writing ultra-quiet sounds produces non-silence in the file. Write zeroes, read back, get a DC offset. but also Read and write are symmetrical. Read -> write -> exact same integers. Write -> read -> centers of ranges of mapped doubles. Reading never produces absolute value > 1.0 (actually always <). Writing a sine function produces full-scale symmetrical output. */ if( sample >= 1.0 ) { y = 32767; } else if( sample < -1.0 ) { y = -32768; } else { /* Casting rounds towards zero, grr. */ y = ( sample + 1.0 ) * 32768.0; y -= 32768; } return( y ); } void sound_write_short( unsigned short y, SoundStream *pSS ) { unsigned short msb, lsb; msb = y / 256; lsb = y % 256; if( pSS->little_endian ) { putc( lsb, pSS->byte_stream ); putc( msb, pSS->byte_stream ); } else { putc( msb, pSS->byte_stream ); putc( lsb, pSS->byte_stream ); } } void write_sample( double sample, SoundStream *pSS ) { sound_write_short( encode_sample( sample ), pSS ); } void write_LR_short( short left, short right, SoundStream *pSS ) { sound_write_short( left, pSS ); sound_write_short( right, pSS ); } void write_LR( double left, double right, SoundStream *pSS ) { write_sample( left, pSS ); write_sample( right, pSS ); }