Donnerstag, 7. Dezember 2017

MIDI Programming SourceCode for Python

import sys, pygame, pygame.midi
 
 # set up pygame
 pygame.init()
 pygame.midi.init()
 
 # list all midi devices
 for x in range( 0, pygame.midi.get_count() ):
     print pygame.midi.get_device_info(x)
 
 # open a specific midi device
 inp = pygame.midi.Input(2)
 
 # run the event loop
 while True:
     if inp.poll():
         # no way to find number of messages in queue
         # so we just specify a high max value
         print inp.read(1000)
 
     # wait 10ms - this is arbitrary, but wait(0) still resulted
     # in 100% cpu utilization
     pygame.time.wait(10)
The output of the above looks something like this after starting up and hitting a pad on my NanoPad controller:
1
2
3
4
5
6
7
8
'CoreMIDI', 'IAC Driver Bus 1', 1, 0, 0)
('CoreMIDI', 'IAC Driver IAC Bus 2', 1, 0, 0)
('CoreMIDI', 'nanoPAD PAD', 1, 0, 0)
('CoreMIDI', 'IAC Driver Bus 1', 0, 1, 0)
('CoreMIDI', 'IAC Driver IAC Bus 2', 0, 1, 0)
('CoreMIDI', 'nanoPAD CTRL', 0, 1, 0)
[[[144, 55, 107, 0], 4993]]
[[[128, 55, 64, 0], 5059]]
I’ve enumerated the MIDI input and output devices in the code, and the first 3 items in the list above are the inputs and the rest are the outputs. You can see the MIDI data in the two python lists at the end.
When I hit ctrl-c to stop the program I get an error from PortMidi. This probably isn’t a big deal, but I suppose exiting the program should be handled more gracefully and/or this exception should be handled. Not sure what they pythonic/pygameic way of doing this is yet, but here is the trace:
1
2
3
4
5
Traceback (most recent call last):
  File "midi.py", line 21, in
    pygame.time.wait(10)
KeyboardInterrupt
Exception Exception: Exception("PortMidi: `Bad pointer'",) in

Keine Kommentare:

Kommentar veröffentlichen

Hinweis: Nur ein Mitglied dieses Blogs kann Kommentare posten.