Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert note to frequency
// Takes string of Note + Octave
// Example:
// var frequency = getFrequency('C3');
var getFrequency = function (note) {
var notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'],
octave,
keyNumber;
if (note.length === 3) {
octave = note.charAt(2);
} else {
octave = note.charAt(1);
}
keyNumber = notes.indexOf(note.slice(0, -1));
if (keyNumber < 3) {
keyNumber = keyNumber + 12 + ((octave - 1) * 12) + 1;
} else {
keyNumber = keyNumber + ((octave - 1) * 12) + 1;
}
// Return frequency of note
return 440 * Math.pow(2, (keyNumber- 49) / 12);
};
@EvanHahn

This comment has been minimized.

Copy link

@EvanHahn EvanHahn commented Sep 2, 2013

What's the licensing on this?

@cristiano-belloni

This comment has been minimized.

@1j01

This comment has been minimized.

Copy link

@1j01 1j01 commented Feb 19, 2015

@CGrassin

This comment has been minimized.

Copy link

@CGrassin CGrassin commented Apr 14, 2020

@rknightly

This comment has been minimized.

Copy link

@rknightly rknightly commented May 14, 2020

@MasterPuffin

This comment has been minimized.

Copy link

@MasterPuffin MasterPuffin commented Mar 2, 2021

Java Version

private double getFrequency(String note) {
        String[] notes = {"A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"};

        int octave = note.length() == 3 ? Integer.parseInt(String.valueOf(note.charAt(2))) : Integer.parseInt(String.valueOf(note.charAt(1)));
        int keyNumber = java.util.Arrays.asList(notes).indexOf(note.substring(0, note.length() - 1));

        if (keyNumber < 3) {
            keyNumber = keyNumber + 12 + ((octave - 1) * 12) + 1;
        } else {
            keyNumber = keyNumber + ((octave - 1) * 12) + 1;
        }

        // Return frequency of note
        return 440 * Math.pow(2, (float)(keyNumber - 49) / 12);
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment