ref: 9ead7a9b1a1fe5c4b53480925c7f6890212f7689
parent: f552e9eeba39ccce2e021af1ff6b899cf974eec1
author: Paul Brossier <piem@piem.org>
date: Sun Mar 10 07:14:49 EDT 2013
lib/aubio/midiconv.py: add note2 midi
--- a/python/lib/aubio/midiconv.py
+++ b/python/lib/aubio/midiconv.py
@@ -36,3 +36,13 @@
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)
--- /dev/null
+++ b/python/tests/test_midi2note.py
@@ -1,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()