Mido - 如何从不同端口实时获取 midi 数据

4 python mido

我创建了 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)
Run Code Online (Sandbox Code Playgroud)

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

小智 5

找到了解决办法;您需要将 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)
Run Code Online (Sandbox Code Playgroud)