Hi everyone,
I came across some inconsistent behavior in AudioFormatWriter/AudioFormatReader. I create a multichannel (four channels) WAV file with AudioFormatWriter. The file can be read by Audacity, no problem. But when I read the very same file with AudioFormatReader, it returns the length of 0 samples through its lengthInSamples field (public!) . All other parameters like bitsPerSample, numChannels and sampleRate are correct. (Public again, tut-tut!). The problem disappears when I change the number of channels to two (stereo).
Here is the code that reproduces the problem:
[code] int sampleCount(1024);
unsigned int channelCount(4); // This causes AudioFormatReader to return length of 0 samples in a non-empty file
// When changed to 2 (stereo) it works correctly
AudioFormatManager audioFormatManager;
WavAudioFormat* wavAudioFormat = new WavAudioFormat();
ScopedPointer<AudioFormatReader> audioFormatReader;
audioFormatManager.registerFormat(wavAudioFormat, true);
// create 4 channel WAV file in 32 bit float format
{
ScopedPointer<AudioFormatWriter> audioFormatWriter;
File af( File::getCurrentWorkingDirectory().getChildFile ("sample.wav") );
af.deleteFile();
FileOutputStream* outStream = af.createOutputStream();
double sampleRate(48000.0);
int bitsPerSample(32);
int qualityOption(0);
audioFormatWriter = wavAudioFormat->createWriterFor(outStream, sampleRate, channelCount, bitsPerSample, nullptr, qualityOption);
AudioSampleBuffer abuf(channelCount, sampleCount);
abuf.clear();
audioFormatWriter->write( (const int**) abuf.getArrayOfChannels(), sampleCount );
std::cout << "Saved audio file: " << audioFormatWriter->getNumChannels() << " channels, "
<< audioFormatWriter->getBitsPerSample() << " bits, "
<< audioFormatWriter->getSampleRate() << " Hz, "
<< sampleCount << " samples.\n\n";
}
// read WAV file
File af( File::getCurrentWorkingDirectory().getChildFile ("sample.wav") );
audioFormatReader = audioFormatManager.createReaderFor(af);
if (audioFormatReader == nullptr)
return 1;
std::cout << "Loaded audio file: " << audioFormatReader->numChannels << " channels, "
<< audioFormatReader->bitsPerSample << " bits, "
<< audioFormatReader->sampleRate << " Hz, "
<< audioFormatReader->lengthInSamples << " samples. \n\n";
audioFormatManager.clearFormats();
[/code]
At the same time, if I use AudioSampleBuffer::readFromAudioReader method, it seems to read the content of the file correctly.
Any ideas what is wrong here?
Cheers,
Roman