christopher@6: # -*- coding: utf-8 -*- christopher@6: """ christopher@6: Created on Sat Mar 21 22:19:52 2015 christopher@6: christopher@6: @author: christopherh christopher@6: """ christopher@6: christopher@6: from midiparser import MidiFile, MidiTrack, DeltaTime, MidiEvent christopher@6: #from RhythmParser import Bar christopher@6: christopher@6: from MusicObjects import * christopher@6: christopher@6: christopher@6: christopher@6: christopher@6: christopher@6: def readMidiFile(filename): christopher@6: """ open and read a MIDI file, return a MidiFile object """ christopher@6: christopher@6: #create a midifile object, open and read a midi file christopher@6: midiFile = MidiFile() christopher@6: midiFile.open(filename, 'rb') christopher@6: midiFile.read() christopher@6: midiFile.close() christopher@6: christopher@6: return midiFile christopher@6: christopher@6: def getBars(midiFile, trackindex=1): christopher@6: christopher@6: track = midiFile.tracks[trackindex] # ignore dummy track 0 christopher@6: eventIdx = 0 christopher@6: numNotes = 0 christopher@6: christopher@6: noteonlist = [] christopher@6: noteOnFound==True christopher@6: christopher@6: while noteOnFound==True: christopher@6: (noteOnIdx, noteOnDelta, noteOnFound) = self.findEvent(track, eventIdx, lambda e: e.type == 'NOTE_ON') christopher@6: noteEvent = track.events[noteOnIdx] christopher@6: eventIdx = noteOnIdx + 1 christopher@6: christopher@6: christopher@6: christopher@6: christopher@6: christopher@6: christopher@6: def findEvent(track, eventStartIdx, lambdaExpr): christopher@6: ''' christopher@6: From code by Csaba Sulyok: christopher@6: Finds MIDI event based on lambda expression, starting from a given index. christopher@6: Returns a tuple of the following 3 elements: christopher@6: 1. event index where the lambda expression is true christopher@6: 2. aggregate delta time from event start index until the found event christopher@6: 3. flag whether or not any value was found, or we've reached the end of the event queue christopher@6: ''' christopher@6: christopher@6: eventIdx = eventStartIdx christopher@6: deltaTime = 0 christopher@6: while eventIdx < len(track.events) and not lambdaExpr(track.events[eventIdx]): christopher@6: if track.events[eventIdx].type == 'DeltaTime': christopher@6: deltaTime += track.events[eventIdx].time christopher@6: eventIdx += 1 christopher@6: christopher@6: success = eventIdx < len(track.events) christopher@6: return (eventIdx, deltaTime, success) christopher@6: christopher@6: