在Python上阅读钢琴笔记 [英] Reading piano notes on Python
问题描述
我想听听端口号,它的Midi输出设备(钢琴)和我的RPi在Debian上运行.我调查了pygame.midi,我设法监听了端口,但是无法以某种方式提取所有的midi信息.请在下面的代码中找到
I'd like to listen to the port having my midi output device (a piano) with my RPi, running on Debian. I've looked into pygame.midi, I managed to listen to the port, but somehow can not extract all midi information. Please find code below [edited code snippet]
已修复,非常感谢!
推荐答案
首先,您需要找出pygame中键盘具有哪个设备ID.我写了这个小函数来找出:
First of all you need to find out which device-id your keyboard has inside pygame. I wrote this little function to find out:
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手册中,您可以了解到该信息元组中的第一个将此设备确定为合适的输入设备. 因此,让我们从一个无限循环中读取一些数据:
From the pygame manual you can learn that the first One inside this info-tuple determines this device as a suitable Input-Device. So let's read some data from it in an endless-loop:
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个项目的列表:
that we have a list of a list with 2 items:
- midi数据列表和
- 时间戳
第二个值是您感兴趣的值.因此,我们将其打印出来作为注释:
The second value is the one you're interested in. So we print it out as a note:
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)
我希望这会有所帮助.这是我的第一个答案,我希望它不会太长. :)
I hope this helped. It's my first answer, I hope it's not too long. :)
这篇关于在Python上阅读钢琴笔记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!