# -*- encoding: utf8 -*-
def note2midi(note):
- " convert a note name to a midi note value "
- # from C-2 to G8, though we do accept everything in the upper octave
+ " 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_octaves = range(-1, 10)
+ if type(note) not in (str, unicode):
+ raise TypeError, "a string is required, got %s" % note
if not (1 < len(note) < 5):
raise ValueError, "string of 2 to 4 characters expected, got %d (%s)" % (len(note), note)
notename, modifier, octave = [None]*3
( 'B#3', 60 ),
( 'A4', 69 ),
( 'A#4', 70 ),
+ ( 'Bb4', 70 ),
+ ( u'B♭4', 70 ),
( 'G8', 115 ),
( u'G♯8', 116 ),
- ( u'G♭9', 126 ),
( 'G9', 127 ),
( u'G\udd2a2', 45 ),
( u'B\ufffd2', 45 ),
self.assertRaises(ValueError, note2midi, 'C')
def test_note2midi_wrong_modifier(self):
- " fails when passed an invalid note name"
+ " fails when passed a note with an invalid modifier "
self.assertRaises(ValueError, note2midi, 'C.1')
- def test_note2midi_wronge_midifier_again(self):
- " fails when passed a wrong modifier"
+ def test_note2midi_another_wrong_modifier_again(self):
+ " fails when passed a note with a invalid note name "
self.assertRaises(ValueError, note2midi, 'CB-3')
def test_note2midi_wrong_octave(self):
- " fails when passed a wrong octave"
+ " fails when passed a wrong octave number "
self.assertRaises(ValueError, note2midi, 'CBc')
def test_note2midi_out_of_range(self):
- " fails when passed a non-existing note"
+ " fails when passed a out of range note"
self.assertRaises(ValueError, note2midi, 'A9')
+ def test_note2midi_wrong_data_type(self):
+ " fails when passed a non-string value "
+ self.assertRaises(TypeError, note2midi, 123)
+
if __name__ == '__main__':
unittest.main()