Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Mido
https://mido.readthedocs.io/en/stable/
Admin
Mido is a Python library for working with MIDI 1.0 ports, messages and files.
Tokens:
24,393
Snippets:
380
Trust Score:
9.6
Update:
1 month ago
Context
Chat
Benchmark
69.48
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install Mido with port support Source: https://mido.readthedocs.io/en/stable/installing.html Installs Mido along with the default rtmidi backend for port functionality. ```bash python3 -m pip install mido[ports-rtmidi] ``` -------------------------------- ### Install Mido from source Source: https://mido.readthedocs.io/en/stable/contributing.html Commands to install the Mido package in editable mode from the source root directory. ```bash python3 -m pip install --editable . ``` ```bash python3 -m pip install --editable .[ports-rtmidi] ``` -------------------------------- ### Install and Update Port Callbacks Source: https://mido.readthedocs.io/en/stable/ports/index.html Demonstrates setting a callback during port initialization or by assigning it to the callback attribute. ```python port = mido.open_input(callback=print_message) port.callback = print_message ... port.callback = another_function ``` -------------------------------- ### Install Mido development dependencies Source: https://mido.readthedocs.io/en/stable/contributing.html Commands to install development dependencies for linting, testing, and documentation, ideally within a virtual environment. ```bash python3 -m pip install --editable .[dev] ``` ```bash python3 -m pip install --editable .[dev,ports-rtmidi] ``` -------------------------------- ### Install Mido via pip Source: https://mido.readthedocs.io/en/stable/installing.html The standard command to install the latest stable version of Mido from PyPi. ```bash python3 -m pip install mido ``` -------------------------------- ### Build the package manually Source: https://mido.readthedocs.io/en/stable/contributing.html Install build dependencies and generate the distribution files. ```bash source mido-build/bin/activate python3 -m pip install --upgrade pip setuptools wheel build twine python3 -m build ``` -------------------------------- ### Install PortMidi Dependencies Source: https://mido.readthedocs.io/en/stable/backends/portmidi.html Commands to install the required PortMidi shared library on various operating systems. ```bash apt install libportmidi-dev ``` ```bash brew install portmidi ``` ```bash port install portmidi ``` -------------------------------- ### Install rtmidi-python Source: https://mido.readthedocs.io/en/stable/backends/rtmidi_python.html Command to install the required rtmidi-python library via pip. ```bash python3 - m pip install rtmidi-python ``` -------------------------------- ### Verify published package Source: https://mido.readthedocs.io/en/stable/contributing.html Install the package from Test PyPI and verify the version information. ```bash python3 -m pip install --index-url https://test.pypi.org/simple/ --no-deps mido python3 -c "import mido; print(mido.version_info)" ``` -------------------------------- ### Server-to-Client Communication Source: https://mido.readthedocs.io/en/stable/ports/index.html Example of a server pushing messages to connected clients. ```python server = PortServer('localhost', 8080): while True: server.send(message) ... ``` ```python for message in connect('localhost', 8080): print(message) ``` -------------------------------- ### Plain Text SYX Format Example Source: https://mido.readthedocs.io/en/stable/files/syx.html Example of the hex-encoded byte format used when writing plain text SYX files. ```text F0 00 01 5D 02 00 F7 F0 00 01 5D 03 00 F7 ``` -------------------------------- ### Common MIDI Message Examples Source: https://mido.readthedocs.io/en/stable/about_midi.html Various examples of MIDI messages including note control, program changes, and system-specific data. ```text # Turn on middle C on channel 2: 92 3C 64 # Turn it back off: 82 3C 64 # Change to program (sound) number 4 on channel 2: C2 04 # Continue (Starts a song that has been paused): FB # Sysex data request for the Roland SH-201 synthesizer: F0 41 10 00 00 16 11 20 00 00 00 00 00 00 21 3F F7 ``` -------------------------------- ### MIDI Note On Message Example Source: https://mido.readthedocs.io/en/stable/about_midi.html A three-byte hexadecimal representation of a note-on command. ```text 92 3C 64 ``` -------------------------------- ### List Available APIs Source: https://mido.readthedocs.io/en/stable/backends/rtmidi.html Retrieves the list of MIDI APIs supported by the current RtMidi installation. ```python >>> mido.backend.module.get_api_names() ['LINUX_ALSA', 'UNIX_JACK'] ``` -------------------------------- ### Representing Unknown Meta Messages Source: https://mido.readthedocs.io/en/stable/meta_message_types.html Example of the string representation for an unknown meta message. ```python UnknownMetaMessage(type_byte=251, data=(1, 2, 3), time=0) ``` -------------------------------- ### Event-based message handling Source: https://mido.readthedocs.io/en/stable/ports/index.html Example of using a callback function in a GTK event-based system to process incoming messages. ```python def callback(self): for msg in self.inport: print(msg) gobject.timeout_add_seconds(timeout, callback) ``` -------------------------------- ### Prepare manual build environment Source: https://mido.readthedocs.io/en/stable/contributing.html Clone the repository and set up a virtual environment for manual building. ```bash git clone --branch <X.Y.Z> --single-branch https://github.com/mido/mido mido-<X.Y.Z> cd mido-<X.Y.Z> python3 -m venv mido-build ``` -------------------------------- ### Creating a Simple Server Source: https://mido.readthedocs.io/en/stable/ports/index.html A basic server implementation that listens for and prints incoming MIDI messages. ```python for message in PortServer('localhost', 8080): print(message) ``` -------------------------------- ### Initialize Sysex Messages with Data Source: https://mido.readthedocs.io/en/stable/message_types.html Demonstrates initializing sysex messages using lists, ranges, and generator expressions for the data parameter. ```python mido.Message('sysex', data=[1, 2, 3]) mido.Message('sysex', data=range(10)) mido.Message('sysex', data=(i for i in range(10) if i % 2 == 0)) ``` -------------------------------- ### Build documentation Source: https://mido.readthedocs.io/en/stable/contributing.html Commands for generating HTML or PDF documentation using Sphinx. ```bash sphinx-build -j auto -q -W -E --keep-going docs docs/_build ``` ```bash sphinx-build -M latexpdf docs docs/_build ``` ```bash sphinx-build -M clean docs docs/_build ``` -------------------------------- ### Configure Backend via Environment Variables Source: https://mido.readthedocs.io/en/stable/backends/rtmidi.html Sets the preferred MIDI backend API using shell environment variables. ```bash $ export MIDO_BACKEND=mido.backends.rtmidi/LINUX_ALSA $ export MIDO_BACKEND=mido.backends.rtmidi/UNIX_JACK ``` -------------------------------- ### Building and running with PyInstaller Source: https://mido.readthedocs.io/en/stable/freezing_exe.html Commands to build the executable and verify the output. ```bash $ pyinstaller --onefile midotest.py $ ./dist/midotest [u'Midi Through Port-0'] ``` -------------------------------- ### Manual Connection Handling with accept() Source: https://mido.readthedocs.io/en/stable/ports/index.html Using accept() for more granular control over client connections. ```python with PortServer('localhost', 8080) as server: while True: client = server.accept() for message in client: print(message) ``` -------------------------------- ### Initialize MidiTrack with Iterables Source: https://mido.readthedocs.io/en/stable/changes.html MidiTrack can now be initialized using various iterables of messages. ```python MidiTrack(messages) MidiTrack(port.iter_pending()) MidiTrack(msg for msg in some_generator) ``` -------------------------------- ### Open a MIDI file Source: https://mido.readthedocs.io/en/stable/files/midi.html Initialize a MidiFile object by providing the path to a MIDI file. ```python from mido import MidiFile mid = MidiFile('song.mid') ``` -------------------------------- ### Embed Mido messages in JSON Source: https://mido.readthedocs.io/en/stable/messages/index.html Example of storing serialized messages within a JSON structure. ```json { "messages": [ "0.0 note_on channel=9 note=60 velocity=120", "0.5 sysex data=(1,2,3)", "...", ] } ``` -------------------------------- ### Initialize and feed the MIDI parser Source: https://mido.readthedocs.io/en/stable/intro.html Create a new parser instance and feed it MIDI data using feed or feed_byte methods. ```python >>> p = mido.Parser() >>> p.feed([0x90, 0x40]) >>> p.feed_byte(0x60) ``` -------------------------------- ### System Exclusive Message Structure Source: https://mido.readthedocs.io/en/stable/about_midi.html The structure of a System Exclusive message using start and stop bytes. ```text F0 ... F7 ``` -------------------------------- ### Use multiple backends simultaneously Source: https://mido.readthedocs.io/en/stable/backends/index.html Instantiates multiple backend objects to manage different MIDI ports concurrently. ```python rtmidi = mido.Backend('mido.backends.rtmidi') portmidi = mido.Backend('mido.backends.portmidi') input = rtmidi.open_input() output = portmidi.open_output() for message in input: output.send(message) ``` -------------------------------- ### Get MIDI Playback Length Source: https://mido.readthedocs.io/en/stable/files/midi.html Access the total playback time in seconds for type 0 and 1 MIDI files. ```python mid.length ``` -------------------------------- ### Configure default ports via environment variables Source: https://mido.readthedocs.io/en/stable/backends/index.html Sets default MIDI ports using environment variables for input and output. ```bash MIDO_DEFAULT_INPUT MIDO_DEFAULT_OUTPUT MIDO_DEFAULT_IOPORT ``` ```bash $ MIDO_DEFAULT_INPUT='SH-201' python3 program.py ``` ```bash $ export MIDO_DEFAULT_OUTPUT='Integra-7' $ python3 program1.py $ python3 program2.py ``` -------------------------------- ### Create and Save a New MIDI File Source: https://mido.readthedocs.io/en/stable/files/midi.html Initializes a new MidiFile, adds a track, appends messages, and saves the file to disk. ```python from mido import Message, MidiFile, MidiTrack mid = MidiFile() track = MidiTrack() mid.tracks.append(track) track.append(Message('program_change', program=12, time=0)) track.append(Message('note_on', note=64, velocity=64, time=32)) track.append(Message('note_off', note=64, velocity=127, time=32)) mid.save('new_song.mid') ``` -------------------------------- ### Create Meta Messages Source: https://mido.readthedocs.io/en/stable/files/midi.html Instantiate meta messages similarly to standard MIDI messages. ```python >>> from mido import MetaMessage >>> MetaMessage('key_signature', key='C#', mode='major') MetaMessage('key_signature', key='C#', mode='major', time=0) ``` -------------------------------- ### mido.open_input Source: https://mido.readthedocs.io/en/stable/api.html Opens a MIDI input port. ```APIDOC ## mido.open_input(name=None, virtual=False, callback=None, **kwargs) ### Description Opens an input port. If the environment variable MIDO_DEFAULT_INPUT is set, it will override the default port. ### Parameters - **name** (str) - Optional - The name of the port to open. - **virtual** (bool) - Optional - If True, opens a new port that other applications can connect to. - **callback** (callable) - Optional - A function to be called when a new message arrives. ``` -------------------------------- ### Set backend via environment variable Source: https://mido.readthedocs.io/en/stable/backends/index.html Configures the backend at runtime using the MIDO_BACKEND environment variable. ```bash $ MIDO_BACKEND=mido.backends.portmidi ./program.py ``` -------------------------------- ### Serve MIDI ports with mido-serve Source: https://mido.readthedocs.io/en/stable/binaries.html Exposes one or more MIDI ports over the network. ```bash $ mido-serve :9080 'Integra-7' ``` -------------------------------- ### Publish to PyPI Source: https://mido.readthedocs.io/en/stable/contributing.html Upload the distribution files to the official PyPI repository. ```bash twine upload dist/* ``` -------------------------------- ### Initialize message with attributes Source: https://mido.readthedocs.io/en/stable/messages/index.html Pass specific attributes as keyword arguments during message creation. ```python >>> mido.Message('note_on', note=100, velocity=3, time=6.2) Message('note_on', channel=0, note=100, velocity=3, time=6.2) ``` -------------------------------- ### Connect to MIDI servers with mido-connect Source: https://mido.readthedocs.io/en/stable/binaries.html Forwards messages from local ports to a remote MIDI server. ```bash $ mido-connect mac.local:9080 'SH-201' ``` -------------------------------- ### Set MIDI File Type Source: https://mido.readthedocs.io/en/stable/files/midi.html Demonstrates setting the MIDI file type during initialization or by modifying the attribute directly. ```python mid = MidiFile(type=2) mid.type = 1 ``` -------------------------------- ### Tag the release Source: https://mido.readthedocs.io/en/stable/contributing.html Create an annotated tag for the release version. ```bash git tag -a <X.Y.Z> -m "mido version <X.Y.Z>" ``` -------------------------------- ### mido.open_output Source: https://mido.readthedocs.io/en/stable/api.html Opens a MIDI output port. ```APIDOC ## mido.open_output(name=None, virtual=False, autoreset=False, **kwargs) ### Description Opens an output port. If the environment variable MIDO_DEFAULT_OUTPUT is set, it will override the default port. ### Parameters - **name** (str) - Optional - The name of the port to open. - **virtual** (bool) - Optional - If True, opens a new port that other applications can connect to. - **autoreset** (bool) - Optional - Automatically send all_notes_off and reset_all_controllers on all channels. ``` -------------------------------- ### Play back a MIDI file using the play method Source: https://mido.readthedocs.io/en/stable/files/midi.html Use the built-in play method to handle timing and filtering automatically. ```python for msg in MidiFile('song.mid').play(): port.send(msg) ``` -------------------------------- ### Play MIDI files with mido-play Source: https://mido.readthedocs.io/en/stable/binaries.html Plays back one or more MIDI files from the command line. ```bash $ mido-play song1.mid [song2.mid] ``` -------------------------------- ### mido.open_ioport Source: https://mido.readthedocs.io/en/stable/api.html Opens a MIDI port for both input and output. ```APIDOC ## mido.open_ioport(name=None, virtual=False, callback=None, autoreset=False, **kwargs) ### Description Opens a port for input and output. If the environment variable MIDO_DEFAULT_IOPORT is set, it will override the default port. ### Parameters - **name** (str) - Optional - The name of the port to open. - **virtual** (bool) - Optional - If True, opens a new port that other applications can connect to. - **callback** (callable) - Optional - A function to be called when a new message arrives. - **autoreset** (bool) - Optional - Automatically send all_notes_off and reset_all_controllers on all channels. ``` -------------------------------- ### Open Output Ports with Partial Names Source: https://mido.readthedocs.io/en/stable/backends/rtmidi.html Demonstrates opening ports by omitting specific ALSA client or port numbers to avoid session-dependent naming issues. ```python mido.open_output('TiMidity port 0') ``` ```python mido.open_output('TiMidity:TiMidity port 0') ``` ```python mido.open_output('TiMidity:TiMidity port 0 128:0') ``` -------------------------------- ### Publish to Test PyPI Source: https://mido.readthedocs.io/en/stable/contributing.html Upload the built package to the Test PyPI repository. ```bash python3 -m build twine upload --repository testpypi dist/* ``` -------------------------------- ### Check release manifest Source: https://mido.readthedocs.io/en/stable/contributing.html Verify that the repository and source code manifest are synchronized. ```bash check-manifest --verbose ``` -------------------------------- ### Manage Port Lifecycle and Iteration Source: https://mido.readthedocs.io/en/stable/intro.html Use the with statement for automatic port closure and iterate over incoming messages. ```python with mido.open_input('SH-201') as inport: ... ``` ```python for msg in inport: ... ``` -------------------------------- ### mido.Backend Source: https://mido.readthedocs.io/en/stable/api.html A wrapper for backend modules that provides functions for managing MIDI ports. ```APIDOC ## class mido.Backend(name=None, api=None, load=False, use_environ=True) ### Methods - **get_input_names(**kwargs)**: Return a list of all input port names. - **get_ioport_names(**kwargs)**: Return a list of all I/O port names. - **get_output_names(**kwargs)**: Return a list of all output port names. - **load()**: Load the module. - **open_input(name=None, virtual=False, callback=None, **kwargs)**: Open an input port. - **open_ioport(name=None, virtual=False, callback=None, autoreset=False, **kwargs)**: Open a port for input and output. - **open_output(name=None, virtual=False, autoreset=False, **kwargs)**: Open an output port. ``` -------------------------------- ### List and Open Ports Source: https://mido.readthedocs.io/en/stable/ports/index.html Retrieve a list of available output ports and open a specific one by name. ```python >>> mido.get_output_names() ['SH-201', 'Integra-7'] ``` ```python >>> port = mido.open_output('Integra-7') ``` -------------------------------- ### Create and manipulate MIDI messages Source: https://mido.readthedocs.io/en/stable/index.html Demonstrates basic message instantiation, attribute access, byte conversion, and copying with modifications. ```python >>> import mido >>> msg = mido.Message('note_on', note=60) >>> msg.type 'note_on' >>> msg.note 60 >>> msg.bytes() [144, 60, 64] >>> msg.copy(channel=2) Message('note_on', channel=2, note=60, velocity=64, time=0) ``` -------------------------------- ### Define overridable port methods Source: https://mido.readthedocs.io/en/stable/ports/custom.html The _open method is used to initialize port resources during instantiation. ```python _open(self, **kwargs) ``` -------------------------------- ### Play a MIDI file Source: https://mido.readthedocs.io/en/stable/index.html Loads a MIDI file and iterates through its messages to send them to an output port. ```python mid = mido.MidiFile('song.mid') for msg in mid.play(): port.send(msg) ``` -------------------------------- ### List and Open Specific Ports Source: https://mido.readthedocs.io/en/stable/intro.html Retrieve available input port names and open a specific port by name. ```python >>> mido.get_input_names() ['Midi Through Port-0', 'SH-201', 'Integra-7'] >>> inport = mido.open_input('SH-201') ``` -------------------------------- ### Create Virtual Ports Source: https://mido.readthedocs.io/en/stable/backends/rtmidi.html Initializes a virtual input port that other applications can connect to, excluding Windows environments. ```python >>> port = mido.open_input('New Port', virtual=True) >>> port <open input 'New Port' (RtMidi/LINUX_ALSA)> ``` -------------------------------- ### Open MIDI Ports Source: https://mido.readthedocs.io/en/stable/ports/index.html Open input and output ports by specifying the device name. ```python >>> inport = mido.open_input('SH-201') >>> outport = mido.open_output('Integra-7') ``` -------------------------------- ### Lint REUSE compliance Source: https://mido.readthedocs.io/en/stable/contributing.html Verify that the project remains REUSE compliant after adding copyright headers. ```bash reuse lint ``` -------------------------------- ### mido.bpm2tempo(bpm, time_signature=(4, 4)) Source: https://mido.readthedocs.io/en/stable/api.html Converts BPM to MIDI file tempo in microseconds per quarter note. ```APIDOC ## mido.bpm2tempo(bpm, time_signature=(4, 4)) ### Description Convert BPM (beats per minute) to MIDI file tempo (microseconds per quarter note). The returned tempo depends on the time signature. ``` -------------------------------- ### mido.MidiFile Source: https://mido.readthedocs.io/en/stable/api.html Represents a standard MIDI file. Provides methods to manage tracks, calculate playback length, play back tracks, and save to disk. ```APIDOC ## class mido.MidiFile ### Description Represents a standard MIDI file. Allows for loading, creating, and manipulating MIDI data. ### Methods - **add_track(name=None)**: Adds a new MidiTrack object to the file. - **play(meta_messages=False, now=<built-in function time>)**: Plays back all tracks. Yields messages with correct timing. - **print_tracks(meta_only=False)**: Prints all messages in the file. - **save(filename=None, file=None)**: Saves the MIDI data to a file or file-like object. ### Properties - **length**: Playback time in seconds. - **merged_track**: Access to the merged track data. ``` -------------------------------- ### Read and Write SYX Files Source: https://mido.readthedocs.io/en/stable/files/syx.html Use these functions to load SysEx messages from a file or save them to a file. Non-sysex messages are ignored during the write process. ```python messages = mido.read_syx_file('patch.syx') ``` ```python mido.write_syx_file('patch.syx', messages) ``` -------------------------------- ### Input Port Methods Source: https://mido.readthedocs.io/en/stable/ports/index.html Methods specific to MIDI input ports. ```APIDOC ## Input Port Methods ### receive(block=True) Receives a message. Blocks until a message is returned if block is True. If block is False, returns None if no message is pending. ### poll() Returns a message, or None if there are no pending messages. ### iter_pending() Iterates through pending messages. ### __iter__() Iterates through messages as they arrive on the port until the port closes. ``` -------------------------------- ### Open and Use MIDI Ports Source: https://mido.readthedocs.io/en/stable/intro.html Basic operations for opening output and input ports to send and receive MIDI messages. ```python >>> outport = mido.open_output() >>> outport.send(msg) ``` ```python >>> inport = mido.open_input() >>> msg = inport.receive() ``` -------------------------------- ### Receive MIDI messages from an input port Source: https://mido.readthedocs.io/en/stable/index.html Uses a context manager to open an input port and iterate over incoming messages. ```python with mido.open_input() as inport: for msg in inport: print(msg) ``` -------------------------------- ### Creating a Custom Meta Message Source: https://mido.readthedocs.io/en/stable/meta_message_types.html Instantiating a custom meta message after registration. ```python >>> from mido import MetaMessage >>> MetaMessage('light_color', r=120, g=60, b=10) MetaMessage('light_color', r=120, g=60, b=10, time=0) ``` -------------------------------- ### Define Backend Module Components Source: https://mido.readthedocs.io/en/stable/backends/custom.html Required components for a custom backend module. ```python Input -- an input port class Output -- an output port class IOPort -- an I/O port class get_devices() -- returns a list of devices ``` -------------------------------- ### mido.write_syx_file(filename, messages, plaintext=False) Source: https://mido.readthedocs.io/en/stable/files/syx.html Writes a list of messages to a SYX file, with an option to format as plain text. ```APIDOC ## mido.write_syx_file(filename, messages, plaintext=False) ### Description Writes SysEx messages to a file. If plaintext is set to True, the file is written as hex-encoded bytes with one message per line. ### Parameters - **filename** (string) - Required - The path to the output file. - **messages** (list) - Required - The list of messages to write. - **plaintext** (boolean) - Optional - If True, writes the file in plain text hex format. ### Example ```python mido.write_syx_file('patch.syx', messages) mido.write_syx_file('patch.txt', messages, plaintext=True) ``` ``` -------------------------------- ### Specify Client Name Source: https://mido.readthedocs.io/en/stable/backends/rtmidi.html Opens an input port with a custom client name, which automatically creates a virtual port. ```python >>> port = mido.open_input('New Port', client_name='My Client') ``` -------------------------------- ### Run unit tests with pytest Source: https://mido.readthedocs.io/en/stable/contributing.html Execute the test suite using the configuration specified in pyproject.toml. ```bash pytest ``` -------------------------------- ### port.receive() Source: https://mido.readthedocs.io/en/stable/ports/index.html Blocks until a message arrives on the input port. ```APIDOC ### Method `port.receive()` ### Description Blocks execution until a message is received on the port. ``` -------------------------------- ### Create a MIDI Message Source: https://mido.readthedocs.io/en/stable/intro.html Instantiate a new MIDI message object using the Message class. ```python >>> from mido import Message >>> msg = Message('note_on', note=60) >>> msg Message('note_on', channel=0, note=60, velocity=64, time=0) ``` -------------------------------- ### Define Device Dictionary Structure Source: https://mido.readthedocs.io/en/stable/backends/custom.html The expected dictionary format for devices returned by get_devices(). ```python { 'name': 'Some MIDI Input Port', 'is_input': True, 'is_output': False, } ``` -------------------------------- ### Handling Multiple Concurrent Connections Source: https://mido.readthedocs.io/en/stable/ports/index.html Advanced server implementation using non-blocking accept() to manage multiple clients. ```python with PortServer('localhost', 8080) as server: clients = [] while True: # Handle connections. client = server.accept(block=False) if client: print('Connection from {}'.format(client.name)) clients.append(client) for i, client in reversed(enumerate(clients)): if client.closed: print('{} disconnected'.format(client.name)) del clients[i] # Receive messages. for client in clients: for message in client.iter_pending() print('Received {} from {}'.format(message, client)) # Do other things ... ``` -------------------------------- ### Autoreset on port close Source: https://mido.readthedocs.io/en/stable/ports/index.html Demonstrates using the autoreset feature to automatically call reset() when the port is closed. ```python with mido.open_output('Integra-7') as outport: for msg in inport: outport.send(msg) # reset() is called here outport.close() # or here ``` -------------------------------- ### mido.tempo2bpm(tempo, time_signature=(4, 4)) Source: https://mido.readthedocs.io/en/stable/api.html Converts MIDI file tempo to BPM. ```APIDOC ## mido.tempo2bpm(tempo, time_signature=(4, 4)) ### Description Convert MIDI file tempo (microseconds per quarter note) to BPM (beats per minute). The returned BPM depends on the time signature denominator. ``` -------------------------------- ### Lint code with ruff Source: https://mido.readthedocs.io/en/stable/contributing.html Run linting checks locally using the configuration defined in pyproject.toml. ```bash ruff check . ``` -------------------------------- ### Time Conversion Utilities Source: https://mido.readthedocs.io/en/stable/files/midi.html Utility functions for converting between MIDI ticks and absolute time in seconds, and between tempo and BPM. ```APIDOC ## Time Conversion Functions ### bpm2tempo(bpm) Converts beats per minute to microseconds per quarter note. ### tempo2bpm(tempo) Converts microseconds per quarter note to beats per minute. ### tick2second(tick, ticks_per_beat, tempo) Converts MIDI ticks to absolute time in seconds based on resolution and tempo. ### second2tick(second, ticks_per_beat, tempo) Converts absolute time in seconds to MIDI ticks. ``` -------------------------------- ### Create Virtual Ports Source: https://mido.readthedocs.io/en/stable/intro.html Create a virtual input port that other applications can connect to, supported by RtMidi. ```python with mido.open_input('New Port', virtual=True) as inport: for message in inport: print(message) ``` -------------------------------- ### Set backend programmatically Source: https://mido.readthedocs.io/en/stable/backends/index.html Sets the active backend within a running program, overriding environment variables. ```python >>> mido.set_backend('mido.backends.portmidi') >>> mido.backend <backend mido.backends.portmidi (not loaded)> ``` -------------------------------- ### Check port capabilities Source: https://mido.readthedocs.io/en/stable/ports/custom.html Use hasattr to determine if a port supports input, output, or both within the _open method. ```python def _open(self, **kwargs): if hasattr(self, 'send'): # This is an output port. if hasattr(self, 'receive'): # This is an input port. if hasattr(self, 'send') and hasattr(self, 'receive'): # This is an I/O port. ``` -------------------------------- ### Open Default Port Source: https://mido.readthedocs.io/en/stable/ports/index.html Open a default output port without specifying a name. ```python port = mido.open_output() ``` -------------------------------- ### MidiFile.play() Source: https://mido.readthedocs.io/en/stable/files/midi.html Iterates over messages in the MIDI file in playback order, handling timing and filtering. ```APIDOC ## MidiFile.play() ### Description Returns an iterator that yields messages in playback order, automatically handling sleep intervals between messages. ### Parameters - **meta_messages** (boolean) - Optional - If True, includes meta messages in the output. Defaults to False. ``` -------------------------------- ### Output Port Methods Source: https://mido.readthedocs.io/en/stable/ports/index.html Methods specific to MIDI output ports. ```APIDOC ## Output Port Methods ### send(message) Sends a MIDI message. ### reset() Sends 'all notes off' and 'reset all controllers' on all channels. ### panic() Sends 'all sounds off' on all channels to abruptly end all sounding notes. ``` -------------------------------- ### Select Backend API Programmatically Source: https://mido.readthedocs.io/en/stable/backends/rtmidi.html Configures the active backend API within a Python script using set_backend or the Backend class. ```python >>> mido.set_backend('mido.backends.rtmidi/LINUX_ALSA') >>> mido.backend <backend mido.backends.rtmidi/LINUX_ALSA (not loaded)> >>> mido.Backend('mido.backends.rtmidi/UNIX_JACK') <backend mido.backends.rtmidi/UNIX_JACK (not loaded)> ``` -------------------------------- ### Implement a custom I/O port Source: https://mido.readthedocs.io/en/stable/ports/custom.html Define a custom port by inheriting from BaseIOPort and implementing the _open, _close, _send, and _receive methods. ```python import fjopp from mido.ports import BaseIOPort # This defines an I/O port. class FjoppPort(BaseIOPort): def _open(self, **kwargs): self._device = fjopp.open_device(self.name) def _close(self): self._device.close() def _send(self, message): self.device.write(message.bytes()) def _receive(self, block=True): while True: data = self.device.read() if data: self._parser.feed(data) else: return ``` -------------------------------- ### Play back a MIDI file manually Source: https://mido.readthedocs.io/en/stable/files/midi.html Iterate over a MidiFile object to send messages to a port with manual timing. ```python for msg in MidiFile('song.mid'): time.sleep(msg.time) if not msg.is_meta: port.send(msg) ``` -------------------------------- ### mido.sockets.PortServer Source: https://mido.readthedocs.io/en/stable/api.html A server class for handling socket-based MIDI connections. ```APIDOC ## class mido.sockets.PortServer(host, portno, backlog=1) ### Description Creates a server to accept socket connections for MIDI communication. ### Methods - **accept(block=True)**: Accept a connection from a client. Returns a SocketPort object. - **close()**: Close the port. - **iter_pending()**: Iterate through pending messages. - **panic()**: Send “All Sounds Off” on all channels. - **poll()**: Receive the next pending message or None. - **receive(block=True)**: Return the next message. - **reset()**: Send “All Notes Off” and “Reset All Controllers” on all channels. - **send(msg)**: Send a message on the port. ``` -------------------------------- ### Create messages from bytes or hex Source: https://mido.readthedocs.io/en/stable/intro.html Use class methods to instantiate messages directly from byte lists or hex strings. The input must represent exactly one complete MIDI message. ```python msg1 = mido.Message.from_bytes([0x90, 0x40, 0x60]) msg2 = mido.Message.from_hex('90, 40 60') ``` -------------------------------- ### Importing Mido Classes and Functions Source: https://mido.readthedocs.io/en/stable/changes.html Standard imports for core Mido components and meta-message specifications. ```python from mido import MidiFile, MidiTrack, MetaMessage from mido.midifiles import MetaSpec, add_meta_spec ``` -------------------------------- ### MidiFile(filename) Source: https://mido.readthedocs.io/en/stable/files/midi.html Opens and reads a MIDI file into memory. ```APIDOC ## MidiFile(filename) ### Description Opens a MIDI file and loads its contents into memory for processing. ### Parameters - **filename** (string) - Required - The path to the .mid file to be opened. ``` -------------------------------- ### Project Copyright Notice Source: https://mido.readthedocs.io/en/stable/licenses.html The copyright notice for the Mido project. ```text Copyright (C) 2013 Ole Martin Bjørndalen Copyright (C) 2023 Raphaël Doursenaud ``` -------------------------------- ### Add SPDX copyright header Source: https://mido.readthedocs.io/en/stable/contributing.html Format for adding copyright information to files to maintain REUSE compliance. ```text # SPDX-FileCopyrightText: YYYY First_Name Last_Name <email_address> # # SPDX-License-Identifier: MIT ``` -------------------------------- ### Define a Callback Function Source: https://mido.readthedocs.io/en/stable/ports/index.html A basic function definition to handle incoming MIDI messages. ```python def print_message(message): print(message) ``` -------------------------------- ### Push tags to GitHub Source: https://mido.readthedocs.io/en/stable/contributing.html Push changes and tags to trigger the automated release workflow. ```bash git push --tags ``` -------------------------------- ### Explicitly importing Mido backends Source: https://mido.readthedocs.io/en/stable/freezing_exe.html Import the required backend module at the top of your script to ensure PyInstaller includes it in the executable. ```python import mido import mido.backends.portmidi # The backend you want to use. print(mido.get_input_names()) ``` -------------------------------- ### Connecting and Sending Messages Source: https://mido.readthedocs.io/en/stable/ports/index.html Client-side code to connect to a server and send MIDI messages. ```python output = connect('localhost', 8080): output.send(message) ``` -------------------------------- ### outport.panic() Source: https://mido.readthedocs.io/en/stable/ports/index.html Abruptly stops all sounding notes without resetting controllers. ```APIDOC ### Method `outport.panic()` ### Description Stops all sounding notes immediately without regard to decay time and without resetting controllers. ``` -------------------------------- ### mido.ports.IOPort Source: https://mido.readthedocs.io/en/stable/api.html A wrapper class for input and output ports, providing unified methods for both. ```APIDOC ## class mido.ports.IOPort(input, output) ### Description Input / output port wrapper that forwards method calls to the appropriate underlying port. ### Methods - **send(msg)**: Send a message on the port. - **close()**: Close the port. - **iter_pending()**: Iterate through pending messages. - **panic()**: Send “All Sounds Off” on all channels. - **poll()**: Receive the next pending message or None. - **receive(block=True)**: Return the next message, blocking until one arrives if block is True. ``` -------------------------------- ### mido.read_syx_file(filename) Source: https://mido.readthedocs.io/en/stable/files/syx.html Reads a SYX file (binary or plain text) and returns a list of messages. Non-sysex messages are ignored. ```APIDOC ## mido.read_syx_file(filename) ### Description Reads a SYX file and returns a list of messages. The function automatically detects if the file is binary or plain text by inspecting the first byte. ### Parameters - **filename** (string) - Required - The path to the .syx or .txt file. ### Returns - **messages** (list) - A list of SysEx messages. ### Example ```python messages = mido.read_syx_file('patch.syx') ``` ``` -------------------------------- ### Parse MIDI bytes with utility functions Source: https://mido.readthedocs.io/en/stable/messages/parsing.html Use mido.parse to convert a single sequence of bytes into a message, or mido.parse_all to process multiple messages. ```python >>> mido.parse([0x92, 0x10, 0x20]) Message('note_on', channel=2, note=16, velocity=32, time=0) >>> mido.parse_all([0x92, 0x10, 0x20, 0x82, 0x10, 0x20]) [Message('note_on', channel=2, note=16, velocity=32, time=0), Message('note_off', channel=2, note=16, velocity=32, time=0)] ``` -------------------------------- ### Registering a Custom Meta Message Source: https://mido.readthedocs.io/en/stable/meta_message_types.html Registering the custom meta specification with the Mido system. ```python add_meta_spec(MetaSpec_light_color) ``` -------------------------------- ### mido.ports Utility Functions Source: https://mido.readthedocs.io/en/stable/api.html Global utility functions for port operations and configuration. ```APIDOC ## mido.ports.multi_receive(ports, yield_ports=False, block=True) ### Description Receive messages from multiple ports. If yield_ports=True, returns (port, message) tuples. ## mido.ports.multi_send(ports, msg) ### Description Send a message on all provided ports. ## mido.ports.set_sleep_time(seconds=0.001) ### Description Set the number of seconds the sleep() function will wait. ## mido.ports.get_sleep_time() ### Description Get the current sleep duration in seconds. ``` -------------------------------- ### Send MIDI messages to an output port Source: https://mido.readthedocs.io/en/stable/index.html Opens a named MIDI output port and sends a message. ```python port = mido.open_output('Port Name') port.send(msg) ``` -------------------------------- ### Read and Write Plain Text SYX Files Source: https://mido.readthedocs.io/en/stable/files/syx.html Mido supports plain text SYX files. The read function automatically detects the format, while the write function requires the plaintext flag. ```python messages = mido.read_syx_file('patch.txt') ``` ```python mido.write_syx_file('patch.txt', messages, plaintext=True) ``` -------------------------------- ### Print all messages in a MIDI file Source: https://mido.readthedocs.io/en/stable/files/midi.html Iterate through the tracks and messages of a loaded MidiFile object to display their contents. ```python for i, track in enumerate(mid.tracks): print('Track {}: {}'.format(i, track.name)) for msg in track: print(msg) ``` -------------------------------- ### mido.second2tick(second, ticks_per_beat, tempo) Source: https://mido.readthedocs.io/en/stable/api.html Converts absolute time in seconds to ticks based on MIDI file resolution and tempo. ```APIDOC ## mido.second2tick(second, ticks_per_beat, tempo) ### Description Convert absolute time in seconds to ticks. Returns absolute time in ticks for a chosen MIDI file time resolution (ticks/pulses per quarter note, also called PPQN) and tempo (microseconds per quarter note). ``` -------------------------------- ### Subclassing Existing Meta Specifications Source: https://mido.readthedocs.io/en/stable/meta_message_types.html Inheriting from existing MetaSpec classes for text-based meta messages. ```python class MetaSpec_copyright(MetaSpec_text): type_byte = 0x02 class MetaSpec_instrument_name(MetaSpec_track_name): type_byte = 0x04 ``` -------------------------------- ### outport.reset() Source: https://mido.readthedocs.io/en/stable/ports/index.html Resets the output port by sending 'all notes off' and 'reset all controllers' on every channel. ```APIDOC ### Method `outport.reset()` ### Description Sends 'all notes off' and 'reset all controllers' on every channel to return the device to a default state. ``` -------------------------------- ### mido.set_backend Source: https://mido.readthedocs.io/en/stable/api.html Sets the current backend for MIDI operations, replacing top-level mido functions. ```APIDOC ## mido.set_backend(name=None, load=False) ### Description Sets the current backend. If no name is passed, the default backend is used. This replaces open_*() and get_*_name() functions in the top-level mido module. ``` -------------------------------- ### Define a custom output port Source: https://mido.readthedocs.io/en/stable/ports/custom.html Subclass BaseOutput and implement the _send method to define custom message handling behavior. ```python from mido.ports import BaseOutput class PrintPort(BaseOutput): def _send(message): print(message) >>> port = PrintPort() >>> port.send(msg) note_on channel=0 note=0 velocity=64 time=0 ``` -------------------------------- ### Retrieve release history Source: https://mido.readthedocs.io/en/stable/contributing.html Commands to list merged pull requests and commits since the previous release tag. ```bash previous_release_tag=git describe --abbrev=0 git log --oneline --merges --reverse "${previous_release_tag}.." git log --oneline --no-merges --reverse "${previous_release_tag}.." ``` -------------------------------- ### Importing Socket Modules Source: https://mido.readthedocs.io/en/stable/ports/index.html Required imports for using PortServer and connect functionality. ```python from mido.sockets import PortServer, connect ``` -------------------------------- ### Define Mido message string format Source: https://mido.readthedocs.io/en/stable/messages/index.html The expected syntax for serialized Mido messages. ```text MESSAGE_TYPE [PARAMETER=VALUE ...] ``` ```text [a-z][0-9][ =_.+()] ``` ```text 'abcdefghijklmnopqrstuvwxyz0123456789 =_.+()' ``` -------------------------------- ### mido.ports.MultiPort Source: https://mido.readthedocs.io/en/stable/api.html A class for managing multiple ports simultaneously. ```APIDOC ## class mido.ports.MultiPort(ports, yield_ports=False) ### Description Manages multiple ports, allowing for collective operations. ### Methods - **send(msg)**: Send a message on the port. - **close()**: Close the port. - **iter_pending()**: Iterate through pending messages. - **panic()**: Send “All Sounds Off” on all channels. - **poll()**: Receive the next pending message or None. - **receive(block=True)**: Return the next message. ``` -------------------------------- ### Send MIDI message Source: https://mido.readthedocs.io/en/stable/ports/index.html Sends a message immediately through the output port. ```python outport.send(message) ```