Write int16_t samples
feliwir opened this issue · 2 comments
Hey, I'm trying to write out int16 samples at 8khz into my audio file (by appending them continously). My code looks like this:
AudioFile<Float> inputFile;
void setup()
{
inputFile.setNumChannels(1);
inputFile.setSampleRate(8000);
inputFile.setBitDepth(16);
}
void append(const int16_t *inputData, uint32_t samples)
{
for (int i = 0; i < samples; i++)
{
float sample = inputData[i] / 32768;
inputFile.samples[0].push_back(sample);
}
}
void close()
{
inputFile.printSummary();
inputFile.save ("input.wav");
}
The file is created correctly, but i can't hear any sound at all. Any suggestions what i'm doing wrong? The summary also prints correct information
My best guess is that it is this line...
float sample = inputData[i] / 32768;
I think what is happening is that the 32768 is an integer and so your 16-bit integer sample divided by the other one never gets larger than 1 and so this becomes truncated to zero. To fix it, make the 32768 a floating point number (by adding .f), and for good measure an explicit cast for the sample...
float sample = static_cast<float> (inputData[i]) / 32768.f;
Hope this helps!
Adam
one other thing to check, do your 16-bit sample values vary between -32768 and +327687? If so then they will produce correct -1 to 1 floating point samples. But if they are all positive (for example) then they won't be correct.