作者:突击手丶罪域 | 来源:互联网 | 2023-05-25 20:09
如何转换AVAudioPCMBuffer
为NSData
?如果应该这样做
let data = NSData(bytes: buffer.floatChannelData, length: bufferLength)
那怎么算bufferLength
?
以及如何转换NSData
为AVAudioPCMBuffer
?
1> Rod Chen..:
缓冲区长度为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(channels[0]) , length: data.length)
return PCMBuffer
}
我成功地在`AVAudioPCMBuffer`中转换`NSData`(我不需要反向,所以没有那个代码):http://pastebin.com/raw/m5c74FPA
2> Brian King..:
如果通过audioBufferList API复制,则复制缓冲区要容易得多。不管实际缓冲区的格式是什么,这都适用。
extension Data {
init(buffer: AVAudioPCMBuffer, time: AVAudioTime) {
let audioBuffer = buffer.audioBufferList.pointee.mBuffers
self.init(bytes: audioBuffer.mData!, count: Int(audioBuffer.mDataByteSize))
}
func makePCMBuffer(format: AVAudioFormat) -> AVAudioPCMBuffer? {
let streamDesc = format.streamDescription.pointee
let frameCapacity = UInt32(count) / streamDesc.mBytesPerFrame
guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCapacity) else { return nil }
buffer.frameLength = buffer.frameCapacity
let audioBuffer = buffer.audioBufferList.pointee.mBuffers
withUnsafeBytes { addr in
audioBuffer.mData?.copyMemory(from: addr, byteCount: Int(audioBuffer.mDataByteSize))
}
return buffer
}
}