在Python中每当按键被按下时就播放声音

问题描述 投票:1回答:2

我正在写一个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 中是可能的。

也许我找错了方向,不需要 while true;如果有什么方法可以在当 任何 键盘键被按下,那么请告诉我。

谢谢你,我正在写一个Python脚本,每按一次键,就播放一次声音。

python python-3.x winsound
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()

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
© www.soinside.com 2019 - 2024. All rights reserved.