ShakeyGames
ShakeyGames

Reputation: 37

Play Sound whenever key is pressed in Python

I am writing a Python script wherein everytime a key is pressed, a sound is played. I am using the Winsound module to play the sound, and I want something like this:

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...

However, I don't want the "While True" block pausing the script when it is being run. I want it to run in the background and let the script carry on being executed, if this is even possible in Python.

Perhaps I am barking up the wrong tree and don't need a while true; if there is any way to play sound when any keyboard key is pressed, then please tell me.

Thank you.

Upvotes: 1

Views: 3837

Answers (2)

Khan Asfi Reza
Khan Asfi Reza

Reputation: 691

If you want your code to execute on any keypress then the following code will work perfectly

import msvcrt, winsound

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

If you want to execute your code on a certain keypress then this code will work well

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

Upvotes: 0

Roshin Raphel
Roshin Raphel

Reputation: 2709

Use the pynput.keyboard module,

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()

Upvotes: 1

Related Questions