首页 > 解决方案 > 在按键上播放随机声音 [Python]

问题描述

我决定编写一个小脚本,它会在按键上播放随机声音。

这是代码:

import os
import keyboard, string, random
from playsound import playsound

path = "C:\\Users\\vilem\\Documents\\My_Stuff\\Py_Projects\\Temp\\keypress" #path to sound files

letter = string.ascii_letters #gets list of lover and uper case letters
digit = string.digits #gets list of numbers

while True:
    mp3Select = random.choice(os.listdir(path)) #selects random sound
    keypress = str(path + "\\" + mp3Select) #gets the path to the random sound

def keyboardPress():
    if keyboard.is_pressed(letter): #checks if letter was pressed
        playsound(keypress) #plays random sound
    elif keyboard.is_pressed(digit): #checks if digit was pressed
        playsound(keypress) #plays random sound

def main():
    while True:
        try:
            keyboardPress()
        except:
            pass

main()

现在,问题是我没有得到任何输出并且没有错误。我从 cmd 运行脚本,即使我让它打印一些变量,就像letter它总是卡住一样,当我用“Ctrl + C”停止它时,它会给我这个错误:

Traceback (most recent call last):
  File "C:\Users\vilem\Documents\My_Stuff\Py_Projects\Temp\typing.py", line 13, in <module>
    mp3Select = random.choice(os.listdir(path))
KeyboardInterrupt

标签: pythonpython-3.x

解决方案


你可以做这样的事情来实现你所追求的功能:

import os
import keyboard, string, random
from playsound import playsound
path = "C:\\Users\\vilem\\Documents\\My_Stuff\\Py_Projects\\Temp\\keypress" #path to sound files
letter = string.ascii_letters #gets list of lover and uper case letters
digit = string.digits #gets list of numbers

mp3Select = random.choice(os.listdir(path)) #selects random sound
keypress = str(path + "\\" + mp3Select) #gets the path to the random sound

pressedKey = input('Press any key then ENTER')

def keyboardPress():
    if pressedKey in letter or digit:
        playsound(keypress)

def main():
        keyboardPress()

main()

如果需要,您可以在循环中将pressedKey和keypress定义添加到主函数中,以不断请求新键,并播放新声音


推荐阅读