我想用我的 RPi 在 Debian 上运行我的 midi 输出设备(钢琴)来听端口。我查看了 pygame.midi,我设法监听了端口,但不知何故无法提取所有 midi 信息。请在下面找到代码 [编辑后的代码片段]
编辑:已修复,非常感谢!
最佳答案
首先你需要找出你的键盘在pygame中有哪个设备ID。我写了这个小函数来找出答案:
import pygame.midi
def print_devices():
for n in range(pygame.midi.get_count()):
print (n,pygame.midi.get_device_info(n))
if __name__ == '__main__':
pygame.midi.init()
print_devices()
看起来像这样:
(0, ('MMSystem', 'Microsoft MIDI Mapper', 0, 1, 0))
(1, ('MMSystem', '6- Saffire 6USB', 1, 0, 0))
(2, ('MMSystem', 'MK-249C USB MIDI keyboard', 1, 0, 0))
(3, ('MMSystem', 'Microsoft GS Wavetable Synth', 0, 1, 0))
从 pygame 手册中,您可以了解到此信息元组中的第一个 One 将此设备确定为合适的输入设备。 因此,让我们在无限循环中从中读取一些数据:
def readInput(input_device):
while True:
if input_device.poll():
event = input_device.read(1)
print (event)
if __name__ == '__main__':
pygame.midi.init()
my_input = pygame.midi.Input(2) #only in my case the id is 2
readInput(my_input)
这表明:
[[[144, 24, 120, 0], 1321]]
我们有一个包含 2 个项目的列表:
- midi 数据列表和
- 时间戳
第二个值是您感兴趣的值。因此我们将其作为注释打印出来:
def number_to_note(number):
notes = ['c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#', 'a', 'a#', 'b']
return notes[number%12]
def readInput(input_device):
while True:
if input_device.poll():
event = input_device.read(1)[0]
data = event[0]
timestamp = event[1]
note_number = data[1]
velocity = data[2]
print (number_to_note(note_number), velocity)
希望对您有所帮助。这是我的第一个答案,我希望它不会太长。 :)
关于python - 在 Python 上阅读钢琴音符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15768066/