Skip to content

Instantly share code, notes, and snippets.

@jaekong
Created August 10, 2019 14:38
Show Gist options
  • Save jaekong/f2fa59c19794811dbe989dff65a772bc to your computer and use it in GitHub Desktop.
Save jaekong/f2fa59c19794811dbe989dff65a772bc to your computer and use it in GitHub Desktop.
AudioBuffer (or AVAudioPCMBuffer) to array of float / Float array to AudioBuffer (or AVAudioPCMBuffer)
import AVFoundation
extension AudioBuffer {
func array() -> [Float] {
return Array(UnsafeBufferPointer(self))
}
}
extension AVAudioPCMBuffer {
func array() -> [Float] {
return self.audioBufferList.pointee.mBuffers.array()
}
}
extension Array where Element: FloatingPoint {
mutating func buffer() -> AudioBuffer {
return AudioBuffer(mNumberChannels: 1, mDataByteSize: UInt32(self.count * MemoryLayout<Element>.size), mData: &self)
}
}
@jaekong
Copy link
Author

jaekong commented Oct 8, 2020

awesome! 👍

Thanks! 😊

@ratkins
Copy link

ratkins commented Jun 8, 2022

I'm getting Cannot use inout expression here; argument 'mData' must be a pointer that outlives the call to 'init(mNumberChannels:mDataByteSize:mData:)' on the &self in Xcode 13.4.1. I thought I'd be able to avoid this using withUnsafeMutablePointer(...) but I can't work out how.

(Edit: for future thread spelunkers, I've asked this question on SO and the Apple Dev Forums.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment