ref: 1827c498cf3df3b76d27c5ea8a4d3552f5ba60e4
parent: cb89e51eaf7b7857d1f849fcb539a26ad51e9126
author: Paul Brossier <piem@piem.org>
date: Tue May 10 17:03:10 EDT 2016
python/lib/aubio/midiconv.py: clean up, add some documentation
--- a/python/lib/aubio/midiconv.py
+++ b/python/lib/aubio/midiconv.py
@@ -1,23 +1,26 @@
# -*- coding: utf-8 -*-
+""" utilities to convert midi note number to and from note names """
import sys
-PY3 = sys.version_info[0] == 3
-if PY3:
- string_types = [str]
+py3 = sys.version_info[0] == 3
+if py3:
+ str_instances = [str]
+ int_instances = [int]
else:
- string_types = [str, unicode]
+ str_instances = [str, unicode]
+ int_instances = [int, long]
def note2midi(note):
" convert note name to midi note number, e.g. [C-1, G9] -> [0, 127] "
_valid_notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11}
- _valid_modifiers = {None: 0, u'♮': 0, '#': +1, u'♯': +1, u'\udd2a': +2, 'b': -1, u'♭': -1, u'\ufffd': -2}
+ _valid_modifiers = {None: 0, u'♮': 0, '#': +1, u'♯': +1, u'\udd2a': +2,
+ 'b': -1, u'♭': -1, u'\ufffd': -2}
_valid_octaves = range(-1, 10)
- if type(note) not in string_types:
- raise TypeError("a string is required, got %s (%s)" % (note, str(type(note)) ))
- if not (1 < len(note) < 5):
- raise ValueError(
- "string of 2 to 4 characters expected, got %d (%s)" %
- (len(note), note))
+ if isinstance(note, str_instances):
+ raise TypeError("a string is required, got %s (%s)" % (note, str(type(note))))
+ if len(note) not in range(2, 5):
+ raise ValueError("string of 2 to 4 characters expected, got %d (%s)" \
+ % (len(note), note))
notename, modifier, octave = [None]*3
if len(note) == 4:
@@ -48,15 +51,14 @@
def midi2note(midi):
" convert midi note number to note name, e.g. [0, 127] -> [C-1, G9] "
- if type(midi) != int:
+ if isinstance(midi, int_instances):
raise TypeError("an integer is required, got %s" % midi)
- if not (-1 < midi < 128):
- raise ValueError(
- "an integer between 0 and 127 is excepted, got %d" % midi)
- midi = int(midi)
+ if midi not in range(0, 128):
+ raise ValueError("an integer between 0 and 127 is excepted, got %d" % midi)
_valid_notenames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
- return _valid_notenames[midi % 12] + str( int(midi / 12) - 1 )
+ return _valid_notenames[midi % 12] + str(int(midi / 12) - 1)
def freq2note(freq):
+ " convert frequency in Hz to nearest note name, e.g. [0, 22050.] -> [C-1, G9] "
from aubio import freqtomidi
return midi2note(int(freqtomidi(freq)))