AudioFormatReader::lengthInSamples==0 ??


#1

Hi, 

With the latest tip, when reading an audio file that I just created, I found that AudioFormatReader::lengthInSamples==0.

However the file seems valid as it can be read by any media player under windows. It looks like a bug in juce ...

 

Here is the whole code. The last jassert fails because the length is null.

 


mProcessedFile.create();
    jassert(mProcessedFile.existsAsFile())
        
    juce::FileOutputStream* fileOutputStream=new juce::FileOutputStream(mProcessedFile);
    fileOutputStream->setPosition(0);
    fileOutputStream->truncate();
    juce::ScopedPointer<juce::AudioFormatWriter> writer=mFormatManager.getDefaultFormat()->createWriterFor(fileOutputStream,
                                                                                                            mProjectSampleRate,
                                                                                                            2,
                                                                                                            32,
                                                                                                            juce::WavAudioFormat::createBWAVMetadata("test","test","test",juce::Time::getCurrentTime(),0,"test"),
                                                                                                            0);
    bool result=writer->writeFromAudioSource(*mSourceFile,mSourceFile->getLengthInSamples());
    jassert(result);
    fileOutputStream->flush();
    // caching complete
  

 juce::FileInputStream* fileInputStream=new juce::FileInputStream(mProcessedFile);
   juce::BufferedInputStream(fileInputStream,mReadAheadBufferSize,true);
    juce::AudioFormatReader* reader = mFormatManager.createReaderFor(fileInputStream);
        
    
    mProcessedFileAudioSource=new juce::AudioFormatReaderSource(reader,true);
    mProcessedFileAudioSource->prepareToPlay(512,mProjectSampleRate);
    mLengthInSamples=reader->lengthInSamples;        
    jassert(mLengthInSamples!=0);
 


#2

There's no point in flushing the output stream until the writer has been deleted, because it may still write to it in its destructor.

Seriously.. break your code down into smaller functions so that all your variables don't live inside one big scope! Variables shouldn't be left hanging around for longer than they're needed, especially when their lifetime affects the behaviour of your program, like it does in this case!


#3

I added the flush after I saw it didn't work but you were right : the problem comes from the fact the destructor of the writer is called after I try to read. Solving this solved the problem. Thanks a lot for your help !