### Install Event Handler for Incoming Messages (GTK Example) Source: https://mido.readthedocs.io/en/stable/ports/index.html In event-based systems like GUIs, install a handler using `gobject.timeout_add_seconds` to periodically check for and process incoming messages. ```python def callback(self): for msg in self.inport: print(msg) gobject.timeout_add_seconds(timeout, callback) ``` -------------------------------- ### Install PortMidi on Ubuntu Source: https://mido.readthedocs.io/en/stable/backends/portmidi.html Use apt to install the PortMidi development library on Ubuntu. ```bash apt install libportmidi-dev ``` -------------------------------- ### Install PortMidi on macOS with Homebrew Source: https://mido.readthedocs.io/en/stable/backends/portmidi.html Use Homebrew to install the PortMidi library on macOS. ```bash brew install portmidi ``` -------------------------------- ### Build Package for Release Source: https://mido.readthedocs.io/en/stable/contributing.html Install necessary build tools and then build the package distribution files. ```bash source mido-build/bin/activate python3 -m pip install --upgrade pip setuptools wheel build twine python3 -m build ``` -------------------------------- ### Install Mido Development Dependencies with Ports Support from Source Source: https://mido.readthedocs.io/en/stable/contributing.html Install Mido in editable mode with development dependencies and ports support. ```bash python3 -m pip install --editable .[dev,ports-rtmidi] ``` -------------------------------- ### Install and Verify Package from Test PyPI Source: https://mido.readthedocs.io/en/stable/contributing.html Install the package from Test PyPI and check its version information to ensure it was published correctly. ```python python3 -m pip install --index-url https://test.pypi.org/simple/ --no-deps mido python3 -c "import mido; print(mido.version_info)" ``` -------------------------------- ### Install Mido Development Dependencies from Source Source: https://mido.readthedocs.io/en/stable/contributing.html Install Mido in editable mode with development dependencies for linting, testing, and documentation. ```bash python3 -m pip install --editable .[dev] ``` -------------------------------- ### Install Mido from Source Source: https://mido.readthedocs.io/en/stable/contributing.html Use this command to install Mido in editable mode from the sources root directory for general usage. ```bash python3 -m pip install --editable . ``` -------------------------------- ### Install a Callback Function Source: https://mido.readthedocs.io/en/stable/ports/index.html Install a callback function for an input port either during port creation or by assigning it to the 'callback' attribute. The callback will be invoked for each incoming message. ```python port = mido.open_input(callback=print_message) port.callback = print_message ``` -------------------------------- ### Install PortMidi on macOS with MacPorts Source: https://mido.readthedocs.io/en/stable/backends/portmidi.html Use MacPorts to install the PortMidi library on macOS. ```bash port install portmidi ``` -------------------------------- ### Install Mido with Ports Support from Source Source: https://mido.readthedocs.io/en/stable/contributing.html Use this command to install Mido in editable mode from the sources root directory, including support for ports. ```bash python3 -m pip install --editable .[ports-rtmidi] ``` -------------------------------- ### Start a Simple MIDI Socket Server Source: https://mido.readthedocs.io/en/stable/ports/index.html Create a basic server that listens on a specified host and port, printing received messages. ```python for message in PortServer('localhost', 8080): print(message) ``` -------------------------------- ### Install Mido using pip Source: https://mido.readthedocs.io/en/stable/installing.html Use this command to install the latest stable version of Mido from PyPi. It's recommended to use a virtual environment. ```bash python3 -m pip install mido ``` -------------------------------- ### Custom Output Port Example Source: https://mido.readthedocs.io/en/stable/ports/custom.html Example of a custom output port that prints MIDI messages to the console. This demonstrates subclassing BaseOutput and overriding the _send method. ```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 ``` -------------------------------- ### Install rtmidi-python Source: https://mido.readthedocs.io/en/stable/backends/rtmidi_python.html Install the rtmidi-python package using pip. This is required to use the rtmidi_python backend. ```python python3 - m pip install rtmidi-python ``` -------------------------------- ### Use Multiple Mido Backends Simultaneously Source: https://mido.readthedocs.io/en/stable/backends/index.html This example demonstrates how to open input and output ports using different backends concurrently. It requires instantiating `mido.Backend` for each desired backend. ```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) ``` -------------------------------- ### Install Mido with ports backend Source: https://mido.readthedocs.io/en/stable/installing.html Install Mido with the default ports backend (rtmidi) if you intend to use the ports feature. Ensure you have the necessary dependencies for the chosen backend. ```bash python3 -m pip install mido[ports-rtmidi] ``` -------------------------------- ### Build PDF Documentation Source: https://mido.readthedocs.io/en/stable/contributing.html Generate a PDF version of the documentation using Sphinx. Requires LaTeX and ImageMagick to be installed locally. The output PDF will be in docs/_build/latex/Mido.pdf. ```bash sphinx-build -M latexpdf docs docs/_build ``` -------------------------------- ### MIDI Note On Message Example Source: https://mido.readthedocs.io/en/stable/about_midi.html An example of a MIDI note on message, showing the status byte, note number, and velocity. ```text 92 3C 64 ``` -------------------------------- ### Implement Custom I/O Port with fjopp Source: https://mido.readthedocs.io/en/stable/ports/custom.html Example of a custom I/O port using the imaginary `fjopp` library. This defines `_open`, `_close`, `_send`, and a non-blocking `_receive` method. ```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 ``` -------------------------------- ### Example Plain Text SYX Output Source: https://mido.readthedocs.io/en/stable/files/syx.html This shows the expected format for plain text SYX files, with each SysEx message represented as a line of hex-encoded bytes. ```text F0 00 01 5D 02 00 F7 F0 00 01 5D 03 00 F7 ``` -------------------------------- ### Constructing Sysex Messages Source: https://mido.readthedocs.io/en/stable/message_types.html Examples of creating sysex messages with different data types for the 'data' parameter. ```python mido.Message('sysex', data=[1, 2, 3]) ``` ```python mido.Message('sysex', data=range(10)) ``` ```python mido.Message('sysex', data=(i for i in range(10) if i % 2 == 0)) ``` -------------------------------- ### Import Error Example Source: https://mido.readthedocs.io/en/stable/freezing_exe.html This is an example of an ImportError that may occur when PyInstaller cannot find a Mido backend module. ```python ImportError: No module named mido.backends.portmidi ``` -------------------------------- ### Set Default Input Port via Environment Variable Source: https://mido.readthedocs.io/en/stable/backends/index.html This example shows how to set a specific MIDI input port as the default using the `MIDO_DEFAULT_INPUT` environment variable. This is useful for programs that automatically connect to a particular device. ```bash $ MIDO_DEFAULT_INPUT='SH-201' python3 program.py ``` -------------------------------- ### Set Default Output Port via Environment Variable Source: https://mido.readthedocs.io/en/stable/backends/index.html This example demonstrates setting a default MIDI output port using the `MIDO_DEFAULT_OUTPUT` environment variable. The setting persists for the shell session, affecting subsequent program executions. ```bash $ export MIDO_DEFAULT_OUTPUT='Integra-7' $ python3 program1.py $ python3 program2.py ``` -------------------------------- ### Serve MIDI Ports Over Network Source: https://mido.readthedocs.io/en/stable/binaries.html Use mido-serve to make MIDI ports available over the network. This is useful for remote MIDI control or multi-computer setups. ```bash $ mido-serve :9080 'Integra-7' ``` -------------------------------- ### MIDI System Common and Real Time Messages Source: https://mido.readthedocs.io/en/stable/about_midi.html Examples of MIDI System Common and Real Time messages, such as 'Continue'. ```text # Continue (Starts a song that has been paused): FB ``` -------------------------------- ### Get Available Input Port Names Source: https://mido.readthedocs.io/en/stable/intro.html Retrieves a list of names for all available MIDI input ports on the system. ```python >>> mido.get_input_names() ['Midi Through Port-0', 'SH-201', 'Integra-7'] ``` -------------------------------- ### MIDI Channel Messages Source: https://mido.readthedocs.io/en/stable/about_midi.html Examples of common MIDI channel messages including note on, note off, and program change. ```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 ``` -------------------------------- ### Mido String Encoding Character Set Example Source: https://mido.readthedocs.io/en/stable/messages/index.html Provides an explicit string containing all allowed characters for Mido message serialization, demonstrating the character set used for encoding. ```text 'abcdefghijklmnopqrstuvwxyz0123456789 =_.+()' ``` -------------------------------- ### Create Meta Message Source: https://mido.readthedocs.io/en/stable/files/midi.html Meta messages can be created using the `MetaMessage` class. Example shows creating a 'key_signature' meta message. ```python from mido import MetaMessage MetaMessage('key_signature', key='C#', mode='major') ``` -------------------------------- ### Backend Class Source: https://mido.readthedocs.io/en/stable/api.html Wrapper for backend modules, providing convenient functions for opening ports and getting port names. ```APIDOC ## class mido.Backend ### Description 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. ### 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. Does nothing if the module is already loaded. This function will be called if you access the ‘module’ property. #### open_input(name=None, virtual=False, callback=None, **kwargs) Open an input port. If the environment variable MIDO_DEFAULT_INPUT is set, it will override the default port. - virtual (boolean): Passing True opens a new port that other applications can connect to. Raises IOError if not supported by the backend. - callback (function): 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, it will override the default port. - virtual (boolean): Passing True opens a new port that other applications can connect to. Raises IOError if not supported by the backend. - callback (function): 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 (boolean): 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, it will override the default port. - virtual (boolean): Passing True opens a new port that other applications can connect to. Raises IOError if not supported by the backend. - autoreset (boolean): Automatically send all_notes_off and reset_all_controllers on all channels. This is the same as calling port.reset(). ### Properties #### loaded (boolean) 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 Default Output Port Source: https://mido.readthedocs.io/en/stable/ports/index.html Opens the default system output port without specifying a name. This is a convenient way to get a port for sending MIDI messages. ```python port = mido.open_output() ``` -------------------------------- ### Implement Blocking Receive in Custom Port Source: https://mido.readthedocs.io/en/stable/ports/custom.html Example of implementing a blocking `_receive` method using `read_blocking()` for a custom port. This ensures the port actually blocks on the device when requested. ```python def _receive(self, block=True): if block: # Actually block on the device. # (``read_blocking()`` will always return some data.) while not ``self._messages``: data = self._device.read_blocking() self._parser.feed(data) else: # Non-blocking read like above. while True: data = self.device.read() if data: self._parser.feed(data) ``` -------------------------------- ### Get List of Available Output Ports Source: https://mido.readthedocs.io/en/stable/ports/index.html Retrieves a list of names for all available MIDI output ports on the system. This is useful for selecting a specific port to open. ```python >>> mido.get_output_names() ['SH-201', 'Integra-7'] ``` -------------------------------- ### Get Output Port Names (Linux/ALSA) Source: https://mido.readthedocs.io/en/stable/backends/rtmidi.html Retrieves a list of available MIDI output port names on Linux/ALSA systems. Port names may include client and port numbers. ```python >>> mido.get_output_names() ['TiMidity:TiMidity port 0 128:0'] ``` -------------------------------- ### Get Available RtMidi API Names Source: https://mido.readthedocs.io/en/stable/backends/rtmidi.html Retrieves a list of all available RtMidi API names that can be used at runtime. Examples include 'LINUX_ALSA' and 'UNIX_JACK'. ```python >>> mido.backend.module.get_api_names() ['LINUX_ALSA', 'UNIX_JACK'] ``` -------------------------------- ### Prepare Clean Environment for Manual Release Source: https://mido.readthedocs.io/en/stable/contributing.html Clone the specific branch and set up a virtual environment for manual release steps. ```bash git clone --branch --single-branch https://github.com/mido/mido mido- cd mido- python3 -m venv mido-build ``` -------------------------------- ### MIDI System Exclusive Message Example Source: https://mido.readthedocs.io/en/stable/about_midi.html An example of a System Exclusive (SysEx) message for a Roland SH-201 synthesizer. ```text F0 41 10 00 00 16 11 20 00 00 00 00 00 00 21 3F F7 ``` -------------------------------- ### Get Playback Length Source: https://mido.readthedocs.io/en/stable/files/midi.html Access the `length` property to get the total playback time in seconds. This is supported for type 0 and 1 MIDI files only. ```python mid.length ``` -------------------------------- ### Create and Save a New Midi File Source: https://mido.readthedocs.io/en/stable/files/midi.html Create a new MIDI file from scratch, add messages to a track, and save it to disk. Requires importing MidiFile, MidiTrack, and Message from mido. ```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') ``` -------------------------------- ### mido.ports.BaseInput methods Source: https://mido.readthedocs.io/en/stable/genindex.html Methods for handling MIDI input. ```APIDOC ## mido.ports.BaseInput methods ### Description Methods for receiving MIDI messages from an input port. ### Methods - **iter_pending()**: Iterates over pending MIDI messages in the input port. ``` -------------------------------- ### Create a MIDI Socket Server to Send Messages Source: https://mido.readthedocs.io/en/stable/ports/index.html Configure a server to send MIDI messages to connected clients. ```python server = PortServer('localhost', 8080) while True: server.send(message) ... ``` -------------------------------- ### mido.ports.get_sleep_time Source: https://mido.readthedocs.io/en/stable/api.html Get number of seconds sleep() will sleep. ```APIDOC ## mido.ports.get_sleep_time ### Description Get number of seconds sleep() will sleep. ### Method N/A (Function in mido.ports module) ### Parameters None ``` -------------------------------- ### Initialize and use the Mido Parser class Source: https://mido.readthedocs.io/en/stable/messages/parsing.html Create a `mido.Parser` object to incrementally parse MIDI bytes. Use `feed()` to provide bytes and `get_message()` to retrieve parsed messages. ```python >>> p = mido.Parser() >>> p.feed([0x90, 0x10, 0x20]) >>> p.pending() 1 >>> p.get_message() Message('note_on', channel=0, note=16, velocity=32, time=0) ``` ```python >>> p.feed_byte(0x90) >>> p.feed_byte(0x10) >>> p.feed_byte(0x20) >>> p.feed([0x80, 0x10, 0x20]) >>> p.pending() 2 >>> p.get_message() Message('note_on', channel=0, note=16, velocity=32, time=0) >>> p.get_message() Message('note_off', channel=0, note=16, velocity=32, time=0) ``` -------------------------------- ### Importing Mido Classes Source: https://mido.readthedocs.io/en/stable/changes.html Import necessary classes for working with MIDI files and meta messages. ```python from mido import MidiFile, MidiTrack, MetaMessage from mido.midifiles import MetaSpec, add_meta_spec ``` -------------------------------- ### Build HTML Documentation Source: https://mido.readthedocs.io/en/stable/contributing.html Generate the HTML documentation using Sphinx. This command uses parallel building (-j auto), quiet output (-q), treats warnings as errors (-W), and forces re-creation of all files (-E). ```bash sphinx-build -j auto -q -W -E --keep-going docs docs/_build ``` -------------------------------- ### Check Release Manifest Source: https://mido.readthedocs.io/en/stable/contributing.html Verify that the repository and source code manifest (.MANIFEST.in) are synchronized. Use the --verbose flag for detailed output. ```bash check-manifest --verbose ``` -------------------------------- ### MIDI System Exclusive Message Structure Source: https://mido.readthedocs.io/en/stable/about_midi.html The structure of a System Exclusive (SysEx) message, indicating its start and end bytes. ```text F0 ... F7 ``` -------------------------------- ### Create and Use Mido Parser Source: https://mido.readthedocs.io/en/stable/intro.html Instantiate a Mido Parser, feed it bytes, and retrieve pending messages. Use this for real-time MIDI stream processing. ```python >>> p = mido.Parser() >>> p.feed([0x90, 0x40]) >>> p.feed_byte(0x60) ``` ```python >>> p.pending() 1 >>> for message in p: ... print(message) ... note_on channel=0 note=64 velocity=96 time=0 ``` -------------------------------- ### Iterate over messages from the Mido Parser Source: https://mido.readthedocs.io/en/stable/messages/parsing.html You can iterate directly over a `mido.Parser` object to get parsed messages. The `feed()` method accepts any iterable of integers. ```python >>> p.feed([0x92, 0x10, 0x20, 0x82, 0x10, 0x20]) >>> for message in p: ... print(message) note_on channel=2 note=16 velocity=32 time=0 note_off channel=2 note=16 velocity=32 time=0 ``` -------------------------------- ### Tag a New Release Source: https://mido.readthedocs.io/en/stable/contributing.html Create an annotated Git tag for the new release version. Annotated tags retain more information than lightweight tags. ```bash git tag -a -m "mido version " ``` -------------------------------- ### mido.ports.BaseOutput methods Source: https://mido.readthedocs.io/en/stable/genindex.html Methods for sending MIDI output. ```APIDOC ## mido.ports.BaseOutput methods ### Description Methods for sending MIDI messages to an output port. ### Methods (No specific output methods documented in this section, but implied by the class) ### Attributes - **is_output**: Indicates if the port is an output port. ``` -------------------------------- ### Valid Input for Stream Parsing Source: https://mido.readthedocs.io/en/stable/messages/index.html Illustrates the expected format for input to `parse_string_stream()`, including comments (starting with '#') and blank lines, which are ignored during parsing. ```text # A very short song with an embedded sysex message. note_on channel=9 note=60 velocity=120 time=0 # Send some data sysex data=(1,2,3) time=0.5 pitchwheel pitch=4000 # bend the not a little time=0.7 note_off channel=9 note=60 velocity=60 time=1.0 ``` -------------------------------- ### Initialize MidiTrack with Messages Source: https://mido.readthedocs.io/en/stable/changes.html Initialize a MidiTrack with an iterable of messages. This can be used with lists, generators, or pending messages from a port. ```python MidiTrack(messages) ``` ```python MidiTrack(port.iter_pending()) ``` ```python MidiTrack(msg for msg in some_generator) ``` -------------------------------- ### Run Ruff Linter Source: https://mido.readthedocs.io/en/stable/contributing.html Execute the ruff linter to check code style and quality. Configuration is in pyproject.toml. ```bash ruff check . ``` -------------------------------- ### Advanced MIDI Socket Server with Connection Handling Source: https://mido.readthedocs.io/en/stable/ports/index.html Implement a server that accepts multiple client connections and processes messages from each. ```python with PortServer('localhost', 8080) as server: while True: client = server.accept() for message in client: print(message) ``` -------------------------------- ### Get First Parsed Message Source: https://mido.readthedocs.io/en/stable/api.html Call get_message() on a Parser object to retrieve the next available parsed MIDI message. Returns None if no message is ready. ```python message = parser.get_message() ``` -------------------------------- ### Run REUSE Compliance Check Source: https://mido.readthedocs.io/en/stable/contributing.html Check if the project adheres to REUSE compliance standards. This command verifies copyright and license information. ```bash reuse lint ``` -------------------------------- ### Connect to a MIDI Socket Server and Send Messages Source: https://mido.readthedocs.io/en/stable/ports/index.html Connect to a running socket server and send MIDI messages to it. ```python output = connect('localhost', 8080) output.send(message) ``` -------------------------------- ### Create and Open Virtual Input Port (RtMidi) Source: https://mido.readthedocs.io/en/stable/backends/rtmidi.html Creates and opens a virtual MIDI input port named 'New Port'. Virtual ports allow other applications to connect to them. Note: Not available on Windows. ```python >>> port = mido.open_input('New Port', virtual=True) >>> port ``` -------------------------------- ### Example of Mido Messages in JSON Source: https://mido.readthedocs.io/en/stable/messages/index.html Demonstrates how Mido messages, serialized as strings, can be embedded within a JSON structure. This is a common use case for storing or transmitting message sequences. ```json { "messages": [ "0.0 note_on channel=9 note=60 velocity=120", "0.5 sysex data=(1,2,3)", "...", ] } ``` -------------------------------- ### Use the Parser Class to Feed Bytes Source: https://mido.readthedocs.io/en/stable/messages/index.html Instantiate a Parser and use feed() to provide bytes. Use pending() to check for available messages and get_message() to retrieve them. ```python >>> p = mido.Parser() >>> p.feed([0x90, 0x10, 0x20]) >>> p.pending() 1 >>> p.get_message() Message('note_on', channel=0, note=16, velocity=32, time=0) ``` -------------------------------- ### Publish Package to Test PyPI Source: https://mido.readthedocs.io/en/stable/contributing.html Upload the built package distributions to the Test PyPI repository for verification. ```bash python3 -m build twine upload --repository testpypi dist/* ``` -------------------------------- ### mido.ports.MultiPort methods Source: https://mido.readthedocs.io/en/stable/genindex.html Methods for handling multiple MIDI ports. ```APIDOC ## mido.ports.MultiPort methods ### Description Methods for managing and interacting with multiple MIDI ports simultaneously. ### Methods - **iter_pending()**: Iterates over pending MIDI messages from all associated ports. ``` -------------------------------- ### Iterate Over MIDI Messages in Playback Order Source: https://mido.readthedocs.io/en/stable/files/midi.html Iterate directly over a `MidiFile` object to get messages in playback order. The `time` attribute is in seconds. Meta messages can be filtered using `msg.is_meta`. ```python if msg.is_meta: ... ``` -------------------------------- ### Initialize MIDI Parser Source: https://mido.readthedocs.io/en/stable/api.html Create a Parser object to process a stream of MIDI bytes. Data can be provided initially or fed later using the feed() or feed_byte() methods. ```python import mido parser = mido.parser.Parser() ``` -------------------------------- ### Publish Package to PyPI Source: https://mido.readthedocs.io/en/stable/contributing.html Upload the final package distributions to the main PyPI repository. This action is irreversible. ```bash twine upload dist/* ``` -------------------------------- ### Play MIDI File Source: https://mido.readthedocs.io/en/stable/index.html Loads a MIDI file and plays its messages through an output port. Requires a MIDI file and an open output port. ```python mid = mido.MidiFile('song.mid') for msg in mid.play(): port.send(msg) ``` -------------------------------- ### Commit Release Preparation Source: https://mido.readthedocs.io/en/stable/contributing.html Commit the changes made to the changelog and version files before tagging the release. ```bash git commit -a -c "Prepare release." ``` -------------------------------- ### Add SPDX Header for Copyright Source: https://mido.readthedocs.io/en/stable/contributing.html Format for adding SPDX copyright and license information to files. Use the appropriate comment format for the file type. ```text # SPDX-FileCopyrightText: YYYY First_Name Last_Name # # SPDX-License-Identifier: MIT ``` -------------------------------- ### Import Mido Socket Modules Source: https://mido.readthedocs.io/en/stable/ports/index.html Import necessary classes for creating and connecting to socket ports. ```python from mido.sockets import PortServer, connect ``` -------------------------------- ### PyInstaller Build Command and Execution Source: https://mido.readthedocs.io/en/stable/freezing_exe.html After adding the explicit import, use PyInstaller to build the executable. This command builds a single executable file. ```bash $ pyinstaller --onefile midotest.py $ ./dist/midotest [u'Midi Through Port-0'] ``` -------------------------------- ### Custom Backend Device Information Structure Source: https://mido.readthedocs.io/en/stable/backends/index.html When implementing a custom Mido backend, the `get_devices()` function should return a list of dictionaries. Each dictionary represents a MIDI device and must include 'name', 'is_input', and 'is_output' keys. ```json { "name": "Some MIDI Input Port", "is_input": True, "is_output": False, } ``` -------------------------------- ### Open a MIDI File Source: https://mido.readthedocs.io/en/stable/files/midi.html Use `MidiFile` to open a MIDI file for reading. Ensure the file is a valid MIDI file; otherwise, consider `mido.read_syx_file()` for SYX files. ```python from mido import MidiFile mid = MidiFile('song.mid') ``` -------------------------------- ### Device Information Dictionary Structure Source: https://mido.readthedocs.io/en/stable/backends/custom.html The `get_devices()` function should return a list of dictionaries, where each dictionary represents a MIDI device and must include 'name', 'is_input', and 'is_output' keys. ```python { 'name': 'Some MIDI Input Port', 'is_input': True, 'is_output': False, } ``` -------------------------------- ### Open Input and Output Ports Source: https://mido.readthedocs.io/en/stable/ports/index.html Opens an input port named 'SH-201' and an output port named 'Integra-7'. These are typically used to interact with MIDI devices. ```python >>> inport = mido.open_input('SH-201') >>> outport = mido.open_output('Integra-7') ``` -------------------------------- ### mido.ports.IOPort methods Source: https://mido.readthedocs.io/en/stable/genindex.html Methods for interacting with input/output ports. ```APIDOC ## mido.ports.IOPort methods ### Description Methods available on mido.ports.IOPort instances for handling MIDI input and output. ### Methods - **iter_pending()**: Iterates over pending MIDI messages in the port. ``` -------------------------------- ### Connect to a MIDI Socket Server to Receive Messages Source: https://mido.readthedocs.io/en/stable/ports/index.html Establish a client connection to a socket server to receive outgoing MIDI messages. ```python for message in connect('localhost', 8080): print(message) ``` -------------------------------- ### mido.Backend methods Source: https://mido.readthedocs.io/en/stable/genindex.html Provides access to backend-specific methods for managing MIDI ports and messages. ```APIDOC ## mido.Backend methods ### Description Methods available on mido.Backend instances for interacting with MIDI ports. ### Methods - **get_input_names()**: Returns a list of available input port names. - **get_ioport_names()**: Returns a list of available input/output port names. - **get_output_names()**: Returns a list of available output port names. - **load()**: Loads a MIDI file or data. ### Properties - **loaded**: Returns True if a MIDI file or data has been loaded, False otherwise. ``` -------------------------------- ### Connect MIDI Ports to Network Server Source: https://mido.readthedocs.io/en/stable/binaries.html Use mido-connect to forward messages from local MIDI ports to a network server. This allows remote control of MIDI devices. ```bash $ mido-connect mac.local:9080 'SH-201' ``` -------------------------------- ### mido.open_input Source: https://mido.readthedocs.io/en/stable/api.html Opens an input port for receiving MIDI messages. Supports virtual ports and callback functions for message handling. The default input port can be overridden by the MIDO_DEFAULT_INPUT environment variable. ```APIDOC ## mido.open_input ### Description Opens an input port for receiving MIDI messages. Supports virtual ports and callback functions for message handling. The default input port can be overridden by the MIDO_DEFAULT_INPUT environment variable. ### Method `mido.open_input(_name =None_, _virtual =False_, _callback =None_, _** kwargs_)` ### Parameters #### Path Parameters - **_name** (string) - Optional - The name of the port to open. - **_virtual** (boolean) - Optional - If True, opens a new port that other applications can connect to. Raises IOError if not supported by the backend. - **_callback** (function) - Optional - 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. #### Keyword Arguments - **_**kwargs** - Additional keyword arguments to be passed to the backend. ``` -------------------------------- ### mido.open_ioport Source: https://mido.readthedocs.io/en/stable/api.html Opens a port for both MIDI input and output. Supports virtual ports, callback functions, and automatic reset. The default I/O port can be overridden by the MIDO_DEFAULT_IOPORT environment variable. ```APIDOC ## mido.open_ioport ### Description Opens a port for both MIDI input and output. Supports virtual ports, callback functions, and automatic reset. The default I/O port can be overridden by the MIDO_DEFAULT_IOPORT environment variable. ### Method `mido.open_ioport(_name =None_, _virtual =False_, _callback =None_, _autoreset =False_, _** kwargs_)` ### Parameters #### Path Parameters - **_name** (string) - Optional - The name of the port to open. - **_virtual** (boolean) - Optional - If True, opens a new port that other applications can connect to. Raises IOError if not supported by the backend. - **_callback** (function) - Optional - 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** (boolean) - Optional - If True, automatically sends all_notes_off and reset_all_controllers on all channels. #### Keyword Arguments - **_**kwargs** - Additional keyword arguments to be passed to the backend. ``` -------------------------------- ### Required Backend Components Source: https://mido.readthedocs.io/en/stable/backends/custom.html A backend module must implement at least one of these components: an input port class, an output port class, an I/O port class, or a `get_devices()` function. ```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.sockets.PortServer methods Source: https://mido.readthedocs.io/en/stable/genindex.html Methods for managing network-based MIDI ports. ```APIDOC ## mido.sockets.PortServer methods ### Description Methods for controlling a server that provides MIDI ports over a network. ### Methods - **iter_pending()**: Iterates over pending MIDI messages received by the server. ### Attributes - **is_input**: Indicates if the port server is configured for input. - **is_output**: Indicates if the port server is configured for output. ``` -------------------------------- ### Select Mido Backend via Environment Variable Source: https://mido.readthedocs.io/en/stable/backends/index.html You can specify a Mido backend other than the default (RtMidi) by setting the `MIDO_BACKEND` environment variable before running your program. ```bash $ MIDO_BACKEND=mido.backends.portmidi ./program.py ``` -------------------------------- ### Create and Inspect MIDI Message Source: https://mido.readthedocs.io/en/stable/index.html Demonstrates creating a MIDI message and accessing its attributes and byte representation. Use this to programmatically generate MIDI events. ```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) ``` -------------------------------- ### Receive and Send MIDI Messages Source: https://mido.readthedocs.io/en/stable/ports/index.html Demonstrates receiving a message from an input port and sending it to an output port. The send() method copies the message, allowing the original to be modified. ```python >>> msg = inport.receive() >>> outport.send(msg) ``` -------------------------------- ### Open Default Output Port and Send Message Source: https://mido.readthedocs.io/en/stable/intro.html Opens the default output port and sends a message. Ensure 'msg' is a valid Mido message object. ```python >>> outport = mido.open_output() >>> outport.send(msg) ``` -------------------------------- ### Send a MIDI Message with Output Port Source: https://mido.readthedocs.io/en/stable/ports/index.html Use the `send()` method to transmit a MIDI message immediately through an output port. The port implementation determines the exact behavior. ```python outport.send(message) ``` -------------------------------- ### Check Port Capabilities in Custom Port Source: https://mido.readthedocs.io/en/stable/ports/custom.html Demonstrates how to check if a custom port supports sending or receiving by using `hasattr()` 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. ``` -------------------------------- ### Run Pytest Suite Source: https://mido.readthedocs.io/en/stable/contributing.html Execute the unit test suite using pytest. Tests are located in tests/test_*.py and configured in pyproject.toml. ```bash pytest ``` -------------------------------- ### mido.ports.BaseInput attributes Source: https://mido.readthedocs.io/en/stable/genindex.html Attributes for BaseInput instances. ```APIDOC ## mido.ports.BaseInput attributes ### Description Attributes providing status and type information for BaseInput objects. ### Attributes - **is_input**: Boolean indicating if the port is an input port. - **is_output**: Boolean indicating if the port is an output port. ``` -------------------------------- ### Open Virtual Input Port with Client Name (RtMidi) Source: https://mido.readthedocs.io/en/stable/backends/rtmidi.html Opens a virtual MIDI input port and specifies a client name. This requires python-rtmidi version 1.0rc1 or later. Passing a client name automatically makes the port virtual. ```python >>> port = mido.open_input('New Port', client_name='My Client') ``` -------------------------------- ### Send MIDI Message to Output Port Source: https://mido.readthedocs.io/en/stable/index.html Opens a MIDI output port and sends a message. Ensure the port name is correct for your system. ```python port = mido.open_output('Port Name') port.send(msg) ``` -------------------------------- ### Create and Use a Virtual Input Port Source: https://mido.readthedocs.io/en/stable/intro.html Creates a virtual input port named 'New Port' that other applications can connect to. This functionality relies on RtMidi and is not supported on Windows. ```python with mido.open_input('New Port', virtual=True) as inport: for message in inport: print(message) ``` -------------------------------- ### Create a Custom Output Port Source: https://mido.readthedocs.io/en/stable/ports/index.html Subclass BaseOutput and override _send to define custom output behavior, such as printing messages. ```python from mido.ports import BaseOutput class PrintPort(BaseOutput): def _send(message): print(message) ``` ```python >>> port = PrintPort() >>> port.send(msg) note_on channel=0 note=0 velocity=64 time=0 ``` -------------------------------- ### Open Output Port with Partial Name (RtMidi) Source: https://mido.readthedocs.io/en/stable/backends/rtmidi.html Opens an output MIDI port using a partial name, allowing omission of port number and client names. This is useful as port numbers can change between sessions. ```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') ``` -------------------------------- ### Write SYX File Source: https://mido.readthedocs.io/en/stable/files/syx.html Use this snippet to write a list of Mido messages to a binary SYX file. Non-SysEx messages will be ignored during writing. ```python mido.write_syx_file('patch.syx', messages) ``` -------------------------------- ### Receive a Single MIDI Message (Blocking) Source: https://mido.readthedocs.io/en/stable/ports/index.html Use `receive()` to block execution until a single MIDI message arrives on the port. ```python msg = port.receive() ``` -------------------------------- ### Play MIDI File Messages to a Port Source: https://mido.readthedocs.io/en/stable/files/midi.html Play MIDI messages from a file to a port, with a delay based on `msg.time`. This basic implementation may suffer from time drift. Meta messages are excluded by default. ```python import time for msg in MidiFile('song.mid'): time.sleep(msg.time) if not msg.is_meta: port.send(msg) ``` -------------------------------- ### mido.open_output Source: https://mido.readthedocs.io/en/stable/api.html Opens an output port for sending MIDI messages. Supports virtual ports and automatic reset functionality. The default output port can be overridden by the MIDO_DEFAULT_OUTPUT environment variable. ```APIDOC ## mido.open_output ### Description Opens an output port for sending MIDI messages. Supports virtual ports and automatic reset functionality. The default output port can be overridden by the MIDO_DEFAULT_OUTPUT environment variable. ### Method `mido.open_output(_name =None_, _virtual =False_, _autoreset =False_, _** kwargs_)` ### Parameters #### Path Parameters - **_name** (string) - Optional - The name of the port to open. - **_virtual** (boolean) - Optional - If True, opens a new port that other applications can connect to. Raises IOError if not supported by the backend. - **_autoreset** (boolean) - Optional - If True, automatically sends all_notes_off and reset_all_controllers on all channels. #### Keyword Arguments - **_**kwargs** - Additional keyword arguments to be passed to the backend. ``` -------------------------------- ### Create Custom Meta Message Source: https://mido.readthedocs.io/en/stable/meta_message_types.html Instantiate a custom meta message using the MetaMessage constructor with the message name and its attributes. ```python from mido import MetaMessage MetaMessage('light_color', r=120, g=60, b=10) ``` -------------------------------- ### Open Default Input Port and Receive Message Source: https://mido.readthedocs.io/en/stable/intro.html Opens the default input port and receives a message. The 'msg' variable will be populated with the received message. ```python >>> inport = mido.open_input() >>> msg = inport.receive() ```