AVAudioConverter convert AVAudioPCMBuffer to AAC

2.7k views Asked by At

I'm having an issue with AVAudioConverter. I'm trying to convert AVAudioPCMBuffers to AAC.

This is my function for converting, taken from the "What's new in Core Audio" session 507 at WWDC 2015.

func convertPCMBufferToAAC(inBuffer : AVAudioPCMBuffer) -> Void {
    let inputFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32,
                                    sampleRate: 8000, channels: 1,
                                    interleaved: false)

    var outDesc = AudioStreamBasicDescription(mSampleRate: 8000,
                                              mFormatID: kAudioFormatMPEG4AAC,
                                              mFormatFlags: 0,
                                              mBytesPerPacket: 0,
                                              mFramesPerPacket: 0,
                                              mBytesPerFrame: 0,
                                              mChannelsPerFrame: 1,
                                              mBitsPerChannel: 0,
                                              mReserved: 0)

    let outputFormat = AVAudioFormat(streamDescription: &outDesc)
    let converter = AVAudioConverter(from: inputFormat, to: outputFormat)
    let outBuffer = AVAudioCompressedBuffer(format: outputFormat,
                                            packetCapacity: 8,
                                            maximumPacketSize: converter.maximumOutputPacketSize)

    let inputBlock : AVAudioConverterInputBlock = {
        inNumPackets, outStatus in
        outStatus.pointee = AVAudioConverterInputStatus.haveData
        return inBuffer
    }
    var error : NSError?
    let status = converter.convert(to: outBuffer, error: &error, withInputFrom: inputBlock)
}

The problem is that the outBuffer is empty. If I print it I get the output <AVAudioCompressedBuffer@0x170012420: 0/6144 bytes> so as you can see it is not filled.

If your wondering I'm getting the AVAudioPCMBuffer from installing a tap on the AVAudioEngine. This I'm converting to the same format as inputFormat using the AVAudioEngines main mixer.

Does anyone know a solution to this?

1

There are 1 answers

9
Gordon Childs On

I think the problem is that the inputFormat you construct differs from inBuffer.format. Try this instead:

let inputFormat = inBuffer.format

and make sure to run the code on a device, as it does not appear to work on the simulator.