Skip to content

Instantly share code, notes, and snippets.

@0xfe
Created February 22, 2020 23:54
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 0xfe/0b8b66bf4e34caedcacb5894164e7c7c to your computer and use it in GitHub Desktop.
Save 0xfe/0b8b66bf4e34caedcacb5894164e7c7c to your computer and use it in GitHub Desktop.
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