-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmidi2pd.py
66 lines (54 loc) · 1.38 KB
/
midi2pd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import sys
import os
import json
import pygame
import pygame.midi
class MIDIInput():
def __enter__(self):
pygame.init()
pygame.midi.init()
self._print_device_info()
if device_id is None:
input_id = pygame.midi.get_default_input_id()
else:
input_id = device_id
print("using input_id :%s:" % input_id)
return pygame.midi.Input(input_id)
def __exit__(self, type, value, traceback):
pygame.midi.quit()
pygame.quit()
def _print_device_info(self):
for i in range(pygame.midi.get_count()):
r = pygame.midi.get_device_info(i)
(interf, name, input, output, opened) = r
in_out = ""
if input:
in_out = "(input)"
if output:
in_out = "(output)"
print(
"%2i: interface :%s:, name :%s:, opened :%s: %s"
% (i, interf, name, opened, in_out)
)
if __name__ == "__main__":
data_file = os.path.join(sys.argv[1], 'midi.json')
try:
device_id = int(sys.argv[-1])
except ValueError:
device_id = None
notes = {}
with MIDIInput() as input:
while True:
if input.poll():
midis = input.read(10)
events = pygame.midi.midis2events(midis, input.device_id)
for event in events:
print(event)
if event.status == 144:
note, volume = event.data1, event.data2
if volume > 0:
notes[note] = volume
elif note in notes:
del notes[note]
with open(data_file, 'w') as outfile:
json.dump(notes, outfile)