首页 > 解决方案 > Mido - 如何从不同端口实时获取 midi 数据

问题描述

我创建了 2 个端口作为输入,以从键盘和 midi 表面控制器(具有一堆滑块和旋钮)捕获数据。虽然我不确定如何从两者中获取数据

for msg1 in input_hw:
    if not msg1.type == "clock":
        print(msg1)
    # Play the note if the note has been triggered
    if msg1.type == 'note_on' or msg1.type == 'note_off' and msg1.velocity > 0:
        out.send(msg1)

for msg in input_hw2:
    #avoid to print the clock message
    if not msg.type == "clock":
        print(msg)

第一个 For 循环有效,我在弹奏键盘时打开和关闭 MIDI 音符,它与input_hw端口绑定,但第二个循环永远不会通过。

标签: pythonmido

解决方案


找到了解决方案;您需要将 for 循环包装在 while 循环中,并使用该iter_pending()函数,该函数确实允许 mido 继续并且不会卡在等待第一个循环。

可能有一个更优雅的解决方案,但这是我能够找到的

while True:
    for msg1 in input_hw.iter_pending():
        if not msg1.type == "clock":
            print(msg1)
        # Play the note if the note has been triggered
        if msg1.type == 'note_on' or msg1.type == 'note_off' and msg1.velocity > 0:
            out.send(msg1)

    for msg in input_hw2.iter_pending():
        #avoid to print the clock message
        if not msg.type == "clock":
            print(msg)

推荐阅读