iOS|iOS 使用CoreAudio生成白噪音频数据

【iOS|iOS 使用CoreAudio生成白噪音频数据】iOS 使用CoreAudio生成白噪音频数据(空白音频)

/// 生成一段白噪音频数据 /// - Parameters: ///- startFrm: 开始frame ///- nFrames: 持续的frame ///- sampleRate: fps ///- numChannels: 声道数量 /// - Returns: 静音音频数据 static 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 }

    推荐阅读