Home > Blockchain >  Detect AudioLayout in AVAssetTrack
Detect AudioLayout in AVAssetTrack

Time:03-23

I need to detect number of channels and the format of audio (interleaved or non-interleaved) from AVAssetTrack. I tried the following code to detect the number of channels. As can be seen in the code, there are two ways to detect number of channels. I want to know which one is more reliable and correct, or none of them perhaps (irrespective of audio format)?

  if let formatDescriptions = track.formatDescriptions as? [CMAudioFormatDescription],
        let audioFormatDesc = formatDescriptions.first,
        let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(audioFormatDesc)
    {                                   
       //First way to detect number of channels
        numChannels = asbd.pointee.mChannelsPerFrame 
        
        var aclSize:size_t = 0
        var currentChannelLayout:UnsafePointer<AudioChannelLayout>? = nil
            
        currentChannelLayout = CMAudioFormatDescriptionGetChannelLayout(audioFormatDesc, sizeOut: &aclSize)
        
        if let currentChannelLayout = currentChannelLayout, aclSize > 0 {
            let channelLayout = currentChannelLayout.pointee
            
            //second way of detecting number of channels
            numChannels = AudioChannelLayoutTag_GetNumberOfChannels(channelLayout.mChannelLayoutTag) 
        }

}

And I don't know how to get audio format details (interleaved or non-interleaved). Looking for help in this.

CodePudding user response:

Use the AudioStreamBasicDescription. All audio CMFormats have one, while the AudioChannelLayout is optional:

https://developer.apple.com/documentation/coremedia/1489137-cmaudioformatdescriptiongetchann?language=objc

AudioChannelLayouts are optional; this API returns NULL if one doesn’t exist.

  • Related