Skip to content

Instantly share code, notes, and snippets.

@anthonyholmes
Created February 18, 2020 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonyholmes/7617e2f899a321080e11a2aba60d265a to your computer and use it in GitHub Desktop.
Save anthonyholmes/7617e2f899a321080e11a2aba60d265a to your computer and use it in GitHub Desktop.
Note to Midi Number
/**
* 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