简体   繁体   English

如何在 Python 中模拟钢琴键?

[英]How to emulate a piano key in Python?

I wrote a Python script that sends MIDI data to a another program on my laptop if the a key is pressed on the keyboard which triggers a piano sound.我写了一个 Python 脚本,如果按下键盘上的a键触发钢琴声音,它会将 MIDI 数据发送到我笔记本电脑上的另一个程序。

My problem is the following: On a real piano if I press a key and I keep it pressed, a single note sounds with sustain.我的问题如下:在真正的钢琴上,如果我按下一个键并按住它,单个音符会发出延音。 But if I press the a key on my keyboard while running the script, instead of behaving as a real acoustic piano, the note sounds a bunch of times while the key is pressed.但是,如果我在运行脚本时按下键盘上的a键,而不是像真正的原声钢琴那样运行,按下该键时音符会响起多次。 I suppose this issue could be resolved with some if and loop logic.我想这个问题可以通过一些 if 和 loop 逻辑来解决。 I just don't know how.我只是不知道如何。

Could anyone suggest me anything?有人可以建议我什么吗?

My script is this:我的脚本是这样的:

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)

You need a variable that remembers if the key is pressed:您需要一个变量来记住按键是否被按下:

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

You could use a dict to save information about more than one key.您可以使用dict来保存有关多个键的信息。

After MaxiMouse's great help, I could accomplish what I wanted.经过MaxiMouse的大力帮助,我可以完成我想要的。 I used the suggestion of MaxiMouse and with a bit of variations I could get the script to work.我使用了 MaxiMouse 的建议,通过一些变化,我可以让脚本工作。

I'll leave the working code here.我将在这里留下工作代码。

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM