1

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.

rdas
  • 20,604
  • 6
  • 33
  • 46
ShakeyGames
  • 277
  • 1
  • 3
  • 11
  • Take a look at [this](https://stackoverflow.com/questions/24072790/detect-key-press-in-python). I think it might be useful for you. – prashantpiyush Jun 03 '20 at 11:59

2 Answers2

1

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()
Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
  • 1
    Thank you so much, it works perfectly, but it pauses the script, so it doesn't run anything after it. Is there a way for the listener to keep running but not pause the script? – ShakeyGames Jun 03 '20 at 12:46
  • Yes, works perfectly! But what about when you hold a key down!? It repeats the sound in loop while holding the key down! Is there a way to stop that from happening? I mean, play the sound once until the key is released. – edif Nov 10 '22 at 15:59
0

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
Khan Asfi Reza
  • 566
  • 5
  • 28