Skip to content

Instantly share code, notes, and snippets.

@saiki-k
Last active July 24, 2020 12:42
Show Gist options
  • Save saiki-k/945783e4ab0d7c6cffc7ee6cef491595 to your computer and use it in GitHub Desktop.
Save saiki-k/945783e4ab0d7c6cffc7ee6cef491595 to your computer and use it in GitHub Desktop.
Functions to calculate the frequency of a musical note, octave range between two musical notes / musical note frequencies
const getNoteDistanceFromC0 = note => {
// Notes in an octave
const noteNumberMap = { "C": 1, "C#": 2, "D♭": 2, "D": 3, "D#": 4, "E♭": 4, "E": 5, "F": 6, "F#": 7, "G♭": 7, "G": 8, "G#": 9, "A♭": 9, "A": 10, "A#": 11, "B♭": 11, "B": 12 };
const getOctaveNum = note => note.charAt(note.length - 1);
return noteNumberMap[note.slice(0, -1)] - 1 + (getOctaveNum(note) * 12);
};
const getOctaveRange = (note1, note2) =>
(getNoteDistanceFromC0(note2) - getNoteDistanceFromC0(note1)) / 12;
/*
** Formula based from — http://www.techlib.com/reference/musical_note_frequencies.htm
** 440Hz is the frequency of A4, which is 57 notes away from C0
*/
const getFrequencyOfNoteInHz = note => 440 * Math.pow(2, (getNoteDistanceFromC0(note) - 57) / 12);
/*
** Formula based from — https://en.wikipedia.org/wiki/Octave
*/
const getOctaveRangeWithFrequencies = (note1, note2) => {
const getBaseLog = (x, y) => Math.log(y) / Math.log(x);
return getBaseLog(
2, getFrequencyOfNoteInHz(note2) / getFrequencyOfNoteInHz(note1)
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment