1 | # -*- encoding: utf8 -*- |
---|
2 | |
---|
3 | def note2midi(note): |
---|
4 | " convert note name to midi note number, e.g. [C-1, G9] -> [0, 127] " |
---|
5 | _valid_notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11} |
---|
6 | _valid_modifiers = {None: 0, u'♮': 0, '#': +1, u'♯': +1, u'\udd2a': +2, 'b': -1, u'♭': -1, u'\ufffd': -2} |
---|
7 | _valid_octaves = range(-1, 10) |
---|
8 | if type(note) not in (str, unicode): |
---|
9 | raise TypeError, "a string is required, got %s" % note |
---|
10 | if not (1 < len(note) < 5): |
---|
11 | raise ValueError, "string of 2 to 4 characters expected, got %d (%s)" % (len(note), note) |
---|
12 | notename, modifier, octave = [None]*3 |
---|
13 | |
---|
14 | if len(note) == 4: |
---|
15 | notename, modifier, octave_sign, octave = note |
---|
16 | octave = octave_sign + octave |
---|
17 | elif len(note) == 3: |
---|
18 | notename, modifier, octave = note |
---|
19 | if modifier == '-': |
---|
20 | octave = modifier + octave |
---|
21 | modifier = None |
---|
22 | else: |
---|
23 | notename, octave = note |
---|
24 | |
---|
25 | notename = notename.upper() |
---|
26 | octave = int(octave) |
---|
27 | |
---|
28 | if notename not in _valid_notenames: |
---|
29 | raise ValueError, "%s is not a valid note name" % notename |
---|
30 | if modifier not in _valid_modifiers: |
---|
31 | raise ValueError, "only # and b are acceptable modifiers, not %s" % modifier |
---|
32 | if octave not in _valid_octaves: |
---|
33 | raise ValueError, "%s is not a valid octave" % octave |
---|
34 | |
---|
35 | midi = 12 + octave * 12 + _valid_notenames[notename] + _valid_modifiers[modifier] |
---|
36 | if midi > 127: |
---|
37 | raise ValueError, "%s is outside of the range C-2 to G8" % note |
---|
38 | return midi |
---|