python - 在按键上播放随机声音 [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
解决方案
你可以做这样的事情来实现你所追求的功能:
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定义添加到主函数中,以不断请求新键,并播放新声音
推荐阅读
- haskell - 倾斜二项式堆能否支持高效合并?
- ios - CIImage 裁剪并渲染到 CVPixelBuffer
- react-native - 将 componentWillReceiveProps 重命名为 componentDidUpdate
- javascript - 用高阶组件包装递归组件
- c++ - g ++详尽的内存使用情况编译自动生成的代码
- r - 在 R 中编写阈值函数
- c# - 在命名空间“System.Data.SqlClient”中找不到类型名称“SqlConnection”
- influxdb-2 - InfluxDB 2.0.2 的配置文件路径在哪里?
- php - Github WebHooks 获取分支详细信息
- python - 动态更改行大小 PySimpleGUI