Created
February 18, 2020 22:08
-
-
Save anthonyholmes/7617e2f899a321080e11a2aba60d265a to your computer and use it in GitHub Desktop.
Note to Midi Number
This file contains hidden or 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
/** | |
* Get the midi note number of a note string | |
* | |
* @param {string} note | |
* | |
* @returns {number} MIDI note number | |
*/ | |
function getMidiNumber(note) { | |
// Based on 1st octave of each note | |
const NoteBaseNumbers = { | |
a: 33, | |
b: 35, | |
c: 24, | |
d: 26, | |
e: 28, | |
f: 29, | |
g: 31 | |
} | |
let noteParts = [...note.toLowerCase()] | |
let letter = noteParts[0] | |
let octave = parseInt(noteParts[noteParts.length - 1]) | |
let accidental = noteParts.length > 2 ? noteParts[1] : false | |
if (!Object.keys(NoteBaseNumbers).includes(letter)) { | |
throw `That note does not exist.` | |
} | |
if (noteParts.length > 3) { | |
throw `MIDI don't go that high!` | |
} | |
/** | |
* CALCULATIONS | |
*/ | |
let octaveModifier = (octave - 1) * 12 | |
let baseValue = NoteBaseNumbers[letter] | |
let value = baseValue + octaveModifier | |
if (accidental && accidental === 'b') { | |
value-- | |
} | |
if (accidental && accidental === '#') { | |
value++ | |
} | |
// Lowest note is A0 with value of 21 | |
if (value < 21) { | |
throw `That note does not exist.` | |
} | |
return value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment