Skip to content

Instantly share code, notes, and snippets.

@off-by-some
Created July 31, 2015 02:11
Show Gist options
  • Select an option

  • Save off-by-some/8cd8a3c4a9f4d9a1e3d9 to your computer and use it in GitHub Desktop.

Select an option

Save off-by-some/8cd8a3c4a9f4d9a1e3d9 to your computer and use it in GitHub Desktop.
Calculating notes from frequencies
let n = (a, i, b) => Math.log(i/b) / Math.log(a)
function findNote(freq, base=440.00) {
let notes = ["A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"]
let octave = 4
const a = Math.pow(2, 1 / 12)
// Our base of A4
const b = base
// How many steps away are we from our base
let halfSteps = Math.round(n(a, freq, b))
let octaveDifference = Math.round(halfSteps / 12)
let stepDifference = Math.round(halfSteps % 12)
let newOctave = octave + octaveDifference
let note = stepDifference >= 0 ? notes[stepDifference] : notes.slice(stepDifference)[0]
return note + newOctave
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment