'''
Created on 8 dec. 2009

@author: Samuel Benveniste
'''

from mxmMidi.MidiOutStream import MidiOutStream

class MidiToSong(MidiOutStream):
    '''
    Creates songs from midi files using mxmMidi package
    '''
    def __init__(self):
        self.midiNoteNumbers = []
        self.noteLengths = []
        self.quarterNoteLength = 500
        self.firstNoteOn = True
        self._lastNoteOnTime = 0

    def header(self, format=0, nTracks=1, division=96):
        print 'format: %s, nTracks: %s, division: %s' % (format, nTracks, division)
        print '----------------------------------'
        print ''
        self.division = division
    
    def tempo(self,value):
        self.quarterNoteLength = value/1000
        print "quarterNoteLength in ms :" + str(self.quarterNoteLength)   
        
    def note_on(self, channel=0, note=0x40, velocity=0x40):
        self.midiNoteNumbers.append(note)
        # if it's the first note_on take note of time (the song begins here)
        # from the second note_on and after, mark the length of the preceding note
        if self.firstNoteOn :
            self.firstNoteOn = False
            self._lastNoteOnTime = self.abs_time()
        else :
            self.noteLengths.append(float(self.abs_time()-self._lastNoteOnTime)/float(self.division))
            self._lastNoteOnTime = self.abs_time()
            
    def eof(self):
        self.noteLengths.append(4)
        for i in range(len(self.midiNoteNumbers)):
            print "note number :" + str(self.midiNoteNumbers[i]) + ", length in quarter Notes :" + str(self.noteLengths[i])
        print"--------------"
        print "end of file"
            
if __name__ == '__main__':

    # get data
    test_file = '../songs/midis/test.mid'
    f = open(test_file, 'rb')
    
    # do parsing
    from mxmMidi.MidiInFile import MidiInFile
    mts = MidiToSong()
    midiIn = MidiInFile(mts, f)
    midiIn.read()
    f.close()
        