|
| 1 | +class MIDI: |
| 2 | + """A helper for encoding/decoding MIDI packets over a midi or uart connection""" |
| 3 | + |
| 4 | + NOTE_ON = 0x90 |
| 5 | + NOTE_OFF = 0x80 |
| 6 | + |
| 7 | + def __init__(self, midi_in, midi_out, *, in_channel=None, out_channel=0): |
| 8 | + self._midi_in = midi_in |
| 9 | + self._midi_out = midi_out |
| 10 | + self.in_channel = in_channel |
| 11 | + self.out_channel = out_channel |
| 12 | + self._debug = True |
| 13 | + |
| 14 | + @property |
| 15 | + def in_channel(self): |
| 16 | + return self._in_channel |
| 17 | + |
| 18 | + @in_channel.setter |
| 19 | + def in_channel(self, channel): |
| 20 | + if (channel is not None) and not (0 <= channel <= 15): |
| 21 | + raise RuntimeError("Invalid input channel") |
| 22 | + self._in_channel = channel |
| 23 | + |
| 24 | + @property |
| 25 | + def out_channel(self): |
| 26 | + return self._out_channel |
| 27 | + |
| 28 | + @out_channel.setter |
| 29 | + def out_channel(self, channel): |
| 30 | + if not (0 <= channel <= 15): |
| 31 | + raise RuntimeError("Invalid output channel") |
| 32 | + self._out_channel = channel |
| 33 | + |
| 34 | + def note_on(self, note, vel, channel=None): |
| 35 | + if not (0 <= note <= 0x7F): |
| 36 | + raise RuntimeError("Note value invalid") |
| 37 | + if not (0 <= vel <= 0x7F): |
| 38 | + raise RuntimeError("Velocity invalid") |
| 39 | + if not channel: |
| 40 | + channel = self._out_channel |
| 41 | + self._send([self.NOTE_ON | channel, note, vel]) |
| 42 | + |
| 43 | + def _send(self, packet): |
| 44 | + if self._debug: |
| 45 | + print("Sending: ", [hex(i) for i in packet]) |
| 46 | + print(self._midi_out(packet)) |
0 commit comments