我在C中有以下代码,它们分配一个具有适当长度的AudioBufferList。
UInt32 bufferSizeBytes = bufferSizeFrames * sizeof(Float32);
propertySize = offsetof(AudioBufferList, mBuffers[0]) + (sizeof(AudioBuffer) * mRecordSBD.mChannelsPerFrame);
mBufferList = (AudioBufferList *) malloc(propertySize);
mBufferList->mNumberBuffers = mRecordSBD.mChannelsPerFrame;
for(UInt32 i = 0; i < mBufferList->mNumberBuffers; ++i)
{
mBufferList->mBuffers[i].mNumberChannels = 1;
mBufferList->mBuffers[i].mDataByteSize = bufferSizeBytes;
mBufferList->mBuffers[i].mData = malloc(bufferSizeBytes);
}
大多数情况下,mChannelsPerFrame
为2,因此上面的代码创建了两个缓冲区,每个缓冲区一个缓冲区。每个缓冲区都有一个值bufferSizeBytes
的保留内存。
如何在Swift中复制相同的行为?
答案 0 :(得分:4)
不幸的是,在Swift中,C数组被视为元组,因此AudioBufferList.mBuffers导入一个带有单个AudioBuffer的元组。 C允许您通过使用指针数学(或本例中的数组下标)来访问相邻内存,以便创建可变长度结构,Swift不会。
AudioBufferList只是简单的并没有很好地转换为Swift。 Apple通过一些辅助函数和类型来缓解这个问题。他们创建了一个静态allocate函数,它返回一个UnsafeMutableAudioBufferListPointer,这是一个特殊的类型,其中下标返回audioBuffers。
let bufferSizeBytes = MemoryLayout<Float>.size * 1234
var bufferlist = AudioBufferList.allocate(maximumBuffers: 2)
bufferlist[0] = AudioBuffer(mNumberChannels: 1,
mDataByteSize: UInt32(bufferSizeBytes),
mData: malloc(bufferSizeBytes))
bufferlist[1] = AudioBuffer(mNumberChannels: 1,
mDataByteSize: UInt32(bufferSizeBytes),
mData: malloc(bufferSizeBytes))
// Free your buffers and the pointer when you're done.
for buffer in bufferlist {
free(buffer.mData)
}
free(&bufferlist)
答案 1 :(得分:0)
您可以使用Core Audio API为2个交错流创建一个带有2个缓冲区的AudioBufferList:
import AudioUnit
import AVFoundation
var myBufferList = AudioBufferList(
mNumberBuffers: 2,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(2),
mDataByteSize: myBufferSizeBytes,
mData: nil) )