Skip to content

Instantly share code, notes, and snippets.

@tion-low
Last active May 14, 2019 02:15
Show Gist options
  • Save tion-low/da1dd95c8a8f7bcf621f1be4d7e5c69b to your computer and use it in GitHub Desktop.
Save tion-low/da1dd95c8a8f7bcf621f1be4d7e5c69b to your computer and use it in GitHub Desktop.
func convertCMSampleBuffer(from pcmBuffer: AVAudioPCMBuffer) -> CMSampleBuffer? {
let bufferList = pcmBuffer.audioBufferList
let asbd = pcmBuffer.format.streamDescription
var sampleBuffer: CMSampleBuffer!
var formatDescription: CMFormatDescription!
var status = CMAudioFormatDescriptionCreate(allocator: kCFAllocatorDefault,
asbd: asbd,
layoutSize: 0,
layout: nil,
magicCookieSize: 0,
magicCookie: nil,
extensions: nil,
formatDescriptionOut: &formatDescription)
guard status == kCMBlockBufferNoErr else {
return nil
}
var timing = CMSampleTimingInfo(duration: CMTime(value: 1, timescale: CMTimeScale(asbd.pointee.mSampleRate)),
presentationTimeStamp: CMTime.zero,
decodeTimeStamp: CMTime.invalid)
status = CMSampleBufferCreate(allocator: kCFAllocatorDefault,
dataBuffer: nil,
dataReady: false,
makeDataReadyCallback: nil,
refcon: nil,
formatDescription: formatDescription,
sampleCount: CMItemCount(pcmBuffer.frameLength),
sampleTimingEntryCount: 1,
sampleTimingArray: &timing,
sampleSizeEntryCount: 0,
sampleSizeArray: nil,
sampleBufferOut: &sampleBuffer)
guard status == kCMBlockBufferNoErr else {
return nil
}
status = CMSampleBufferSetDataBufferFromAudioBufferList(sampleBuffer,
blockBufferAllocator: kCFAllocatorDefault,
blockBufferMemoryAllocator: kCFAllocatorDefault,
flags: 0,
bufferList: bufferList)
guard status == kCMBlockBufferNoErr else {
return nil
}
return sampleBuffer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment