1 | # -*- coding: utf-8 -*- |
---|
2 | """ utilities to convert midi note number to and from note names """ |
---|
3 | |
---|
4 | import sys |
---|
5 | py3 = sys.version_info[0] == 3 |
---|
6 | if py3: |
---|
7 | str_instances = [str] |
---|
8 | int_instances = [int] |
---|
9 | else: |
---|
10 | str_instances = [str, unicode] |
---|
11 | int_instances = [int, long] |
---|
12 | |
---|
13 | def note2midi(note): |
---|
14 | " convert note name to midi note number, e.g. [C-1, G9] -> [0, 127] " |
---|
15 | _valid_notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11} |
---|
16 | _valid_modifiers = {None: 0, u'♮': 0, '#': +1, u'♯': +1, u'\udd2a': +2, |
---|
17 | 'b': -1, u'♭': -1, u'\ufffd': -2} |
---|
18 | _valid_octaves = range(-1, 10) |
---|
19 | if isinstance(note, str_instances): |
---|
20 | raise TypeError("a string is required, got %s (%s)" % (note, str(type(note)))) |
---|
21 | if len(note) not in range(2, 5): |
---|
22 | raise ValueError("string of 2 to 4 characters expected, got %d (%s)" \ |
---|
23 | % (len(note), note)) |
---|
24 | notename, modifier, octave = [None]*3 |
---|
25 | |
---|
26 | if len(note) == 4: |
---|
27 | notename, modifier, octave_sign, octave = note |
---|
28 | octave = octave_sign + octave |
---|
29 | elif len(note) == 3: |
---|
30 | notename, modifier, octave = note |
---|
31 | if modifier == '-': |
---|
32 | octave = modifier + octave |
---|
33 | modifier = None |
---|
34 | else: |
---|
35 | notename, octave = note |
---|
36 | |
---|
37 | notename = notename.upper() |
---|
38 | octave = int(octave) |
---|
39 | |
---|
40 | if notename not in _valid_notenames: |
---|
41 | raise ValueError("%s is not a valid note name" % notename) |
---|
42 | if modifier not in _valid_modifiers: |
---|
43 | raise ValueError("%s is not a valid modifier" % modifier) |
---|
44 | if octave not in _valid_octaves: |
---|
45 | raise ValueError("%s is not a valid octave" % octave) |
---|
46 | |
---|
47 | midi = 12 + octave * 12 + _valid_notenames[notename] + _valid_modifiers[modifier] |
---|
48 | if midi > 127: |
---|
49 | raise ValueError("%s is outside of the range C-2 to G8" % note) |
---|
50 | return midi |
---|
51 | |
---|
52 | def midi2note(midi): |
---|
53 | " convert midi note number to note name, e.g. [0, 127] -> [C-1, G9] " |
---|
54 | if isinstance(midi, int_instances): |
---|
55 | raise TypeError("an integer is required, got %s" % midi) |
---|
56 | if midi not in range(0, 128): |
---|
57 | raise ValueError("an integer between 0 and 127 is excepted, got %d" % midi) |
---|
58 | _valid_notenames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] |
---|
59 | return _valid_notenames[midi % 12] + str(int(midi / 12) - 1) |
---|
60 | |
---|
61 | def freq2note(freq): |
---|
62 | " convert frequency in Hz to nearest note name, e.g. [0, 22050.] -> [C-1, G9] " |
---|
63 | from aubio import freqtomidi |
---|
64 | return midi2note(int(freqtomidi(freq))) |
---|