With the following code, I can read the a wave-file into a float array. However, the negative side of the wave ends up on the positive side so: -MAX -> 0 and "-0" -> MAX. I can't quite wrap my head around how to do this properly. I do realize the header portion of the wave may be more than 44 bytes long, but for this application it's not going to happen. I hope one of you fine folks can help me :-)
string filename;
getline(cin, filename);
ifstream wavFile(filename, ios::binary | ios::ate);
if (!wavFile)
cout << "error reading file\n";
int size = wavFile.tellg();
wavArray = new unsigned char[size];
wavFile.seekg(0, ios::beg);
wavFile.read((char *)wavArray, size);
wavFile.close();
int j = 1;
for (int i = 0; i < 262; i++)
{
unsigned int tmp = (wavArray[i + 44] | (wavArray[i + 45] << 8));
printf("%d : %f \n", k, (tmp / 32768.0));
j++;
i++;
}
The problem is your use of unsigned for the tmp
variable. So you never have a negative value in tmp
, even when the sample is negative. Try this
int16_t tmp = (wavArray[i + 44] | (wavArray[i + 45] << 8));
You should #include <cstdint>
to get the int16_t
type.