Skip to content

Instantly share code, notes, and snippets.

@jtodaone
Created August 10, 2019 14:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jtodaone/f2fa59c19794811dbe989dff65a772bc to your computer and use it in GitHub Desktop.
Save jtodaone/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)
}
}
@danielrc-ime
Copy link

awesome! 👍

@jtodaone
Copy link
Author

jtodaone 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