I am using the pynput and winsound modules to make a program that makes the pc play the sound of the keys and mouse. The problem is that when I press a key and hold it down the key is triggered repeatedly, which causes the sound to play repeatedly in a loop until I release the key.
I followed this solution to create the program: Play Sound whenever key is pressed in Python
Then as I wanted to play the mouse sound as well, I found this article: How to Use pynput's Mouse and Keyboard Listener at the Same Time
So, I ended up with this code:
from pynput.mouse import Listener as MouseListener
from pynput.keyboard import Listener as KeyboardListener
import winsound
def on_press(key):
winsound.PlaySound("sound.wav", winsound.SND_ASYNC)
print("Key pressed: {0}".format(key))
def on_release(key):
print("Key released: {0}".format(key))
def on_click(x, y, button, pressed):
if pressed:
winsound.PlaySound("mouse_click.wav", winsound.SND_ASYNC)
print('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
else:
print('Mouse released at ({0}, {1}) with {2}'.format(x, y, button))
keyboard_listener = KeyboardListener(on_press=on_press, on_release=on_release)
mouse_listener = MouseListener(on_click=on_click)
keyboard_listener.start()
mouse_listener.start()
keyboard_listener.join()
mouse_listener.join()
Now, the mouse click does exactly what I want the keyboard to do! It plays the sound once while it is being held until I release it!
I just don't know how to make the keyboard play the sound only once until the key is released, like the mouse!!!