我一直在尝试将AVAudioPCMBuffer转换为[UInt8],这是我到目前为止所拥有的。
请注意,我从此Rhythmic Fistman的answer中找到了此方法。
func audioBufferToBytes(audioBuffer: AVAudioPCMBuffer) -> [UInt8] {
let srcLeft = audioBuffer.floatChannelData![0]
let bytesPerFrame = audioBuffer.format.streamDescription.pointee.mBytesPerFrame
let numBytes = Int(bytesPerFrame * audioBuffer.frameLength)
// initialize bytes by 0
var audioByteArray = [UInt8](repeating: 0, count: numBytes)
srcLeft.withMemoryRebound(to: UInt8.self, capacity: numBytes) { srcByteData in
audioByteArray.withUnsafeMutableBufferPointer {
$0.baseAddress!.initialize(from: srcByteData, count: numBytes)
}
}
return audioByteArray
}
最后这是我的方法,这是从上面的相同答案中找到的。
func bytesToAudioBuffer(_ buf: [UInt8]) -> AVAudioPCMBuffer {
let fmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44100, channels: 1, interleaved: true)
let frameLength = UInt32(buf.count) / fmt.streamDescription.pointee.mBytesPerFrame
let audioBuffer = AVAudioPCMBuffer(pcmFormat: fmt, frameCapacity: frameLength)
audioBuffer.frameLength = frameLength
let dstLeft = audioBuffer.floatChannelData![0]
// for stereo
// let dstRight = audioBuffer.floatChannelData![1]
buf.withUnsafeBufferPointer {
let src = UnsafeRawPointer($0.baseAddress!).bindMemory(to: Float.self, capacity: Int(frameLength))
dstLeft.initialize(from: src, count: Int(frameLength))
}
return audioBuffer
}
所以首先我将audioBuffer转换为字节,然后我通过OutputStream传输这些数据。然后在InputStream上我将数据转换回AVAudioPCMBuffer,我尝试使用AVAudioEngine和AVAudioPlayerNode播放它。然而,我听到的只是静电或听起来像是有人用手指在麦克风上摩擦,我听不到任何噪音。我认为转换有问题吗?
另外,需要注意的事项。 audioBufferToBytes中的变量“numBytes”非常大。它说它是17640,(如果我错了,请纠正我)似乎需要每秒多次流式传输多个字节。