Play audio from BinaryData

Hi everyone,

I’m trying to play and resample a BinaryData,
this is my code:

void prepareToPlay (double sampleRate, int samplesPerBlock) {
    juce::MemoryInputStream inputStream{ BinaryData::sample_wav, BinaryData::sample_wavSize, false };
    juce::WavAudioFormat wavFormat;
    juce::AudioFormatReader* mFormatReader = wavFormat.createReaderFor(&inputStream, false);

    audioFormatReaderSource = new juce::AudioFormatReaderSource(mFormatReader, true);
    resampler = new juce::ResamplingAudioSource{ audioFormatReaderSource, false, getNumOutputChannels() };
    resampler->prepareToPlay(samplesPerBlock, sampleRate);

void processBlock (juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midiMessages) {
        juce::AudioSourceChannelInfo channelInfo(buffer);

        for (int i = 0; i < numSamples; i++) {
            buffer.setSample(0, i, channelInfo.buffer->getSample(0, i));
            buffer.setSample(1, i, channelInfo.buffer->getSample(1, i));

An exception is thrown at line 1488 of the juce_WavAudioFormat.cpp file

input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);

Could anyone help me?

Since both inputStream and wavFormat are on the stack, they both go out of scope when you exit prepareToPlay. It seems these two objects need to be valid for the reader to work in processBlock? The inputStream provides the raw data and the wavFormat decodes it? I haven’t written that type of code recently, so I am just making a guess. :slight_smile:

Thanks a lot :slightly_smiling_face:, that was the problem, I put both as attributes of the class.

1 Like