Search code examples
iosswiftaudiocore-audio

How to convert to AVAudioPCMBuffer from AudioBufferList?


i am struggling to convert it.

I made AudioBufferList data using AudioUnit with refer This.

And It has filled audio buffer data by AudioUnitRender().

       var bufferList = AudioBufferList(
           mNumberBuffers: 1,
           mBuffers: AudioBuffer(
               mNumberChannels: UInt32(2),
               mDataByteSize: 16,
               mData: nil))
   
       
       if let au = audioObject.audioUnit {
           err = AudioUnitRender(au,
                                 ioActionFlags,
                                 inTimeStamp,
                                 inBusNumber,
                                 frameCount,
                                 &bufferList)
       }

And then, I tried to convert it to AudioBufferList. But, It doesn't work

Following is what i did.

        let audioFormat = AVAudioFormat(
            commonFormat: AVAudioCommonFormat.pcmFormatFloat64,
            sampleRate: recoder.sampleRate,
            interleaved: false,
            channelLayout: AVAudioChannelLayout(
                layoutTag: kAudioChannelLayoutTag_Stereo
            )!
        )

        guard let pcmBuffer = AVAudioPCMBuffer(
                    pcmFormat: audioFormat,
                    bufferListNoCopy: &bufferList
                ) else {
                    return
                }

A console message i received.

AVAudioBuffer.mm:248   the number of buffers (1) does not match the format's number of channel streams (2)

Please help me someone

thank you.


Solution

  • The AudioBufferList you create has mNumberBuffers = 1 and the single contained AudioBuffer has mNumberChannels = 2 so overall the buffer list contains two interleaved channels. The AVAudioFormat you're creating is non-interleaved stereo which is why you're seeing the format mismatch error. You can try creating a non-interleaved AVAudioFormat or use AVAudioConverter to deinterleave the data.