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