本文介绍了将AVAudioPCMBuffer转换为NSData并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将 AVAudioPCMBuffer
转换为 NSData
?如果应该这样做
How to convert AVAudioPCMBuffer
to NSData
? If it should be done as
let data = NSData(bytes: buffer.floatChannelData, length: bufferLength)
然后如何计算 bufferLength
?
以及如何将 NSData
转换为 AVAudioPCMBuffer
?
推荐答案
缓冲区长度为frameCapacity * bytesPerFrame。以下是可以在NSData和AVAudioPCMBuffer之间进行转换的函数。
Buffer length is frameCapacity * bytesPerFrame. Here are functions that can do conversion between NSData and AVAudioPCMBuffer.
func toNSData(PCMBuffer: AVAudioPCMBuffer) -> NSData {
let channelCount = 1 // given PCMBuffer channel count is 1
var channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: channelCount)
var ch0Data = NSData(bytes: channels[0], length:Int(PCMBuffer.frameCapacity * PCMBuffer.format.streamDescription.memory.mBytesPerFrame))
return ch0Data
}
func toPCMBuffer(data: NSData) -> AVAudioPCMBuffer {
let audioFormat = AVAudioFormat(commonFormat: AVAudioCommonFormat.PCMFormatFloat32, sampleRate: 8000, channels: 1, interleaved: false) // given NSData audio format
var PCMBuffer = AVAudioPCMBuffer(PCMFormat: audioFormat, frameCapacity: UInt32(data.length) / audioFormat.streamDescription.memory.mBytesPerFrame)
PCMBuffer.frameLength = PCMBuffer.frameCapacity
let channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: Int(PCMBuffer.format.channelCount))
data.getBytes(UnsafeMutablePointer<Void>(channels[0]) , length: data.length)
return PCMBuffer
}
这篇关于将AVAudioPCMBuffer转换为NSData并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!