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

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

python/lib/aubio/midiconv.py: make sure midi2note uses midi int (python3)

  • Property mode set to 100644
File size: 2.1 KB
Line 
1# -*- coding: utf-8 -*-
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(
12                "string of 2 to 4 characters expected, got %d (%s)" %
13                (len(note), note))
14    notename, modifier, octave = [None]*3
15
16    if len(note) == 4:
17        notename, modifier, octave_sign, octave = note
18        octave = octave_sign + octave
19    elif len(note) == 3:
20        notename, modifier, octave = note
21        if modifier == '-':
22            octave = modifier + octave
23            modifier = None
24    else:
25        notename, octave = note
26
27    notename = notename.upper()
28    octave = int(octave)
29
30    if notename not in _valid_notenames:
31        raise ValueError("%s is not a valid note name" % notename)
32    if modifier not in _valid_modifiers:
33        raise ValueError("%s is not a valid modifier" % modifier)
34    if octave not in _valid_octaves:
35        raise ValueError("%s is not a valid octave" % octave)
36
37    midi = 12 + octave * 12 + _valid_notenames[notename] + _valid_modifiers[modifier]
38    if midi > 127:
39        raise ValueError("%s is outside of the range C-2 to G8" % note)
40    return midi
41
42def midi2note(midi):
43    " convert midi note number to note name, e.g. [0, 127] -> [C-1, G9] "
44    if type(midi) != int:
45        raise TypeError("an integer is required, got %s" % midi)
46    if not (-1 < midi < 128):
47        raise ValueError(
48                "an integer between 0 and 127 is excepted, got %d" % midi)
49    midi = int(midi)
50    _valid_notenames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
51    return _valid_notenames[midi % 12] + str( int(midi / 12) - 1 )
52
53def freq2note(freq):
54    from aubio import freqtomidi
55    return midi2note(int(freqtomidi(freq)))
Note: See TracBrowser for help on using the repository browser.