From: Paul Brossier Date: Sun, 10 Mar 2013 16:14:49 +0000 (-0500) Subject: lib/aubio/midiconv.py: add note2 midi X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=9ead7a9b1a1fe5c4b53480925c7f6890212f7689;p=aubio.git lib/aubio/midiconv.py: add note2 midi --- diff --git a/python/lib/aubio/midiconv.py b/python/lib/aubio/midiconv.py index a42b69f6..e658290a 100644 --- a/python/lib/aubio/midiconv.py +++ b/python/lib/aubio/midiconv.py @@ -36,3 +36,13 @@ def note2midi(note): if midi > 127: raise ValueError, "%s is outside of the range C-2 to G8" % note return midi + +def midi2note(midi): + " convert midi note number to note name, e.g. [0, 127] -> [C-1, G9] " + if type(midi) != int: + 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) + _valid_notenames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] + return _valid_notenames[midi % 12] + str( midi / 12 - 1) diff --git a/python/tests/test_midi2note.py b/python/tests/test_midi2note.py new file mode 100644 index 00000000..cf865d6d --- /dev/null +++ b/python/tests/test_midi2note.py @@ -0,0 +1,42 @@ +# -*- encoding: utf8 -*- + +from aubio import midi2note +import unittest + +list_of_known_midis = ( + ( 0, 'C-1' ), + ( 1, 'C#-1' ), + ( 38, 'D2' ), + ( 48, 'C3' ), + ( 59, 'B3' ), + ( 60, 'C4' ), + ( 127, 'G9' ), + ) + +class TestMidi2NoteGoodValues(unittest.TestCase): + + def test_midi2note_known_values(self): + " known values are correctly converted " + for midi, note in list_of_known_midis: + self.assertEqual ( midi2note(midi), note ) + +class TestNote2MidiWrongValues(unittest.TestCase): + + def test_midi2note_negative_value(self): + " fails when passed a negative value " + self.assertRaises(ValueError, midi2note, -2) + + def test_midi2note_negative_value(self): + " fails when passed a value greater than 127 " + self.assertRaises(ValueError, midi2note, 128) + + def test_midi2note_floating_value(self): + " fails when passed a floating point " + self.assertRaises(TypeError, midi2note, 69.2) + + def test_midi2note_character_value(self): + " fails when passed a value that can not be transformed to integer " + self.assertRaises(TypeError, midi2note, "a") + +if __name__ == '__main__': + unittest.main()