Search code examples
swiftios8nsdataavaudiopcmbuffer

Convert AVAudioPCMBuffer to NSData and back


How to convert AVAudioPCMBuffer to NSData? If it should be done as

let data = NSData(bytes: buffer.floatChannelData, length: bufferLength)

then how to calculate bufferLength?

And how to convert NSData to AVAudioPCMBuffer?


Solution

  • Buffer length is frameCapacity * bytesPerFrame. Here are functions that can do conversion between NSData and AVAudioPCMBuffer.

    extension AVAudioPCMBuffer {
        func data() -> Data {
            let channelCount = 1  // given PCMBuffer channel count is 1
            let channels = UnsafeBufferPointer(start: self.floatChannelData, count: channelCount)
            let ch0Data = NSData(bytes: channels[0], length:Int(self.frameCapacity * self.format.streamDescription.pointee.mBytesPerFrame))
            return ch0Data as Data
        }
    }
    
    
    func toPCMBuffer(data: NSData) -> AVAudioPCMBuffer? {
        let audioFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 8000, channels: 1, interleaved: false)!  // given NSData audio format
        guard let PCMBuffer = AVAudioPCMBuffer(pcmFormat: audioFormat, frameCapacity: UInt32(data.length) / audioFormat.streamDescription.pointee.mBytesPerFrame) else {
            return nil
        }
        PCMBuffer.frameLength = PCMBuffer.frameCapacity
        let channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: Int(PCMBuffer.format.channelCount))
        data.getBytes(UnsafeMutableRawPointer(channels[0]) , length: data.length)
        return PCMBuffer
    }