AudioBufferList allocate in Swift

1k views Asked by At

I am struggling with this API and the syntax in Swift

audioBufferList = AudioBufferList(mNumberBuffers: 2, mBuffers: (AudioBuffer))

I don't know what (AudioBuffer) with ( ) means? Any ideas and how do I initialize it? This is from the headers:

  public struct AudioBufferList {

      public var mNumberBuffers: UInt32
      public var mBuffers: (AudioBuffer) // this is a variable length array of mNumberBuffers elements
      public init()
      public init(mNumberBuffers: UInt32, mBuffers: (AudioBuffer))
 }
2

There are 2 answers

1
hotpaw2 On

Here is one way to initialize an AudioBufferList, with one empty mono buffer array, that you can pass to Audio Unit calls, such as AudioUnitRender() which then allocates and fills the buffer as needed :

var bufferList = AudioBufferList(
        mNumberBuffers: 1,
        mBuffers: AudioBuffer(
            mNumberChannels: UInt32(1),
            mDataByteSize: 1024,
            mData: nil))
0
Roman Aliyev On

Solved the problem by using AVAudioPCMBuffer class in the following way:

import AVFoundation

// noninterleaved stereo data
let processingFormat = AVAudioFormat(
  commonFormat: .pcmFormatFloat32,
  sampleRate: 44100,
  channels: 2,
  interleaved: false
)!

// this line also creates AudioBufferList instance.
let buffer = AVAudioPCMBuffer(
  pcmFormat: processingFormat,
  frameCapacity: 1024)!
// this line updates mDataByteSize properties
buffer.frameLength = 1024

let bufferList: UnsafePointer<AudioBufferList> = buffer.audioBufferList

print(bufferList.pointee) // Prints: AudioBufferList(mNumberBuffers: 2, mBuffers: __C.AudioBuffer(mNumberChannels: 1, mDataByteSize: 4096, mData: Optional(0x00007ff253840e00)))