/* wav.c : PUBLIC DOMAIN - Jon Mayo - August 22, 2006 * - You may remove any comments you wish, modify this code any way you wish, * and distribute any way you wish.*/ /* simple WAV audio file exporter */ #include #include /* used for making temp variables in macros */ #define make_name2(x,y) x##y #define make_name(x,y) make_name2(x,y) #define var(x) make_name(x,__LINE__) /* WRite Little-Endian 32-bit value */ #define WR_LE32BIT(dest, offset, value) do { \ unsigned var(tmp)=value; \ (dest)[offset]=var(tmp)%256; \ (dest)[offset+1]=(var(tmp)/256)%256; \ (dest)[offset+2]=(var(tmp)/65536L)%256; \ (dest)[offset+3]=(var(tmp)/16777216L)%256; \ } while(0) /* WRite Little-Endian 16-bit value */ #define WR_LE16BIT(dest, offset, value) do { \ unsigned var(tmp)=value; \ (dest)[offset]=var(tmp)%256; \ (dest)[offset+1]=(var(tmp)/256)%256; \ } while(0) /* saves a single channel 16-bit sound file */ static int wav_save(const char *filename, short *data, unsigned nr_samples, unsigned sample_rate) { unsigned chunk_sz; FILE *f; unsigned i; unsigned char header[44] = { /* RIFF header */ 'R', 'I', 'F', 'F', /* 000 - chunk id 'RIFF' */ 0, 0, 0, 0, /* 004 - chunk size */ 'W', 'A', 'V', 'E', /* 008 - riff format 'WAVE' */ /* fmt sub-chunk */ 'f', 'm', 't', ' ', /* 012 - 'fmt ' sub-chunk */ 16, 0, 0, 0, /* 016 - sub-chunk size */ 1, 0, /* 020 - 1 = PCM (Linear) */ 1, 0, /* 022 - Number of channels */ 0, 0, 0, 0, /* 024 - Sample rate */ 0, 0, 0, 0, /* 028 - Byte rate */ 0, 0, /* 032 - Bytes per sample */ 16, 0, /* 034 - Bits per sample */ /* data sub-chunk */ 'd', 'a', 't', 'a', /* 036 - 'data' sub-chunk */ 0, 0, 0, 0, /* 040 - number of bytes for the data */ }; /* chunk size */ chunk_sz=sizeof header - 8 + nr_samples * 16/8; WR_LE32BIT(header, 4, chunk_sz); WR_LE32BIT(header, 24, sample_rate); WR_LE32BIT(header, 28, sample_rate*1*16/8); /* byte rate */ WR_LE16BIT(header, 32, 1 * 16/8); /* block alignment */ WR_LE32BIT(header, 40, nr_samples * 16/8); /* data length */ f=fopen(filename, "wb"); if(!f) { perror(filename); return 0; } if(fwrite(header, sizeof header, 1, f)!=1) { perror(filename); fclose(f); return 0; } for(i=0;i #define NR(x) (sizeof(x)/sizeof*(x)) int main() { /* fills it with sine-wave data */ short data[22050]; const unsigned sample_rate=44100; const double frequency=1000.; int i; for(i=0;i