Skip to content

Instantly share code, notes, and snippets.

@zooba
Last active September 5, 2020 12:56
Show Gist options
  • Save zooba/75279203dcdcb4ee1f0a9bfe545bba77 to your computer and use it in GitHub Desktop.
Save zooba/75279203dcdcb4ee1f0a9bfe545bba77 to your computer and use it in GitHub Desktop.
WinRT script showing MIDI in/out with the PreSonus Faderport
import asyncio
from winrt.windows.devices import midi
from winrt.windows.devices.enumeration import DeviceInformation
async def list_ports(kind=midi.MidiInPort):
devs = await DeviceInformation.find_all_async(kind.get_device_selector(), [])
return {d.name: d.id for d in devs}
async def main():
in_port_id = (await list_ports())['PreSonus FP2 [1]']
in_port = await midi.MidiInPort.from_id_async(in_port_id)
print("Input device:", in_port, in_port_id)
out_port_id = (await list_ports(midi.MidiOutPort))['PreSonus FP2 [0]']
out_port = await midi.MidiOutPort.from_id_async(out_port_id)
print("Output device:", out_port, out_port_id)
LEVEL = 0
def midi_in_event(sender, e):
nonlocal LEVEL
if e.message.type == midi.MidiMessageType.NOTE_ON:
n = midi.MidiNoteOnMessage._from(e.message)
print('note on', n.channel, n.note, n.velocity)
if n.note in {46, 47, 32} and n.velocity == 127:
LEVEL += {46: -1000, 47: 1000, 32: -LEVEL}[n.note]
LEVEL = min(max(LEVEL, 0), 2**14-1)
out_port.send_message(midi.MidiPitchBendChangeMessage(0, LEVEL))
elif e.message.type == midi.MidiMessageType.PITCH_BEND_CHANGE:
n = midi.MidiPitchBendChangeMessage._from(e.message)
print('pitch', n.channel, n.bend)
LEVEL = n.bend
elif e.message.type == midi.MidiMessageType.CONTROL_CHANGE:
n = midi.MidiControlChangeMessage._from(e.message)
print('control', n.channel, n.controller, n.control_value)
if n.controller == 16:
if n.control_value <= 64:
LEVEL += 100 * n.control_value
else:
LEVEL -= 100 * (n.control_value - 64)
LEVEL = min(max(LEVEL, 0), 2**14-1)
out_port.send_message(midi.MidiPitchBendChangeMessage(0, LEVEL))
else:
t = e.message.type
print(next((k for k in dir(midi.MidiMessageType) if getattr(midi.MidiMessageType, k) == t), t))
in_port.add_message_received(midi_in_event)
while True:
await asyncio.sleep(1.0)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment