2

I am using external camera which records both audio and video.

My app receives the audio in AAC format with the following struct:

struct AudioPacket {
   let timestamp: TimeInterval
   let data: Data
   let asbd: AudioStreamBasicDescription
   let magicCookie: Data
   let audioSpecificConfigData: Data
}

The AudioStreamBasicDescription property has the following content:

- mSampleRate : 48000.0
- mFormatID : 1633772320
- mFormatFlags : 0
- mBytesPerPacket : 0
- mFramesPerPacket : 1024
- mBytesPerFrame : 0
- mChannelsPerFrame : 1
- mBitsPerChannel : 0
- mReserved : 0

I am writing both audio and video into a file using AVAssetWriter and need to provide CMSampleBuffer-s to the asset writer.

So how can I convert the above AudioPacket struct to CMSampleBuffer?

plamkata__
  • 729
  • 5
  • 13

1 Answers1

2

Not an exact answer, but I would try something like the following:

func convertPacket(_ packet: AudioPacket) -> CMSampleBuffer? {
    var data = packet.data
    var asbd = packet.asbd
    var magicCookie = packet.magicCookie
    var blockBuffer: CMBlockBuffer?
    var formatDescription: CMFormatDescription?
    var sampleBuffer: CMSampleBuffer?
    CMBlockBufferCreateWithMemoryBlock(
        allocator: nil, memoryBlock: &data, blockLength: data.count,
        blockAllocator: nil, customBlockSource: nil, offsetToData: 0,
        dataLength: data.count, flags: 0, blockBufferOut: &blockBuffer
    )
    CMAudioFormatDescriptionCreate(
        allocator: nil, asbd: &asbd, layoutSize: 0, layout: nil,
        magicCookieSize: magicCookie.count, magicCookie: &magicCookie,
        extensions: nil, formatDescriptionOut: &formatDescription
    )
    CMAudioSampleBufferCreateWithPacketDescriptions(
        allocator: nil, dataBuffer: blockBuffer, dataReady: true,
        makeDataReadyCallback: nil, refcon: nil, formatDescription: formatDescription!,
        sampleCount: 1, // <- provide correct number
        presentationTimeStamp: CMTime(seconds: packet.timestamp, preferredTimescale: 100),
        packetDescriptions: nil, sampleBufferOut: &sampleBuffer
    )
    return sampleBuffer
}
bbjay
  • 1,728
  • 3
  • 19
  • 35