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@10: from music_objects import * christopher@6: christopher@6: christopher@6: christopher@6: christopher@6: christopher@10: def read_midi_file(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@10: # def get_bars(midiFile, trackindex=1): christopher@10: # """ returns a list of bar objects from a MidiFile object """ christopher@6: christopher@10: # # select a track to extract (default = 1, ignoring dummy track 0) christopher@10: # track = midiFile.tracks[trackindex] christopher@10: # eventIndex = 0 christopher@10: # numNotes = 0 christopher@6: christopher@10: # noteonlist = [] christopher@10: # noteOnFound==True christopher@6: christopher@10: # while noteOnFound==True: christopher@10: # (noteOnIndex, noteOnDelta, noteOnFound) = self.find_event(track, eventIndex, lambda e: e.type == 'NOTE_ON') christopher@10: # noteEvent = track.events[noteOnIndex] christopher@10: # eventIndex = noteOnIndex + 1 christopher@6: christopher@6: christopher@6: christopher@6: christopher@6: christopher@6: christopher@10: def find_event(track, eventStartIndex, 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@10: eventIndex = eventStartIndex christopher@6: deltaTime = 0 christopher@10: while eventIndex < len(track.events) and not lambdaExpr(track.events[eventIndex]): christopher@10: if track.events[eventIndex].type == 'DeltaTime': christopher@10: deltaTime += track.events[eventIndex].time christopher@10: eventIndex += 1 christopher@6: christopher@10: success = eventIndex < len(track.events) christopher@10: return (eventIndex, deltaTime, success) christopher@6: christopher@6: