libmidi.types.midifile

MIDI file.

Classes

MidiFile([format, tracks, division])

Class representing a MIDI 1.0 file.

class libmidi.types.midifile.MidiFile(format: int = 1, tracks: List[Track] = None, division: int = 480)

Class representing a MIDI 1.0 file. Complies with the standard MIDI 1.0 file format specification (https://www.midi.org/specifications/file-format-specifications/standard-midi-files).

A MIDI file is a binary file containing one or more tracks. They’re written with big-endian byte order. All MIDI files must start with the string ‘MThd’ followed by an unsigned 32 bit integer, which represent the number of tracks in the file.

__init__(format: int = 1, tracks: List[Track] = None, division: int = 480)

Initialize a new MIDI file.

__iter__()

Iterate over all events in the MIDI file.

static _fix_end_of_track(events: List[Event])

Remove all end_of_track messages and add one at the end.

This is used by merge_tracks() and MidiFile.save().

classmethod from_file(filename: Path | str) MidiFile

Read a MIDI file from a file.

classmethod from_stream(stream: BufferedReader) MidiFile

Read a MIDI file from a stream.

get_length()

Playback time in seconds.

This will be computed by going through every message in every track and adding up delta times.

merge_tracks()

Returns a MidiTrack object with all messages from all tracks.

The messages are returned in playback order with delta times as if they were all in one track.

play(meta_messages: bool = False)

Play back all tracks.

The generator will sleep between each message by default. Messages are yielded with correct timing. The time attribute is set to the number of seconds slept since the previous message.

By default you will only get normal MIDI messages. Pass meta_messages=True if you also want meta messages.

You will receive copies of the original messages, so you can safely modify them without ruining the tracks.

to_bytes() bytes

Return the MIDI file as a byte string.

to_file(filename: Path | str) int

Write the MIDI file to a file.

Returns the number of bytes written.