Merge branch 'master' into feature/earlynoteoff
[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', 'note2freq']
5
6 import sys
7 from ._aubio import freqtomidi, miditofreq
8
9 py3 = sys.version_info[0] == 3
10 if py3:
11     str_instances = str
12     int_instances = int
13 else:
14     str_instances = (str, unicode)
15     int_instances = (int, long)
16
17 def note2midi(note):
18     " convert note name to midi note number, e.g. [C-1, G9] -> [0, 127] "
19     _valid_notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11}
20     _valid_modifiers = {
21             u'𝄫': -2,                        # double flat
22             u'♭': -1, 'b': -1, '\u266d': -1, # simple flat
23             u'♮': 0, '\u266e': 0, None: 0,   # natural
24             '#': +1, u'♯': +1, '\u266f': +1, # sharp
25             u'𝄪': +2,                        # double sharp
26             }
27     _valid_octaves = range(-1, 10)
28     if not isinstance(note, str_instances):
29         msg = "a string is required, got {:s} ({:s})"
30         raise TypeError(msg.format(str(type(note)), repr(note)))
31     if len(note) not in range(2, 5):
32         msg = "string of 2 to 4 characters expected, got {:d} ({:s})"
33         raise ValueError(msg.format(len(note), note))
34     notename, modifier, octave = [None]*3
35
36     if len(note) == 4:
37         notename, modifier, octave_sign, octave = note
38         octave = octave_sign + octave
39     elif len(note) == 3:
40         notename, modifier, octave = note
41         if modifier == '-':
42             octave = modifier + octave
43             modifier = None
44     else:
45         notename, octave = note
46
47     notename = notename.upper()
48     octave = int(octave)
49
50     if notename not in _valid_notenames:
51         raise ValueError("%s is not a valid note name" % notename)
52     if modifier not in _valid_modifiers:
53         raise ValueError("%s is not a valid modifier" % modifier)
54     if octave not in _valid_octaves:
55         raise ValueError("%s is not a valid octave" % octave)
56
57     midi = 12 + octave * 12 + _valid_notenames[notename] \
58             + _valid_modifiers[modifier]
59     if midi > 127:
60         raise ValueError("%s is outside of the range C-2 to G8" % note)
61     return midi
62
63 def midi2note(midi):
64     " convert midi note number to note name, e.g. [0, 127] -> [C-1, G9] "
65     if not isinstance(midi, int_instances):
66         raise TypeError("an integer is required, got %s" % midi)
67     if midi not in range(0, 128):
68         msg = "an integer between 0 and 127 is excepted, got {:d}"
69         raise ValueError(msg.format(midi))
70     _valid_notenames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#',
71             'A', 'A#', 'B']
72     return _valid_notenames[midi % 12] + str(int(midi / 12) - 1)
73
74 def freq2note(freq):
75     " convert frequency in Hz to nearest note name, e.g. [0, 22050.] -> [C-1, G9] "
76     nearest_note = int(freqtomidi(freq) + .5)
77     return midi2note(nearest_note)
78
79 def note2freq(note):
80     """Convert note name to corresponding frequency, in Hz.
81
82     Parameters
83     ----------
84     note : str
85         input note name
86
87     Returns
88     -------
89     freq : float [0, 23000[
90         frequency, in Hz
91
92     Example
93     -------
94     >>> aubio.note2freq('A4')
95     440
96     >>> aubio.note2freq('A3')
97     220.1
98     """
99     midi = note2midi(note)
100     return miditofreq(midi)