source: python/lib/aubio/midiconv.py @ 33102ab

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

lib/aubio/midiconv.py: add note2midi

  • Property mode set to 100644
File size: 1.4 KB
Line 
1# -*- encoding: utf8 -*-
2
3def note2midi(note):
4    " convert a note name to a midi note value "
5    # from C-2 to G8, though we do accept everything in the upper octave
6    _valid_notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11}
7    _valid_modifiers = {None: 0, u'♮': 0, '#': +1, u'♯': +1, u'\udd2a': +2, 'b': -1, u'♭': -1, u'\ufffd': -2}
8    _valid_octaves = range(-1, 10) 
9    if not (1 < len(note) < 5):
10        raise ValueError, "string of 2 to 4 characters expected, got %d (%s)" % (len(note), note)
11    notename, modifier, octave = [None]*3
12
13    if len(note) == 4:
14        notename, modifier, octave_sign, octave = note
15        octave = octave_sign + octave
16    elif len(note) == 3:
17        notename, modifier, octave = note
18        if modifier == '-':
19            octave = modifier + octave
20            modifier = None
21    else:
22        notename, octave = note
23
24    notename = notename.upper()
25    octave = int(octave)
26
27    if notename not in _valid_notenames:
28        raise ValueError, "%s is not a valid note name" % notename
29    if modifier not in _valid_modifiers:
30        raise ValueError, "only # and b are acceptable modifiers, not %s" % modifier
31    if octave not in _valid_octaves:
32        raise ValueError, "%s is not a valid octave" % octave
33
34    midi = 12 + octave * 12 + _valid_notenames[notename] + _valid_modifiers[modifier]
35    if midi > 127:
36        raise ValueError, "%s is outside of the range C-2 to G8" % note
37    return midi
Note: See TracBrowser for help on using the repository browser.