当我按下键盘键时,Windows可以播放声音吗?

时间:2019-10-07 13:12:51

标签: python windows

我发现an application允许您执行此操作,我想知道是否可以使用任何内置程序来完成此操作(我不是说Caps Lock,Num Lock单选按钮,它们的声音可以在控制面板中打开)?可以使用以下代码在python上完成此操作,但是我的winsound.PlaySound不想找到文件,而只是播放错误的系统声音。 answer并没有帮助(通过sys或创建文件夹)。

代码:

import winsound
import keyboard
duration = 250
q = 300
while True:
    try:
        if keyboard.is_pressed('q'):
            winsound.PlaySound('C:\\some.wav',winsound.SND_FILENAME)            
            winsound.Beep(q, duration)#Since PlaySound does not want to search, you have to do it through squeak
    except:
        break

1 个答案:

答案 0 :(得分:0)

几个月前,我在VB.net中发现了类似的内容
因此,我建议您不要使用winsound而是使用simpleaudio软件包。

import simpleaudio as sa

filename = 'myfile.wav'
wave_obj = sa.WaveObject.from_wave_file(filename)
play_obj = wave_obj.play()
play_obj.wait_done()  # Wait until sound has finished playing




from pynput.keyboard import Listener
import simpleaudio as sa


filename = 'music.wav'
wave_obj = sa.WaveObject.from_wave_file(filename)


def on_press(key):
    if key.char == 'q':
        play_obj = wave_obj.play()
        play_obj.wait_done()


with Listener(on_press=on_press) as listener:
    listener.join()