Wav File writing issue with int16 data

I am having an issue on writing a wav file with int16 data. For testing I made a file with sample [0]=-32768 then each sample increments on up to sample[65536] = 32767.
The issue is values greater than 16384 (+0.5f) are written one bit value too low.

sample[49152]=16384 (0.5f)
sample[49153]= should be 16385 (0.500031f) but is 16384 (0.5f)
sample[49154]= should be 16386 (0.500061f) but is 16385 (0.500031f)

The attached zip has a console app that reads the input file and compares it to what the values should be (in floats). It then writes the data from the file into a second file and compares it to what it should be.

Float32 data works with no issues.

WavFileTest.zip (118.4 KB)

Windows10, VS2017, JUCE Version 5.4.3

This explanation comes to mind: http://www.mega-nerd.com/libsndfile/FAQ.html#Q010

PS.: Shooting in the dark, as I‘m on mobile and thus unable to look at your code. It’s an interesting read regardless it’s relevance.

1 Like

I guess that make sense, surprising to me that all the error shows up at >0.5f. That being said, I should be able to add 1/(0x7fff) to sample for values > 0.5f before writing it to file and get the output values back. At this point I am only messing with the metadata.

This did work. The values read file the int16 file where the same as what was written.

There’s no need to convert it to float and back… Have you looked at WavAudioFormat::replaceMetadataInFile() ?

No, I missed that. Thanks. The on going vastness of JUCE.