source: python/lib/aubio/midiconv.py @ f552e9e

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5pitchshiftsamplertimestretchyinfft+
Last change on this file since f552e9e was f552e9e, checked in by Paul Brossier <piem@piem.org>, 11 years ago

lib/aubio/midiconv.py: improve note2midi

  • Property mode set to 100644
File size: 1.5 KB
Line 
1# -*- encoding: utf8 -*-
2
3def 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
Note: See TracBrowser for help on using the repository browser.