Last active
January 27, 2022 10:19
-
-
Save doozMen/10dc3d29cfca50ae8a5ed9eb25fda7a6 to your computer and use it in GitHub Desktop.
CMSampleBuffer for audio created to be used in unit tests - swift 5.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import AVFoundation | |
func createSilentAudio(startFrm: Int64, nFrames: Int, sampleRate: Float64, numChannels: UInt32) -> CMSampleBuffer { | |
let bytesPerFrame = UInt32(2 * numChannels) | |
let blockSize = nFrames*Int(bytesPerFrame) | |
var block: CMBlockBuffer? | |
var status = CMBlockBufferCreateWithMemoryBlock( | |
allocator: kCFAllocatorDefault, | |
memoryBlock: nil, | |
blockLength: blockSize, // blockLength | |
blockAllocator: nil, // blockAllocator | |
customBlockSource: nil, // customBlockSource | |
offsetToData: 0, // offsetToData | |
dataLength: blockSize, // dataLength | |
flags: 0, // flags | |
blockBufferOut: &block | |
) | |
assert(status == kCMBlockBufferNoErr) | |
// we seem to get zeros from the above, but I can't find it documented. so... memset: | |
status = CMBlockBufferFillDataBytes(with: 0, blockBuffer: block!, offsetIntoDestination: 0, dataLength: blockSize) | |
assert(status == kCMBlockBufferNoErr) | |
var asbd = AudioStreamBasicDescription( | |
mSampleRate: sampleRate, | |
mFormatID: kAudioFormatLinearPCM, | |
mFormatFlags: kLinearPCMFormatFlagIsSignedInteger, | |
mBytesPerPacket: bytesPerFrame, | |
mFramesPerPacket: 1, | |
mBytesPerFrame: bytesPerFrame, | |
mChannelsPerFrame: numChannels, | |
mBitsPerChannel: 16, | |
mReserved: 0 | |
) | |
var formatDesc: CMAudioFormatDescription? | |
status = CMAudioFormatDescriptionCreate(allocator: kCFAllocatorDefault, asbd: &asbd, layoutSize: 0, layout: nil, magicCookieSize: 0, magicCookie: nil, extensions: nil, formatDescriptionOut: &formatDesc) | |
assert(status == noErr) | |
var sampleBuffer: CMSampleBuffer? | |
// born ready | |
status = CMAudioSampleBufferCreateReadyWithPacketDescriptions( | |
allocator: kCFAllocatorDefault, | |
dataBuffer: block!, // dataBuffer | |
formatDescription: formatDesc!, | |
sampleCount: nFrames, // numSamples | |
presentationTimeStamp: CMTimeMake(value: startFrm, timescale: Int32(sampleRate)), // sbufPTS | |
packetDescriptions: nil, // packetDescriptions | |
sampleBufferOut: &sampleBuffer | |
) | |
assert(status == noErr) | |
return sampleBuffer! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
original https://stackoverflow.com/questions/34441648/create-a-silent-audio-cmsamplebufferref but update swift version