簡體   English   中英

Pynput 鍵盤監聽器自動重復

[英]pynput keyboard Listener autorepeat

我正在嘗試使用pynput來獲取實時鍵盤輸入,但是 on_press 函數在 autorepeat 上被調用。

示例代碼:

#!/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()

如果您運行代碼並按住Q鍵,鍵盤自動重復開始並破壞整個偵聽器。 是否有正確處理原始鍵盤輸入的python輸入模塊?

第二件事是代碼往往會經常使我的 Xorg 崩潰。 我只運行了幾次腳本,Xorg 就宕機了。 我不明白為什么。 Linux 5.5.2-zen1-1-zen x86_64 GNU/LinuxX.Org 1.20.7

第三件事是聲音合成似乎有點滯后。 回調函數的幀數似乎在 400 左右,以每秒 48000 個樣本的速率計算不到 10 毫秒,但實際音頻反饋感覺像是有數百毫秒的延遲。

pygame 有一個很好的密鑰偵聽器,並且很容易構建一個顯示輸出的 GUI 窗口。 它在 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM