How do I call CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer?

后端 未结 6 1036
北荒
北荒 2021-01-13 04:10

I\'m trying to figure out how to call this AVFoundation function in Swift. I\'ve spent a ton of time fiddling with declarations and syntax, and got this far.

6条回答
  •  花落未央
    2021-01-13 04:58

    Disclaimer: I have just tried to translate the code from Reading audio samples via AVAssetReader to Swift, and verified that it compiles. I have not tested if it really works.

    // Needs to be initialized somehow, even if we take only the address
    var audioBufferList = AudioBufferList(mNumberBuffers: 1,
          mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))
    
    var buffer: Unmanaged? = nil
    
    CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
        sampleBuffer,
        nil,
        &audioBufferList,
        UInt(sizeof(audioBufferList.dynamicType)),
        nil,
        nil,
        UInt32(kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment),
        &buffer
    )
    
    // Ensure that the buffer is released automatically.
    let buf = buffer!.takeRetainedValue() 
    
    // Create UnsafeBufferPointer from the variable length array starting at audioBufferList.mBuffers
    let audioBuffers = UnsafeBufferPointer(start: &audioBufferList.mBuffers,
        count: Int(audioBufferList.mNumberBuffers))
    
    for audioBuffer in audioBuffers {
        // Create UnsafeBufferPointer from the buffer data pointer
        var samples = UnsafeMutableBufferPointer(start: UnsafeMutablePointer(audioBuffer.mData),
            count: Int(audioBuffer.mDataByteSize)/sizeof(Int16))
    
        for sample in samples {
            // ....
        }
    }
    

提交回复
热议问题