I have been trying to convert an AVAudioPCMBuffer to [UInt8], and this is what I have so far.
Note that I found this method from Rhythmic Fistman from this 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
}
And finally this is my method, which was found from the same answer above.
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
}
So first I convert the audioBuffer to bytes, and then I stream this data over an OutputStream. Then on the InputStream I convert the data back to AVAudioPCMBuffer, and I attempt to play it using an AVAudioEngine and an AVAudioPlayerNode. However, all I hear is static or what sounds like someone rubbing there finger on the microphone, I don't hear any noises. I assume there is something wrong with the conversion?
Also, something to note. The variable "numBytes" in audioBufferToBytes is extremely large. It says it's 17640, which (correct me if I'm wrong) seems like a lot of bytes to be streaming multiple times a second.