For a small application, i'm trying to play a sound whenever the user presses a specific key, as close to realtime as is possible to get. It is to be used in a 'morse code' type way, where I simulate the 'beats' from a morse tapper. Therefore I need for the solution to as closely match the timing at which the key is being pressed, and for the output sound to match this timing.
What would be the best way to simulate a morse tapper with a PC keyboard?
This is the code i'm using now, as it's the closest i've got. It seems to lose the timing once a few (but not more than 32) sounds are playing
import keyboard
import pygame as pg
# Sets up the pygame mixer
pg.mixer.init()
pg.init()
#sets the sound to play
bellSound = pg.mixer.Sound("ding2.wav")
#sets the number of sounds to be able to play at once.
pg.mixer.set_num_channels(32)
while True:
print("waiting for keypress")
keyboard.wait('`')
bellSound.play()
I've tried the 'raw_input()' method from here : How do I get realtime keyboard input in Python? but this requires a return key as well.
I've also tried to get pygame.key.get_pressed to work, but it didn't seem to respond in the expected manner.
The issue I'm having could have a number of other issues. I could be running into input lag from the USB keyboard, or lag from the system playing the sound.
Also, I'm not bothered if a current sound is cut off by a new sound. Currently, the sounds will play concurrently, which could also be causing issues. If there is another way of making the sound play on keypress, and restart if the key is pressed again, rather than playing another sound... that might work better, and be more accurate to what i'm trying to simulate.
question is not related to getting input from the keyboard. which is why closure is not appropriate. The issue is getting the input to behave like a morse code tapper, which it currently doesn't