Library Reference

Messages

class mido.Message(type, **arguments)

MIDI message class.

bin()

Encode message and return as a bytearray.

This can be used to write the message to a file.

bytes()

Encode message and return as a list of integers.

copy(**overrides)

Return a copy of the message.

Attributes will be overridden by the passed keyword arguments. Only message specific attributes can be overridden. The message type can not be changed.

Example:

a = Message(‘note_on’) b = a.copy(velocity=32)
hex(sep=' ')

Encode message and return as a string of hex numbers,

Each number is separated by the string sep.

Ports

mido.open_input(name=None, virtual=False, callback=None, **kwargs)

Open an input port.

If the environment variable MIDO_DEFAULT_INPUT is set, if will override the default port.

virtual=False
Passing True opens a new port that other applications can connect to. Raises IOError if not supported by the backend.
callback=None
A callback function to be called when a new message arrives. The function should take one argument (the message). Raises IOError if not supported by the backend.
mido.open_output(name=None, virtual=False, autoreset=False, **kwargs)

Open an output port.

If the environment variable MIDO_DEFAULT_OUTPUT is set, if will override the default port.

virtual=False
Passing True opens a new port that other applications can connect to. Raises IOError if not supported by the backend.
autoreset=False
Automatically send all_notes_off and reset_all_controllers on all channels. This is the same as calling port.reset().
mido.open_ioport(name=None, virtual=False, callback=None, autoreset=False, **kwargs)

Open a port for input and output.

If the environment variable MIDO_DEFAULT_IOPORT is set, if will override the default port.

virtual=False
Passing True opens a new port that other applications can connect to. Raises IOError if not supported by the backend.
callback=None
A callback function to be called when a new message arrives. The function should take one argument (the message). Raises IOError if not supported by the backend.
autoreset=False
Automatically send all_notes_off and reset_all_controllers on all channels. This is the same as calling port.reset().
mido.get_input_names(**kwargs)

Return a sorted list of all input port names.

mido.get_output_names(**kwargs)

Return a sorted list of all output port names.

mido.get_ioport_names(**kwargs)

Return a sorted list of all I/O port names.

Backends

mido.set_backend(name=None)

Set current backend.

name can be a module name like ‘mido.backends.rtmidi’ or a Backend object.

If no name is passed, the default backend will be used.

This will replace all the open_*() and get_*_name() functions in top level mido module. The module will be loaded the first time one of those functions is called.

class mido.Backend(name=None, api=None, load=False, use_environ=True)

Wrapper for backend module.

A backend module implements classes for input and output ports for a specific MIDI library. The Backend object wraps around the object and provides convenient ‘open_*()’ and ‘get_*_names()’ functions.

get_input_names(**kwargs)

Return a sorted list of all input port names.

get_ioport_names(**kwargs)

Return a sorted list of all I/O port names.

get_output_names(**kwargs)

Return a sorted list of all output port names.

load()

Load the module.

Does nothing if the module is already loaded.

This function will be called if you access the ‘module’ property.

loaded

Return True if the module is loaded.

module

A reference module implementing the backend.

This will always be a valid reference to a module. Accessing this property will load the module. Use .loaded to check if the module is loaded.

open_input(name=None, virtual=False, callback=None, **kwargs)

Open an input port.

If the environment variable MIDO_DEFAULT_INPUT is set, if will override the default port.

virtual=False
Passing True opens a new port that other applications can connect to. Raises IOError if not supported by the backend.
callback=None
A callback function to be called when a new message arrives. The function should take one argument (the message). Raises IOError if not supported by the backend.
open_ioport(name=None, virtual=False, callback=None, autoreset=False, **kwargs)

Open a port for input and output.

If the environment variable MIDO_DEFAULT_IOPORT is set, if will override the default port.

virtual=False
Passing True opens a new port that other applications can connect to. Raises IOError if not supported by the backend.
callback=None
A callback function to be called when a new message arrives. The function should take one argument (the message). Raises IOError if not supported by the backend.
autoreset=False
Automatically send all_notes_off and reset_all_controllers on all channels. This is the same as calling port.reset().
open_output(name=None, virtual=False, autoreset=False, **kwargs)

Open an output port.

If the environment variable MIDO_DEFAULT_OUTPUT is set, if will override the default port.

virtual=False
Passing True opens a new port that other applications can connect to. Raises IOError if not supported by the backend.
autoreset=False
Automatically send all_notes_off and reset_all_controllers on all channels. This is the same as calling port.reset().

Parsing

mido.parse(data)

Parse MIDI data and return the first message found.

Data after the first message is ignored. Use parse_all() to parse more than one message.

mido.parse_all(data)

Parse MIDI data and return a list of all messages found.

This is typically used to parse a little bit of data with a few messages in it. It’s best to use a Parser object for larger amounts of data. Also, tt’s often easier to use parse() if you know there is only one message in the data.

class mido.Parser(data=None)

MIDI Parser

Parses a stream of bytes and produces messages.

Data can be put into the parser in the form of integers, byte arrays or byte strings.

feed(data)

Feed MIDI data to the parser.

Accepts any object that produces a sequence of integers in range 0..255, such as:

[0, 1, 2] (0, 1, 2) [for i in range(256)] (for i in range(256)] bytearray() b’’ # Will be converted to integers in Python 2.
feed_byte(byte)

Feed one MIDI byte into the parser.

The byte must be an integer in range 0..255.

get_message()

Get the first parsed message.

Returns None if there is no message yet. If you don’t want to deal with None, you can use pending() to see how many messages you can get before you get None.

pending()

Return the number of pending messages.

MIDI Files

class mido.MidiFile(filename=None, file=None, type=1, ticks_per_beat=480, charset='latin1', debug=False)
add_track(name=None)

Add a new track to the file.

This will create a new MidiTrack object and append it to the track list.

length

Playback time in seconds.

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

play(meta_messages=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.

print_tracks(meta_only=False)

Prints out all messages in a .midi file.

May take argument meta_only to show only meta messages.

Use: print_tracks() -> will print all messages print_tracks(meta_only=True) -> will print only MetaMessages

save(filename=None, file=None)

Save to a file.

If file is passed the data will be saved to that file. This is typically an in-memory file or and already open file like sys.stdout.

If filename is passed the data will be saved to that file.

Raises ValueError if both file and filename are None, or if a type 0 file has != one track.

class mido.MidiTrack
append()

Append object to the end of the list.

clear()

Remove all items from list.

copy()

Return a shallow copy of the list.

count()

Return number of occurrences of value.

extend()

Extend list by appending elements from the iterable.

index()

Return first index of value.

Raises ValueError if the value is not present.

insert()

Insert object before index.

name

Name of the track.

This will return the name from the first track_name meta message in the track, or ‘’ if there is no such message.

Setting this property will update the name field of the first track_name message in the track. If no such message is found, one will be added to the beginning of the track with a delta time of 0.

pop()

Remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.

remove()

Remove first occurrence of value.

Raises ValueError if the value is not present.

reverse()

Reverse IN PLACE.

sort()

Stable sort IN PLACE.

class mido.MetaMessage(type_, **kwargs)
bin()

Encode message and return as a bytearray.

This can be used to write the message to a file.

bytes()
copy(**overrides)

Return a copy of the message.

Attributes will be overridden by the passed keyword arguments. Only message specific attributes can be overridden. The message type can not be changed.

Example:

a = Message(‘note_on’) b = a.copy(velocity=32)
hex(sep=' ')

Encode message and return as a string of hex numbers,

Each number is separated by the string sep.

mido.bpm2tempo(bpm)

Convert beats per minute to MIDI file tempo.

Returns microseconds per beat as an integer:

240 => 250000
120 => 500000
60 => 1000000
mido.tempo2bpm(tempo)

Convert MIDI file tempo to BPM.

Returns BPM as an integer or float:

250000 => 240
500000 => 120
1000000 => 60
mido.merge_tracks(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.

SYX Files

mido.read_syx_file(filename)

Read sysex messages from SYX file.

Returns a list of sysex messages.

This handles both the text (hexadecimal) and binary formats. Messages other than sysex will be ignored. Raises ValueError if file is plain text and byte is not a 2-digit hex number.

mido.write_syx_file(filename, messages, plaintext=False)

Write sysex messages to a SYX file.

Messages other than sysex will be skipped.

By default this will write the binary format. Pass plaintext=True to write the plain text format (hex encoded ASCII text).

Port Classes and Functions

class mido.ports.BaseInput(name='', **kwargs)

Base class for input port.

Subclass and override _receive() to create a new input port type. (See portmidi.py for an example of how to do this.)

close()

Close the port.

If the port is already closed, nothing will happen. The port is automatically closed when the object goes out of scope or is garbage collected.

iter_pending()

Iterate through pending messages.

pending()

Return how many messages are ready to be received.

Note: This is kept around for backward compatibility. It’s better to use iter_pending() to iterate over pending messages.

This will read data from the device and put it in the parser. I will then return the number of messages available to be received.

The value will not be reliable when receiving messages in multiple threads.

If this is called on a closed port it will work as normal except it won’t try to read from the device.

poll()

Receive the next pending message or None

This is the same as calling receive(block=False).

receive(block=True)

Return the next message.

This will block until a message arrives.

If you pass block=False it will not block and instead return None if there is no available message.

If the port is closed and there are no pending messages IOError will be raised. If the port closes while waiting inside receive(), IOError will be raised. Todo: this seems a bit inconsistent. Should different errors be raised? What’s most useful here?

class mido.ports.BaseOutput(name='', autoreset=False, **kwargs)

Base class for output port.

Subclass and override _send() to create a new port type. (See portmidi.py for how to do this.)

close()

Close the port.

If the port is already closed, nothing will happen. The port is automatically closed when the object goes out of scope or is garbage collected.

panic()

Send “All Sounds Off” on all channels.

This will mute all sounding notes regardless of envelopes. Useful when notes are hanging and nothing else helps.

reset()

Send “All Notes Off” and “Reset All Controllers” on all channels

send(message)

Send a message on the port.

A copy of the message will be sent, so you can safely modify the original message without any unexpected consequences.

class mido.ports.IOPort(input, output)

Input / output port.

This is a convenient wrapper around an input port and an output port which provides the functionality of both. Every method call is forwarded to the appropriate port.

close()

Close the port.

If the port is already closed, nothing will happen. The port is automatically closed when the object goes out of scope or is garbage collected.

iter_pending()

Iterate through pending messages.

panic()

Send “All Sounds Off” on all channels.

This will mute all sounding notes regardless of envelopes. Useful when notes are hanging and nothing else helps.

pending()

Return how many messages are ready to be received.

Note: This is kept around for backward compatibility. It’s better to use iter_pending() to iterate over pending messages.

This will read data from the device and put it in the parser. I will then return the number of messages available to be received.

The value will not be reliable when receiving messages in multiple threads.

If this is called on a closed port it will work as normal except it won’t try to read from the device.

poll()

Receive the next pending message or None

This is the same as calling receive(block=False).

receive(block=True)

Return the next message.

This will block until a message arrives.

If you pass block=False it will not block and instead return None if there is no available message.

If the port is closed and there are no pending messages IOError will be raised. If the port closes while waiting inside receive(), IOError will be raised. Todo: this seems a bit inconsistent. Should different errors be raised? What’s most useful here?

reset()

Send “All Notes Off” and “Reset All Controllers” on all channels

send(message)

Send a message on the port.

A copy of the message will be sent, so you can safely modify the original message without any unexpected consequences.

class mido.ports.MultiPort(ports, yield_ports=False)
close()

Close the port.

If the port is already closed, nothing will happen. The port is automatically closed when the object goes out of scope or is garbage collected.

iter_pending()

Iterate through pending messages.

panic()

Send “All Sounds Off” on all channels.

This will mute all sounding notes regardless of envelopes. Useful when notes are hanging and nothing else helps.

pending()

Return how many messages are ready to be received.

Note: This is kept around for backward compatibility. It’s better to use iter_pending() to iterate over pending messages.

This will read data from the device and put it in the parser. I will then return the number of messages available to be received.

The value will not be reliable when receiving messages in multiple threads.

If this is called on a closed port it will work as normal except it won’t try to read from the device.

poll()

Receive the next pending message or None

This is the same as calling receive(block=False).

receive(block=True)

Return the next message.

This will block until a message arrives.

If you pass block=False it will not block and instead return None if there is no available message.

If the port is closed and there are no pending messages IOError will be raised. If the port closes while waiting inside receive(), IOError will be raised. Todo: this seems a bit inconsistent. Should different errors be raised? What’s most useful here?

reset()

Send “All Notes Off” and “Reset All Controllers” on all channels

send(message)

Send a message on the port.

A copy of the message will be sent, so you can safely modify the original message without any unexpected consequences.

mido.ports.multi_receive(ports, yield_ports=False, block=True)

Receive messages from multiple ports.

Generates messages from ever input port. The ports are polled in random order for fairness, and all messages from each port are yielded before moving on to the next port.

If yield_ports=True, (port, message) is yielded instead of just the message.

If block=False only pending messages will be yielded.

mido.ports.multi_iter_pending(ports, yield_ports=False)

Iterate through all pending messages in ports.

This is the same as calling multi_receive(ports, block=False). The function is kept around for backwards compatability.

mido.ports.sleep()

Sleep for N seconds.

This is used in ports when polling and waiting for messages. N can be set with set_sleep_time().

mido.ports.set_sleep_time(seconds=0.001)

Set the number of seconds sleep() will sleep.

mido.ports.get_sleep_time()

Get number of seconds sleep() will sleep.

Socket Ports

class mido.sockets.PortServer(host, portno, backlog=1)
accept(block=True)

Accept a connection from a client.

Will block until there is a new connection, and then return a SocketPort object.

If block=False, None will be returned if there is no new connection waiting.

close()

Close the port.

If the port is already closed, nothing will happen. The port is automatically closed when the object goes out of scope or is garbage collected.

iter_pending()

Iterate through pending messages.

panic()

Send “All Sounds Off” on all channels.

This will mute all sounding notes regardless of envelopes. Useful when notes are hanging and nothing else helps.

pending()

Return how many messages are ready to be received.

Note: This is kept around for backward compatibility. It’s better to use iter_pending() to iterate over pending messages.

This will read data from the device and put it in the parser. I will then return the number of messages available to be received.

The value will not be reliable when receiving messages in multiple threads.

If this is called on a closed port it will work as normal except it won’t try to read from the device.

poll()

Receive the next pending message or None

This is the same as calling receive(block=False).

receive(block=True)

Return the next message.

This will block until a message arrives.

If you pass block=False it will not block and instead return None if there is no available message.

If the port is closed and there are no pending messages IOError will be raised. If the port closes while waiting inside receive(), IOError will be raised. Todo: this seems a bit inconsistent. Should different errors be raised? What’s most useful here?

reset()

Send “All Notes Off” and “Reset All Controllers” on all channels

send(message)

Send a message on the port.

A copy of the message will be sent, so you can safely modify the original message without any unexpected consequences.

class mido.sockets.SocketPort(host, portno, conn=None)
close()

Close the port.

If the port is already closed, nothing will happen. The port is automatically closed when the object goes out of scope or is garbage collected.

iter_pending()

Iterate through pending messages.

panic()

Send “All Sounds Off” on all channels.

This will mute all sounding notes regardless of envelopes. Useful when notes are hanging and nothing else helps.

pending()

Return how many messages are ready to be received.

Note: This is kept around for backward compatibility. It’s better to use iter_pending() to iterate over pending messages.

This will read data from the device and put it in the parser. I will then return the number of messages available to be received.

The value will not be reliable when receiving messages in multiple threads.

If this is called on a closed port it will work as normal except it won’t try to read from the device.

poll()

Receive the next pending message or None

This is the same as calling receive(block=False).

receive(block=True)

Return the next message.

This will block until a message arrives.

If you pass block=False it will not block and instead return None if there is no available message.

If the port is closed and there are no pending messages IOError will be raised. If the port closes while waiting inside receive(), IOError will be raised. Todo: this seems a bit inconsistent. Should different errors be raised? What’s most useful here?

reset()

Send “All Notes Off” and “Reset All Controllers” on all channels

send(message)

Send a message on the port.

A copy of the message will be sent, so you can safely modify the original message without any unexpected consequences.

mido.sockets.parse_address(address)

Parse and address on the format host:port.

Returns a tuple (host, port). Raises ValueError if format is invalid or port is not an integer or out of range.