Last active
May 14, 2020 06:35
-
-
Save rknightly/55c4c5f9433a62a85e2f9784a482576b to your computer and use it in GitHub Desktop.
A Swift function that converts a note (eg. "A4") to a frequency (eg. 440.0)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MIT License | |
// Swift that converts a string note (eg. "A4") to a frequency (eg. 440.0). | |
// Inspired by https://gist.github.com/stuartmemo/3766449 | |
static func noteToFrequency (note: String) -> Double { | |
let notes = ["A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"] | |
let octave = Double(String(note.last!))! | |
var keyNumber = Double(notes.firstIndex(of: String(note.dropLast()))!) | |
if (keyNumber < 3) { | |
keyNumber += octave * 12 + 1 | |
} else { | |
keyNumber += (octave - 1) * 12 + 1 | |
} | |
return 440 * pow(2, (keyNumber - 49) / 12) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment