如何在 Python 中模拟钢琴键?

How to emulate a piano key in Python?

我写了一个 Python 脚本,如果按下键盘上的 a 键会触发钢琴声,它会将 MIDI 数据发送到笔记本电脑上的另一个程序。

我的问题如下:在一架真正的钢琴上,如果我按下一个键并保持按下,单个音符会发出延音。但是,如果我在 运行 脚本的同时按下键盘上的 a 键,而不是像真正的原声钢琴一样,在按下键时音符会响起很多次.我想这个问题可以通过一些 if 和循环逻辑来解决。我就是不知道怎么办。

有人能给我一些建议吗?

我的脚本是这样的:

import time
import rtmidi
import mido
import keyboard

outport = mido.open_output('loopMIDI 1')

while True:
    #Pad A
    if keyboard.is_pressed("a"):
        msg = mido.Message("note_on", note=36, velocity=100, time=10)
        outport.send(msg)
        time.sleep(0.05)
    else:
        msg = mido.Message("note_off", note=36, velocity=100, time=10)
        outport.send(msg)

您需要一个变量来记住按键是否被按下:

import time
import rtmidi
import mido
import keyboard

outport = mido.open_output('loopMIDI 1')
a_pressed = False

while True:
    #Pad A
    if keyboard.is_pressed("a"):
        if a_pressed:
            msg = mido.Message("note_on", note=36, velocity=100, time=10)
            outport.send(msg)
            a_pressed = True
    elif a_pressed:
        msg = mido.Message("note_off", note=36, velocity=100, time=10)
        outport.send(msg)
        a_pressed = False

您可以使用 dict 来保存关于多个密钥的信息。

在MaxiMouse的大力帮助下,我可以完成我想要的。我使用了 MaxiMouse 的建议,并稍加改动就可以使脚本正常工作。

我会在这里留下工作代码。

import time
import rtmidi
import mido
import keyboard

outport = mido.open_output('loopMIDI 1')
a_pressed = False

while True:
    #Pad A
    if keyboard.is_pressed("a") and not a_pressed:
        msg = mido.Message("note_on", note=36, velocity=100, time=10)
        outport.send(msg)
        a_pressed = True
        print("True press")
    elif (keyboard.is_pressed("a") == False):
        msg = mido.Message("note_off", note=36, velocity=100, time=10)
        outport.send(msg)
        a_pressed = False
        print("False press")