Mido - MIDI Objects for Python

1.3.3 · active · verified Tue Apr 14

Mido is a Python library for working with MIDI 1.0 ports, messages, and files. It provides a straightforward and Pythonic interface for interacting with MIDI hardware and software. The library is currently at version 1.3.3 and has an active development cycle, with new features and bug fixes being regularly released.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create MIDI messages, list available ports, send a message to an output port, and read/play messages from a MIDI file. It includes a fallback for when no physical MIDI ports are available and creates a dummy MIDI file for demonstration.

import mido

# Create a MIDI message
msg = mido.Message('note_on', note=60, velocity=64, time=0)
print(f"Created message: {msg}")

# List available MIDI ports (example, actual names vary)
print("Available input ports:", mido.get_input_names())
print("Available output ports:", mido.get_output_names())

# Open an output port and send a message (replaces 'Port Name' with an actual port if available)
try:
    outport_name = next(iter(mido.get_output_names()), None)
    if outport_name:
        print(f"Attempting to open output port: {outport_name}")
        with mido.open_output(outport_name) as outport:
            print(f"Sending {msg} to {outport_name}")
            outport.send(msg)
            print("Message sent.")
    else:
        print("No output MIDI ports found to send message.")
except Exception as e:
    print(f"Could not send MIDI message: {e}")

# Read a MIDI file (requires a 'test.mid' file, creating a dummy one)
try:
    mid = mido.MidiFile()
    track = mido.MidiTrack()
    mid.tracks.append(track)
    track.append(mido.Message('note_on', note=60, velocity=100, time=0))
    track.append(mido.Message('note_off', note=60, velocity=100, time=120))
    mid.save('test.mid')
    print("Created dummy 'test.mid'")

    print("Reading messages from 'test.mid':")
    for msg in mido.MidiFile('test.mid').play():
        print(msg)
except Exception as e:
    print(f"Could not read/create MIDI file: {e}")

view raw JSON →