As a small experimental piece of music, I am trying to program a song in the C standard. The code outputs a raw PCM file that can be imported into Audacity. At the moment, everything works as expected, but I ran into problems when trying to write each sample as 16 bits, and not the current 8-bit I use.
Until recording, the current sample is calculated as a float, and its boundaries are stored within the range of an 8-bit integer. It is then written as an 8-bit integer before repeating the process for the next sample. It works great and plays correctly. The problem arises when I try to write it as a 16-bit raw PCM file - I multiply the float by 256 and copy the result to an integer, after which I use fwrite to write the resulting 16-bit integer. This does not give the expected results when importing, which leads to a very distorted version of the expected.
I added the current code below, since the problem only occurs at the writing stage.
Working 8-bit code:
if (out<-127) {out=-128;} else if (out>126) {out=127;} putc(out,fo);
16-bit code does not work:
if (out<-127) {out=-128;} else if (out>126) {out=127;} pcm=out*256; fwrite(&pcm,2,1,fo);
I probably just missed something obvious, but I tried to work for hours. Thanks in advance!
source share