1 | # -*- coding: utf-8 -*- |
---|
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, "%s is not a valid modifier" % 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 |
---|
39 | |
---|
40 | def midi2note(midi): |
---|
41 | " convert midi note number to note name, e.g. [0, 127] -> [C-1, G9] " |
---|
42 | if type(midi) != int: |
---|
43 | raise TypeError, "an integer is required, got %s" % midi |
---|
44 | if not (-1 < midi < 128): |
---|
45 | raise ValueError, "an integer between 0 and 127 is excepted, got %d" % midi |
---|
46 | midi = int(midi) |
---|
47 | _valid_notenames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] |
---|
48 | return _valid_notenames[midi % 12] + str( midi / 12 - 1) |
---|