A class that generates MIDI files from MidiTracks.
| 27 | |
| 28 | |
| 29 | class MidiFile(object): |
| 30 | |
| 31 | """A class that generates MIDI files from MidiTracks.""" |
| 32 | |
| 33 | tracks = [] |
| 34 | time_division = b"\x00\x48" |
| 35 | |
| 36 | def __init__(self, tracks=None): |
| 37 | if tracks is None: |
| 38 | tracks = [] |
| 39 | self.reset() |
| 40 | self.tracks = tracks |
| 41 | |
| 42 | def get_midi_data(self): |
| 43 | """Collect and return the raw, binary MIDI data from the tracks.""" |
| 44 | tracks = [t.get_midi_data() for t in self.tracks if t.track_data != b""] |
| 45 | return self.header() + b"".join(tracks) |
| 46 | |
| 47 | def header(self): |
| 48 | """Return a header for type 1 MIDI file.""" |
| 49 | tracks = a2b_hex("%04x" % len([t for t in self.tracks if t.track_data != ""])) |
| 50 | return b"MThd\x00\x00\x00\x06\x00\x01" + tracks + self.time_division |
| 51 | |
| 52 | def reset(self): |
| 53 | """Reset every track.""" |
| 54 | [t.reset() for t in self.tracks] |
| 55 | |
| 56 | def write_file(self, file, verbose=False): |
| 57 | """Collect the data from get_midi_data and write to file.""" |
| 58 | dat = self.get_midi_data() |
| 59 | try: |
| 60 | f = open(file, "wb") |
| 61 | except: |
| 62 | print("Couldn't open '%s' for writing." % file) |
| 63 | return False |
| 64 | try: |
| 65 | f.write(dat) |
| 66 | except: |
| 67 | print("An error occured while writing data to %s." % file) |
| 68 | return False |
| 69 | f.close() |
| 70 | if verbose: |
| 71 | print("Written %d bytes to %s." % (len(dat), file)) |
| 72 | return True |
| 73 | |
| 74 | |
| 75 | def write_Note(file, note, bpm=120, repeat=0, verbose=False): |
no outgoing calls
no test coverage detected