初始化(分配内存)和释放(释放)具有3个AudioBuffers的AudioBufferList的正确方法是什么?(我知道可能有不止一种方法可以做到这一点。)
我想使用这3个缓冲区来读取音频文件的连续部分,并使用音频单元播放它们。
发布于 2010-09-26 13:41:50
我是这样做的:
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;
}发布于 2010-09-22 19:50:25
首先,我认为你实际上想要3个AudioBufferLists,而不是一个有3个AudioBuffer成员的AudioBufferList。AudioBuffer表示单个通道的数据,因此如果您有3个立体声音频文件,则应将它们放在3个AudioBufferLists中,每个列表具有2个AudioBuffers,一个用于左通道,一个用于右通道。然后,您的代码将分别处理每个列表(及其相应的通道数据),您可以将这些列表存储在NSArray或类似的东西中。
从技术上讲,你没有理由不能有一个包含3个交错音频通道的缓冲区列表(这意味着左声道和右声道都存储在一个数据缓冲区中),但这与API的常规使用背道而驰,而且会有点混乱。
无论如何,与CoreAudio - C-ish相比,malloc API的这一部分更像是C语言,所以您应该使用malloc/free而不是alloc/release。代码将如下所示:
#define kNumChannels 2
AudioBufferList *bufferList = (AudioBufferList*)malloc(sizeof(AudioBufferList) * kNumChannels);
bufferList->mNumberBuffers = kNumChannels; // 2 for stereo, 1 for mono
for(int i = 0; i < 2; i++) {
int numSamples = 123456; // Number of sample frames in the buffer
bufferList->mBuffers[i].mNumberChannels = 1;
bufferList->mBuffers[i].mDataByteSize = numSamples * sizeof(Float32);
bufferList->mBuffers[i].mData = (Float32*)malloc(sizeof(Float32) * numSamples);
}
// Do stuff...
for(int i = 0; i < 2; i++) {
free(bufferList->mBuffers[i].mData);
}
free(bufferList);上面的代码假设你以浮点数的形式读入数据。如果您没有对这些文件进行任何特殊处理,那么将它们作为SInt16 (原始PCM数据)读取会更有效,因为iPhone没有FPU。
此外,如果您没有在单个方法之外使用列表,那么通过将其声明为常规对象而不是指针,将它们分配到堆栈而不是堆上会更有意义。您仍然需要malloc() AudioBuffer的实际mData成员,但至少您不需要担心实际的AudioBufferList本身。
https://stackoverflow.com/questions/3767527
复制相似问题