Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MIDI note helper
class Note:
values = {
"c": 0,
"d": 2,
"e": 4,
"f": 5,
"g": 7,
"a": 9,
"b": 11
}
names = ["C", "Cs", "D", "Ds", "E", "F", "Fs", "G", "Gs", "A", "As", "B"]
# Takes a note in the form "C#4", "Bb2", "A5", etc. and returns
# the MIDI note number.
@classmethod
def note(cls, str):
matches = re.match('^([ABCDEFGabcdefg])([b#s]?)([0-9])$', str)
note = matches.group(1).lower()
acc = matches.group(2).lower()
octave = int(matches.group(3))
shift = 0
if acc == "b":
shift -= 1
elif acc == '#':
shift += 1
elif acc == 's':
shift += 1
value = ((octave+1) * 12) + cls.values[note] + shift
return int(value)
@classmethod
def notes(cls, note_list):
return map(cls.note, note_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment