From: Paul Brossier Date: Tue, 10 May 2016 19:03:10 +0000 (+0200) Subject: python/lib/aubio/midiconv.py: clean up, add some documentation X-Git-Tag: 0.4.4~300^2~98 X-Git-Url: https://git.aubio.org/?p=aubio.git;a=commitdiff_plain;h=1827c498cf3df3b76d27c5ea8a4d3552f5ba60e4 python/lib/aubio/midiconv.py: clean up, add some documentation --- diff --git a/python/lib/aubio/midiconv.py b/python/lib/aubio/midiconv.py index a2bcfb22..8952d44d 100644 --- 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 note2midi(note): 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)))