Skip to content

Instantly share code, notes, and snippets.

@jczimm
Last active January 18, 2016 00:49
Show Gist options
  • Save jczimm/e860401c0c7026f4d175 to your computer and use it in GitHub Desktop.
Save jczimm/e860401c0c7026f4d175 to your computer and use it in GitHub Desktop.
Calculates the frequency of a note provided on 12TET scale. (traditional Western scale)
const a4Freq = 440;
const noteNames = ["A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"];
function noteToFrequency(noteName) {
const [, noteLetter, octaveNum] = noteName.match(/^(\w#?)(\d)$/) || [];
const numStepsFromA = noteNames.indexOf(noteLetter.toUpperCase());
if (numStepsFromA === -1 || !noteLetter) return new Error("Invalid note");
const numStepsFromMiddleA = numStepsFromA + 12 * (octaveNum - 4);
return a4Freq * (2**(1/12)) ** numStepsFromMiddleA;
}
// example
console.log(noteToFrequency("a#4"))
@jczimm
Copy link
Author

jczimm commented Jan 18, 2016

Not accurate. Works with A4-G#4 in octave 4 (where octave 4 actually should end with A4-B4, since note after is C5).

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