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

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

Merge branch 'master' into feature/docstrings

  • Property mode set to 100644
File size: 4.6 KB
RevLine 
[7d89e61]1# -*- coding: utf-8 -*-
[1827c498]2""" utilities to convert midi note number to and from note names """
[33102ab]3
[476cb41]4__all__ = ['note2midi', 'midi2note', 'freq2note', 'note2freq']
[744190f]5
[e76842e]6import sys
[6f944b5]7from ._aubio import freqtomidi, miditofreq
[1f07bdd]8
[1827c498]9py3 = sys.version_info[0] == 3
10if py3:
[016813e]11    str_instances = str
12    int_instances = int
[e76842e]13else:
[016813e]14    str_instances = (str, unicode)
15    int_instances = (int, long)
[e76842e]16
[33102ab]17def note2midi(note):
[7165fc56]18    """Convert note name to midi note number.
19
20    Input string `note` should be composed of one note root
21    and one octave, with optionally one modifier in between.
22
23    List of valid components:
24
25    - note roots: `C`, `D`, `E`, `F`, `G`, `A`, `B`,
26    - modifiers: `b`, `#`, as well as unicode characters
27      `𝄫`, `♭`, `♮`, `♯` and `𝄪`,
28    - octave numbers: `-1` -> `11`.
29
30    Parameters
31    ----------
32    note : str
33        note name
34
35    Returns
36    -------
37    int
38        corresponding midi note number
39
40    Examples
41    --------
42    >>> aubio.note2midi('C#4')
43    61
44    >>> aubio.note2midi('B♭5')
45    82
46
47    Raises
48    ------
49    TypeError
50        If `note` was not a string.
51    ValueError
52        If an error was found while converting `note`.
53
54    See Also
55    --------
56    midi2note, freqtomidi, miditofreq
57    """
[33102ab]58    _valid_notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11}
[3aad0b1]59    _valid_modifiers = {
60            u'𝄫': -2,                        # double flat
61            u'♭': -1, 'b': -1, '\u266d': -1, # simple flat
62            u'♮': 0, '\u266e': 0, None: 0,   # natural
63            '#': +1, u'♯': +1, '\u266f': +1, # sharp
64            u'𝄪': +2,                        # double sharp
65            }
[7d89e61]66    _valid_octaves = range(-1, 10)
[016813e]67    if not isinstance(note, str_instances):
[40136171]68        msg = "a string is required, got {:s} ({:s})"
69        raise TypeError(msg.format(str(type(note)), repr(note)))
[1827c498]70    if len(note) not in range(2, 5):
[40136171]71        msg = "string of 2 to 4 characters expected, got {:d} ({:s})"
72        raise ValueError(msg.format(len(note), note))
[33102ab]73    notename, modifier, octave = [None]*3
74
75    if len(note) == 4:
76        notename, modifier, octave_sign, octave = note
77        octave = octave_sign + octave
78    elif len(note) == 3:
79        notename, modifier, octave = note
80        if modifier == '-':
81            octave = modifier + octave
82            modifier = None
83    else:
84        notename, octave = note
85
86    notename = notename.upper()
87    octave = int(octave)
88
89    if notename not in _valid_notenames:
[b8ed85e]90        raise ValueError("%s is not a valid note name" % notename)
[33102ab]91    if modifier not in _valid_modifiers:
[b8ed85e]92        raise ValueError("%s is not a valid modifier" % modifier)
[33102ab]93    if octave not in _valid_octaves:
[b8ed85e]94        raise ValueError("%s is not a valid octave" % octave)
[33102ab]95
[40136171]96    midi = 12 + octave * 12 + _valid_notenames[notename] \
97            + _valid_modifiers[modifier]
[33102ab]98    if midi > 127:
[b8ed85e]99        raise ValueError("%s is outside of the range C-2 to G8" % note)
[33102ab]100    return midi
[9ead7a9]101
102def midi2note(midi):
[7165fc56]103    """Convert midi note number to note name.
104
105    Parameters
106    ----------
107    midi : int [0, 128]
108        input midi note number
109
110    Returns
111    -------
112    str
113        note name
114
115    Examples
116    --------
117    >>> aubio.midi2note(70)
118    'A#4'
119    >>> aubio.midi2note(59)
120    'B3'
121
122    Raises
123    ------
124    TypeError
125        If `midi` was not an integer.
126    ValueError
127        If `midi` is out of the range `[0, 128]`.
128
129    See Also
130    --------
131    note2midi, miditofreq, freqtomidi
132    """
[016813e]133    if not isinstance(midi, int_instances):
[b8ed85e]134        raise TypeError("an integer is required, got %s" % midi)
[1827c498]135    if midi not in range(0, 128):
[40136171]136        msg = "an integer between 0 and 127 is excepted, got {:d}"
137        raise ValueError(msg.format(midi))
138    _valid_notenames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#',
139            'A', 'A#', 'B']
[1827c498]140    return _valid_notenames[midi % 12] + str(int(midi / 12) - 1)
[3cc1491]141
142def freq2note(freq):
[7165fc56]143    """Convert frequency in Hz to nearest note name.
144
145    Parameters
146    ----------
147    freq : float [0, 23000[
148        input frequency, in Hz
149
150    Returns
151    -------
152    str
153        name of the nearest note
154
155    Example
156    -------
157    >>> aubio.freq2note(440)
158    'A4'
159    >>> aubio.freq2note(220.1)
160    'A3'
161    """
[44582b0]162    nearest_note = int(freqtomidi(freq) + .5)
163    return midi2note(nearest_note)
[6f944b5]164
165def note2freq(note):
166    """Convert note name to corresponding frequency, in Hz.
167
168    Parameters
169    ----------
170    note : str
171        input note name
172
173    Returns
174    -------
175    freq : float [0, 23000[
176        frequency, in Hz
177
178    Example
179    -------
180    >>> aubio.note2freq('A4')
181    440
182    >>> aubio.note2freq('A3')
183    220.1
184    """
185    midi = note2midi(note)
186    return miditofreq(midi)
Note: See TracBrowser for help on using the repository browser.