3

As the title suggests.

There is an old solution in Swift here. But I have hard time converting to Objective-C. Seems there is no Objective-C equivalent of UnsafeBufferPointer

Harikrishnan R
  • 150
  • 1
  • 12

1 Answers1

5

Objective-C has unsafe pointers built right into the language, so the conversion simply becomes:

- (NSData *)bufferToNSData:(AVAudioPCMBuffer *)buffer {
    return [[NSData alloc] initWithBytes:buffer.floatChannelData[0] length:buffer.frameLength * 4];
}

N.B. this assumes mono 32 bit float data in the buffer. More work needs to be done to serialize all supported AVAudioPCMBuffer formats to NSData.

Rhythmic Fistman
  • 34,352
  • 5
  • 87
  • 159
  • I need mono 16 bit data. So I assume I should use `int16ChannelData` instead of `floatChannelData`. But what is the criteria of the `4` in `buffer.frameLength * 4`. Size of float? – Harikrishnan R Apr 20 '18 at 10:40
  • That’s right, and the 4 would become 2. You can dig that number out of the buffer if you want. – Rhythmic Fistman Apr 20 '18 at 10:42
  • @LordHari did you solve the mystery. If yes please share me the code, since I am not able to get 'int16ChannelData' – Majid Bashir Aug 28 '18 at 07:32