Skip to content

Instantly share code, notes, and snippets.

@omriman067
Last active March 6, 2019 07:58
Show Gist options
  • Save omriman067/2ec59228c6d0803fcf7c5d72e1a3049e to your computer and use it in GitHub Desktop.
Save omriman067/2ec59228c6d0803fcf7c5d72e1a3049e to your computer and use it in GitHub Desktop.
import sys, pygame, pygame.midi
import time
# set up pygame
M_NOTE_ON = 144
M_NOTE_OFF = 128
M_RIBBON_ON = 100
pygame.init()
pygame.midi.init()
# list all midi devices
for x in range(0, pygame.midi.get_count()):
print(str(x) + ': ' + str(pygame.midi.get_device_info(x)))
# open a specific midi device
# inp = pygame.midi.Input(1)
inp = pygame.midi.Input(pygame.midi.get_default_input_id())
# run the event loop
port = pygame.midi.get_default_output_id()
# port = 2
print("using output_id :%s:" % port)
midi_out = pygame.midi.Output(port)
midi_out.set_instrument(6)
last = 0
lastms = 0
stop = True
note_on = False
notes = []
while True:
if inp.poll():
# no way to find number of messages in queue
# so we just specify a high max value
keystrokes = inp.read(1000)
print(keystrokes)
for key in keystrokes:
if key[0][1] > 43 and key[0][1] < 85 and key[0][0] == M_NOTE_ON:
last = key[0][1]
notes.append(key[0][1])
note_on = True
if stop:
midi_out.note_on(key[0][1], 127) # 74 is middle C, 127 is "how loud" - max is 127
if key[0][1] > 43 and key[0][1] < 85 and key[0][0] == M_NOTE_OFF:
note_on = False
notes.remove(key[0][1])
if stop:
midi_out.note_off(key[0][1], 127)
if key[0][1] == M_RIBBON_ON:
if key[0][2] > 0:
# OldRange = (127 - 1)
# NewRange = (127 - 60)
# NewValue = (((key[0][2] - 1) * NewRange) / OldRange) + 100
stop = False
else:
stop = True
ms = int(time.time() * 10)
if not stop and len(notes) > 0:
for note in notes:
midi_out.note_on(note, 127) # 74 is middle C, 127 is "how loud" - max is 127
pygame.time.wait(80)
for note in notes:
midi_out.note_off(note, 127) # 74 is middle C, 127 is "how loud" - max is 127
# wait 10ms - this is arbitrary, but wait(0) still resulted
# in 100% cpu utilization
# pygame.time.wait(10)
@omriman067
Copy link
Author

Please replace magic numbers like key[0][0] == 144: and key[0][0] == 128: with constants, like

M_NOTE_ON = 144
key[0][0] == M_NOTE_ON:
...

You can do it even by defining these constants in a class/module, but not really needed for such a teeny tiny project.

this was just a small script to fool around but you are right, changed :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment