I am looking at creating a WAV file
in C and have seen an example here.
This looks good, but I'm interested in adding two buffers to make the audio stereo (the possibility to have different sound in each ear). If I set the number of channels to two, the audio plays out of the left channel only (which apparently is right, as the left channel is the first channel). I have read I must interleave it with the right channel.
Unfortunately I haven't found much online to help create a stereo WAV.
write_little_endian((unsigned int)(data[i]),bytes_per_sample, wav_file);
I've tried to create a second buffer, with half the amplitude to see if I could interleave.
for (j=0; i<BUF_SIZE; i++) {
phase +=freq_radians_per_sample;
buffertwo[i] = (int)((amplitude/2) * sin(phase));;
}
write_wav("test.wav", BUF_SIZE, buffer, buffertwo, S_RATE);
(changing the function to take two short integer buffers)
And just doing
write_little_endian((unsigned int)(data[i]),bytes_per_sample, wav_file);
write_little_endian((unsigned int)(datatwo[i]),bytes_per_sample, wav_file);
But that does not work. That should in theory be interleaved.
So I decided to give it a shot for fun and here is an alternative way to write a .wav file. It generates a file called
sawtooth_test.wav
. When you play it back, you should hear two different frequencies from left and right. (Don't play it back too loud. Its annoying.)I think the problem is with the function "write_little_endian". You shouldn't need to use it on your laptop.
Endianness is architecture specific. The original example was likely for an Arduino microcontroller board. Arduino boards use Atmel microcontrollers which are big-endian. Thats why the code you cited explicitly needs to convert the 16-bit integers to little-endian format.
Your laptop on the other hand, uses x86 processors which are already little endian so no conversion is necessary. If you want robust portable code to convert endianness, you can use the function
htole16
in Linux. Lookup the man pages to learn more about this function.For a quick but non-portable fix, I would say just write out the entire 16bit value.
Also, I don't think you need to halve the amplitudes to go from mono to stereo.