MCPcopy Create free account
hub / github.com/bspaans/python-mingus / MidiFile

Class MidiFile

mingus/midi/midi_file_out.py:29–72  ·  view source on GitHub ↗

A class that generates MIDI files from MidiTracks.

Source from the content-addressed store, hash-verified

27
28
29class 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
75def write_Note(file, note, bpm=120, repeat=0, verbose=False):

Callers 5

write_NoteFunction · 0.70
write_NoteContainerFunction · 0.70
write_BarFunction · 0.70
write_TrackFunction · 0.70
write_CompositionFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected