Sending MIDI messages using Python (on Ubuntu)

You need to add a sleep to your call, right after you send the message to the output.

I have added a simple sleep right after the message of 1s and the tone play just fine


Ok, well, I got the MIDI in/out working, by creating a small script that echoes whatever is played on the keyboard, with certain delay:

import mido
import time
from collections import deque

print mido.get_output_names() # To list the output ports
print mido.get_input_names() # To list the input ports

inport = mido.open_input('DigitalKBD MIDI 1')
outport = mido.open_output('DigitalKBD MIDI 1')

msglog = deque()
echo_delay = 2

while True:
    while inport.pending():
        msg = inport.receive()
        if msg.type != "clock":
            print msg
            msglog.append({"msg": msg, "due": time.time() + echo_delay})
    while len(msglog) > 0 and msglog[0]["due"] <= time.time():
        outport.send(msglog.popleft()["msg"])

This script works very well, so I had opportunity to walk carefully back to see why my initial test was unsuccessful. Turns out, for the output messages to be received, the input port also has to be opened. Don't know the reason why, but this is the simplest code that works:

import mido
inport = mido.open_input('DigitalKBD MIDI 1')
outport = mido.open_output('DigitalKBD MIDI 1')
outport.send(mido.Message('note_on', note=72))

What's more, if the python is exited immediately after running the above code, it might happen that MIDO did not manage to send the message, so no sound will be played. Give it some time to wrap up.

Tags:

Python

Midi