I wrote a program in c++ to generate a .wav file for an 800Hz sine wave (1 channel, 8-bit, 16000Hz sampling, 32000 samples so 2 seconds long), but when I play it or examine its spectrogram in Audacity, it has overtones.
I think the problem is with the algorithm converting the sine wave to PCM; I'm not sure where to put 'zero' displacement, at 127, or 127.5, or 128 etc.
char data[32000];
for (int j = 0; j < 32000; ++j)
{
data[j] = (char) (round(127 + 60 * (sin(2.0 * 3.14159265358979323846264338327950 * j / 20.0))));
}
and the file produced is this: output.wav
If necessary, here's the cpp file: wavwriter.cpp
Thanks!
EDIT 2: I have changed the char to an uint8_t
uint8_t data[32000];
for (int j = 0; j < 32000; ++j)
{
data[j] = round(127 + 60 * (sin(2.0 * 3.14159265358979323846264338327950 * j / 20.0)));
}
outfile.write((char *)&data[0], sizeof data);
outfile.close();
return true;
to avoid undefined behaviour. The same problem still applies.
char
signed or unsigned on your platform? – Adze(char)(127 + 60)
is? – Southwestward-69
– Southwestward(char)(187)
triggers undefined behavior. In practice, on Windows x86 and x64 it might be0xBB
, but you should not rely on that. Anyway, changingchar
touint8_t
everywhere along the serialization code and testing again should tell whether signedness is a problem or is it something else. – Southwestwarduint8_t
and removestatic_cast
. Applyreinterpret_cast
to data. – Southwestward