CMSAMPLEBuffer: audio PCM to MP4 AAC

Hello,

As explained in this link, the AVAssetReaderTrackOutput.copyNextSampleBuffer() returns a CMSampleBuffer in linear PCM audio format.

I want to place this audio buffer into an AVAssetWriterInput of type kAudioFormatMPEG4AAC, but I can't manage the conversion.

Could you help me by providing an extension that returns a CMSampleBuffer converted from linear PCM audio format to kAudioFormatMPEG4AAC?

Example:

extension CMSampleBuffer {
    func fromPCMToAAC() -> CMSampleBuffer? {
        // Here, get a new AudioStreamBasicDescription, create a CMSampleBuffer and a CMBlockBuffer
    }
}

I've tried multiple times but without success.

Software: iOS 18.1 XCode: 16.0 Thank you!

Answered by Engineer in 807324022

Hello @Paulo_DEV01, you don't need to convert PCM buffers to AAC before adding them to AVAssetWriterInput. You can simply use the init(mediaType:outputSettings:) initializer and specify AAC in the output settings. Below is an example:

let settings: [String : Any] = [
    AVFormatIDKey: kAudioFormatMPEG4AAC,
    AVNumberOfChannelsKey: 2,
    AVSampleRateKey: 48000,
    AVEncoderBitRatePerChannelKey: 96000,
    AVEncoderBitRateStrategyKey: AVAudioBitRateStrategy_Variable,
]

let writerInput = AVAssetWriterInput(mediaType: .audio, outputSettings: settings)
Accepted Answer

Hello @Paulo_DEV01, you don't need to convert PCM buffers to AAC before adding them to AVAssetWriterInput. You can simply use the init(mediaType:outputSettings:) initializer and specify AAC in the output settings. Below is an example:

let settings: [String : Any] = [
    AVFormatIDKey: kAudioFormatMPEG4AAC,
    AVNumberOfChannelsKey: 2,
    AVSampleRateKey: 48000,
    AVEncoderBitRatePerChannelKey: 96000,
    AVEncoderBitRateStrategyKey: AVAudioBitRateStrategy_Variable,
]

let writerInput = AVAssetWriterInput(mediaType: .audio, outputSettings: settings)
CMSAMPLEBuffer: audio PCM to MP4 AAC
 
 
Q