将AVAudioPCMBuffer转换为NSData并返回
怎么转换AVAudioPCMBuffer
成NSData
?如果应该这样做
let data = NSData(bytes: buffer.floatChannelData, length: bufferLength)
那怎么算bufferLength
呢?
以及如何转换NSData
为AVAudioPCMBuffer
?
回答:
缓冲区长度为frameCapacity * bytesPerFrame。以下是可以在NSData和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并返回 的全部内容, 来源链接: utcz.com/qa/424169.html