1

我正在编写一个 Python 脚本,其中每次按下一个键,都会播放一个声音。我正在使用 Winsound 模块播放声音,我想要这样的东西:

import winsound

while True:
    if any_key_is_being_pressed: # Replace this with an actual if statement.
        winsound.PlaySound("sound.wav", winsound.SND_ASYNC)

# rest of the script goes here...

但是,我不希望“While True”块在脚本运行时暂停它。我希望它在后台运行并让脚本继续执行,如果这在 Python 中是可能的的话。

也许我在叫错树,不需要一段时间是真的;如果按下任何键盘键时有什么方法可以播放声音,那么请告诉我。

谢谢你。

4

2 回答 2

0

使用 pynput.keyboard 模块,

from pynput.keyboard import Key, Listener
import winsound

def on_press(key):
    winsound.PlaySound("sound.wav", winsound.SND_ASYNC)

def on_release(key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

# Collect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()
于 2020-06-03T12:01:45.723 回答
0

如果您希望您的代码在任何按键上执行,那么以下代码将完美运行

import msvcrt, winsound

while True:
    if msvcrt.kbhit():   #Checks if any key is pressed
         winsound.PlaySound("sound.wav", winsound.SND_ASYNC) 

如果您想在某个按键上执行您的代码,那么此代码将运行良好

import keyboard  
""" using module keyboard please install before using this module 
    pip install keyboard
"""
while True:  
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('a'):  # if key 'a' is pressed 
             winsound.PlaySound("sound.wav", winsound.SND_ASYNC)
            break  # finishing the loop
    except:
        break
于 2020-06-03T12:10:18.097 回答