Skip to content

Instantly share code, notes, and snippets.

@jeremycochoy
Created February 7, 2020 20:41
Show Gist options
  • Save jeremycochoy/45346cbfe507ee9cb96a08c049dfd34f to your computer and use it in GitHub Desktop.
Save jeremycochoy/45346cbfe507ee9cb96a08c049dfd34f to your computer and use it in GitHub Desktop.
How to use Apple's Accelerate FFT in swift
//
// MIT LICENSE: Copy past as much as you want :)
//
// Your signal, array of length 1024
let signal: [Float] = (0 ... 1024)
// --- INITIALIZATION
// The length of the input
length = vDSP_Length(signal.count)
// The power of two of two times the length of the input.
// Do not forget this factor 2.
log2n = vDSP_Length(ceil(log2(Float(length * 2))))
// Create the instance of the FFT class which allow computing FFT of complex vector with length
// up to `length`.
fftSetup = vDSP.FFT(log2n: log2n, radix: .radix2, ofType: DSPSplitComplex.self)!
// --- Input / Output arrays
var forwardInputReal = [Float](signal) // Copy the signal here
var forwardInputImag = [Float](repeating: 0, count: Int(length))
var forwardOutputReal = [Float](repeating: 0, count: Int(length))
var forwardOutputImag = [Float](repeating: 0, count: Int(length))
var magnitudes = [Float](repeating: 0, count: Int(length))
/// --- Compute FFT
forwardInputReal.withUnsafeMutableBufferPointer { forwardInputRealPtr in
forwardInputImag.withUnsafeMutableBufferPointer { forwardInputImagPtr in
forwardOutputReal.withUnsafeMutableBufferPointer { forwardOutputRealPtr in
fforwardOutputImag.withUnsafeMutableBufferPointer { forwardOutputImagPtr in
// Input
let forwardInput = DSPSplitComplex(realp: forwardInputRealPtr.baseAddress!, imagp: forwardInputImagPtr.baseAddress!)
// Output
var forwardOutput = DSPSplitComplex(realp: forwardOutputRealPtr.baseAddress!, imagp: forwardOutputImagPtr.baseAddress!)
fftSetup.forward(input: forwardInput, output: &forwardOutput)
vDSP.absolute(forwardOutput, result: &magnitudes)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment