23

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?

2 Answers 2

34

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
}
6
  • Me too @Massimo.
    – Brennan
    Mar 10, 2017 at 19:44
  • 4
    I succeeded in transforming NSData in AVAudioPCMBuffer (I did not need the reverse, so don't have that code): pastebin.com/raw/m5c74FPA
    – Massimo
    Mar 13, 2017 at 8:32
  • 1
    @Massimo how to reverse it, means AVAudioPCMBuffer to 16 bit NSData ? Aug 30, 2017 at 12:37
  • 2
    For Swift 4, replace streamDescription.memory with streamDescription.pointee.
    – Avi
    Aug 6, 2019 at 7:21
  • 2
    Hi is it ok to use .floatChannelData when the data is actually int16?
    – ch271828n
    Sep 17, 2020 at 7:55
11

Copying the buffers is much easier if you copy via the audioBufferList API's. This also works no matter what the format is of the actual buffer.

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 { (bufferPointer) in
            guard let addr = bufferPointer.baseAddress else { return }
            audioBuffer.mData?.copyMemory(from: addr, byteCount: Int(audioBuffer.mDataByteSize))
        }

        return buffer
    }
}
1
  • 1
    To avoid 'withUnsafeBytes' is deprecated: use 'withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R' warning with Swift 5, you can pass addr.baseAddress to copyMemory function instead of addr.
    – aleksmutlu
    Nov 7, 2019 at 9:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.