iPhone: AudioBufferList init and release

Tom Ilsinszki picture Tom Ilsinszki · Sep 22, 2010 · Viewed 11k times · Source

What are the correct ways of initializing (allocating memory) and releasing (freeing) an AudioBufferList with 3 AudioBuffers? (I'm aware that there might be more than one ways of doing this.)

I'd like to use those 3 buffers to read sequential parts of an audio file into them and play them back using Audio Units.

Answer

sbooth picture sbooth · Sep 26, 2010

Here is how I do it:

AudioBufferList *
AllocateABL(UInt32 channelsPerFrame, UInt32 bytesPerFrame, bool interleaved, UInt32 capacityFrames)
{
    AudioBufferList *bufferList = NULL;

    UInt32 numBuffers = interleaved ? 1 : channelsPerFrame;
    UInt32 channelsPerBuffer = interleaved ? channelsPerFrame : 1;

    bufferList = static_cast<AudioBufferList *>(calloc(1, offsetof(AudioBufferList, mBuffers) + (sizeof(AudioBuffer) * numBuffers)));

    bufferList->mNumberBuffers = numBuffers;

    for(UInt32 bufferIndex = 0; bufferIndex < bufferList->mNumberBuffers; ++bufferIndex) {
        bufferList->mBuffers[bufferIndex].mData = static_cast<void *>(calloc(capacityFrames, bytesPerFrame));
        bufferList->mBuffers[bufferIndex].mDataByteSize = capacityFrames * bytesPerFrame;
        bufferList->mBuffers[bufferIndex].mNumberChannels = channelsPerBuffer;
    }

    return bufferList;
}