pyrtmidi
pyrtmidi is a Python interface to RtMidi?. It provides real-time midi input and output.
import rtmidi midiin = rtmidi.RtMidiIn() ports = range(midiin.getPortCount()) if ports: for i in ports: print midiin.getPortName(i) midiin.openPort(1, True) while True: print 'MESSAGE:',midiin.getMessage() else: print 'NO MIDI INPUT PORTS!'
Documentation
The API is copied near verbatim from the C++ code. Refer to the RtMidi tutorial, and take into account the following caveats:
RtMidiIn?
openPort(port, blocking=False)
- The port argument is required, and cannot be 0 (this locked my system, not sure why).
- An optional blocking argument causes getMessage() to block and wait for a message instead of its default behavior, which is to not block and return a blank message.
getMessage()
- The message argument has been removed.
- The call will always return (byte1, byte2, byte3, timestamp) - or an empty tuple if no data was available.
- getMessage() will block if openPort() was called with blocking enabled.
- If openPort() was called with blocking disabled, the return value will be an empty tuple.
setCallback
- Callback support is not available yet.
- Use openPort(port, blocking=True).
Recipes
QObject interface
The pksampler implements a QObject wrapper for rtmidi.RtMidiIn? that emits a 'message()' signal. The original source can be found at /pk/sampler/midi.py. The essential code is follows:
class MidiInput(QThread): def __init__(self, devid, parent=None): QThread.__init__(self, parent) self.device = rtmidi.RtMidiIn() self.device.openPort(devid, True) self.running = False def run(self): self.running = True while self.running: msg = self.device.getMessage() if msg: self.msg = msg self.emit(SIGNAL('message(PyObject *)'), self.msg) self.emit(SIGNAL('message()') midi = MidiInput(1) def slotMessage(msg): print msg QObject.connect(midi, SIGNAL('message(PyObject *)'), slotMessage)