christopher@6
|
1 # -*- coding: utf-8 -*-
|
christopher@6
|
2 """
|
christopher@6
|
3 Created on Sat Mar 21 22:19:52 2015
|
christopher@6
|
4
|
christopher@6
|
5 @author: christopherh
|
christopher@6
|
6 """
|
christopher@6
|
7
|
christopher@6
|
8 from midiparser import MidiFile, MidiTrack, DeltaTime, MidiEvent
|
christopher@6
|
9 #from RhythmParser import Bar
|
christopher@6
|
10
|
christopher@6
|
11 from MusicObjects import *
|
christopher@6
|
12
|
christopher@6
|
13
|
christopher@6
|
14
|
christopher@6
|
15
|
christopher@6
|
16
|
christopher@6
|
17 def readMidiFile(filename):
|
christopher@6
|
18 """ open and read a MIDI file, return a MidiFile object """
|
christopher@6
|
19
|
christopher@6
|
20 #create a midifile object, open and read a midi file
|
christopher@6
|
21 midiFile = MidiFile()
|
christopher@6
|
22 midiFile.open(filename, 'rb')
|
christopher@6
|
23 midiFile.read()
|
christopher@6
|
24 midiFile.close()
|
christopher@6
|
25
|
christopher@6
|
26 return midiFile
|
christopher@6
|
27
|
christopher@6
|
28 def getBars(midiFile, trackindex=1):
|
christopher@6
|
29
|
christopher@6
|
30 track = midiFile.tracks[trackindex] # ignore dummy track 0
|
christopher@6
|
31 eventIdx = 0
|
christopher@6
|
32 numNotes = 0
|
christopher@6
|
33
|
christopher@6
|
34 noteonlist = []
|
christopher@6
|
35 noteOnFound==True
|
christopher@6
|
36
|
christopher@6
|
37 while noteOnFound==True:
|
christopher@6
|
38 (noteOnIdx, noteOnDelta, noteOnFound) = self.findEvent(track, eventIdx, lambda e: e.type == 'NOTE_ON')
|
christopher@6
|
39 noteEvent = track.events[noteOnIdx]
|
christopher@6
|
40 eventIdx = noteOnIdx + 1
|
christopher@6
|
41
|
christopher@6
|
42
|
christopher@6
|
43
|
christopher@6
|
44
|
christopher@6
|
45
|
christopher@6
|
46
|
christopher@6
|
47 def findEvent(track, eventStartIdx, lambdaExpr):
|
christopher@6
|
48 '''
|
christopher@6
|
49 From code by Csaba Sulyok:
|
christopher@6
|
50 Finds MIDI event based on lambda expression, starting from a given index.
|
christopher@6
|
51 Returns a tuple of the following 3 elements:
|
christopher@6
|
52 1. event index where the lambda expression is true
|
christopher@6
|
53 2. aggregate delta time from event start index until the found event
|
christopher@6
|
54 3. flag whether or not any value was found, or we've reached the end of the event queue
|
christopher@6
|
55 '''
|
christopher@6
|
56
|
christopher@6
|
57 eventIdx = eventStartIdx
|
christopher@6
|
58 deltaTime = 0
|
christopher@6
|
59 while eventIdx < len(track.events) and not lambdaExpr(track.events[eventIdx]):
|
christopher@6
|
60 if track.events[eventIdx].type == 'DeltaTime':
|
christopher@6
|
61 deltaTime += track.events[eventIdx].time
|
christopher@6
|
62 eventIdx += 1
|
christopher@6
|
63
|
christopher@6
|
64 success = eventIdx < len(track.events)
|
christopher@6
|
65 return (eventIdx, deltaTime, success)
|
christopher@6
|
66
|
christopher@6
|
67
|