Handling mp3/m4a read into an array


I’m new to Juce and I want to read in mp3/m4a with it. In the Juce Demo, there is a AudioPlayBackPage where mp3 and m4a files can be played back, and that is why I think Juce can handle this.

But I met a problem when I was trying to do so

Here is how I wrote my own class handling the audio read in:

[code]#include "JuceHeader.h"
class AudioReader : public AudioFormatReaderSource
AudioSourceChannelInfo bufferToFill;
int64 totalLength;
unsigned int numChannels;
double sampleRate;
AudioFormatReader *sourceReader;

AudioReader(AudioFormatReader *sourceReader, bool deleteReaderWhenThisIsDeleted):AudioFormatReaderSource(sourceReader,deleteReaderWhenThisIsDeleted) {
	totalLength = sourceReader->lengthInSamples;
	numChannels = sourceReader->numChannels;
	sampleRate = sourceReader->sampleRate;
float** readAudio(){
     this->bufferToFill.buffer->readFromAudioReader(sourceReader, 0, totalLength, 0, true, true);
      return this->bufferToFill.buffer->getArrayOfChannels();


And this is how I call it in main function:

[code]int main (int argc, char* argv[])
float** audio;
File * audioFile = new File("/Users/Ajay/Documents/MATLAB/unBecame_v3.mp3");
AudioFormatManager formatManager;
AudioFormatReader* reader = formatManager.createReaderFor (*audioFile);
if (reader != 0)
AudioReader * audioReader = new AudioReader (reader, true);
printf("%d, %lld, %f\n", audioReader->numChannels,audioReader->totalLength,audioReader->sampleRate);

return 0;


As the code runs, the printf inside the main function can be run and the numbers printed out are right. But then it pops up a “EXC_BAD_ACCESS”, and lead me into the implementation of void AudioSampleBuffer::readFromAudioReader(), and the program stops at jassert (startSample >= 0 && startSample + numSamples <= size);

What is wrong with my code?


Your bufferToFill doesn’t have a buffer allocated.

class AudioReader
AudioSampleBuffer buffer;

AudioReader::AudioReader() : buffer(2,8192) // for 2 channels, 8192 samples


Also you can put things that don’t need to persist like File on the stack(no need to use new)

And for other things, instead of using delete, use a scopedpointer so

ScopedPointer<AudioReader> audioReader(new AudioReader(reader,true));


Oh, and you probably DON’T want to load the totalLength of the audio in on your readaudio. At most the number of samples assigned to your sample buffer.


Thanks man! You solved my problem! Awesome!