简体   繁体   English

Pynput 键盘监听器自动重复

[英]pynput keyboard Listener autorepeat

I'm trying to use pynput to get realtime keyboard input, but the on_press function gets called on autorepeat.我正在尝试使用pynput来获取实时键盘输入,但是 on_press 函数在 autorepeat 上被调用。

example code:示例代码:

#!/usr/bin/env python3

import sys

import numpy as np
import sounddevice as sd

from pynput import keyboard

frequency = []

def on_press(key):
    global frequency
    try:
        print(key.vk)
        if key.char == "q":
            frequency.append(440)
        elif key.char == "w":
            frequency.append(880)
    except AttributeError:
        pass

def on_release(key):
    global frequency
    if key == keyboard.Key.esc:
        # Stop listener
        print("Press Enter")
        return False
    elif key.char == "q":
        frequency.remove(440)
    elif key.char == "w":
        frequency.remove(880)

listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release,
    suppress = True)
listener.start()

start_idx = 0

def callback(outdata, frames, time, status):
    if status:
        print(status, file=sys.stderr)
    print(frames)
    global start_idx
    t = (start_idx + np.arange(frames)) / 48000
    t = t.reshape(-1, 1)
    outdata[:] = 0 * t
    if len(frequency) > 0:
        print("Playing")
    for freq in frequency:
        outdata[:] = outdata[:] + 0.2 * np.sin(2 * np.pi * freq * t)

    start_idx += frames

try:
    with sd.OutputStream(channels=1, callback=callback,
            samplerate=48000):
        input()
        listener.stop()
except Exception as e:
    print("Exception")
    listener.stop()
    exit()

If you run the code and press and hold the Q key, the keyboard autorepeat kicks in and ruins the whole listener.如果您运行代码并按住Q键,键盘自动重复开始并破坏整个侦听器。 Is there a python input module which handles raw keyboard input properly?是否有正确处理原始键盘输入的python输入模块?

The second thing is that the code tends to crash my Xorg quite regularly.第二件事是代码往往会经常使我的 Xorg 崩溃。 I just run the script a few times and the Xorg goes down.我只运行了几次脚本,Xorg 就宕机了。 And I can't figure out why.我不明白为什么。 Linux 5.5.2-zen1-1-zen x86_64 GNU/Linux , X.Org 1.20.7 . Linux 5.5.2-zen1-1-zen x86_64 GNU/LinuxX.Org 1.20.7

The third thing is that the sound synthesis seems to lag quite a bit.第三件事是声音合成似乎有点滞后。 The number of frames to the callback function seems to hang around 400, which at the rate of 48000 samples per second is less then 10 milliseconds, but the actual audio feedback feels like on hundreds of milliseconds delay.回调函数的帧数似乎在 400 左右,以每秒 48000 个样本的速率计算不到 10 毫秒,但实际音频反馈感觉像是有数百毫秒的延迟。

pygame has a good keylistener and is easy to build a GUI window that displays output. pygame 有一个很好的密钥侦听器,并且很容易构建一个显示输出的 GUI 窗口。 It also works well in Linux:它在 Linux 中也运行良好:

import pygame

def main_loop():
    #code
    loopExit = False
    while not loopExit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                loopExit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    #code

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_q:
                    #code

https://www.pygame.org/docs/ref/key.html https://www.pygame.org/docs/ref/key.html

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

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