I have taken code from online which listens for the user's keystrokes, in this case the two keys that will activate the code is "e" and ".". Both are linked to a dictionary which defines each with an mp3 file (consider it a shortcut). And then plays the mp3 file using playsound.
My problem is that when a sound is played, it does not allow me to press any other keys, I would like it that it acts as a usual soundboard in which I can repeatidly press the same button and the audio would play from the beginning again.
from time import sleep
import keyboard as kb
import playsound as ps
keymap_count = None
is_playing = False
def do_for_key(pressed_key, keymap):
global keymap_count
global is_playing
if keymap_count is None:
keymap_count = dict(zip(keymap, [0]*len(keymap)))
for key in keymap:
if kb.is_pressed(key) and is_playing == False:
print(f"\n{key}: {keymap[key]}")
ps.playsound(keymap[pressed_key])
is_playing = True
elif kb.is_pressed(key) and is_playing == True:
is_playing = False
ps.terminate()
def soundboard(keymap):
for key in keymap:
kb.on_press_key(key, lambda key_event: do_for_key(key_event.name, keymap))
while True:
try:
sleep(0.05)
except KeyboardInterrupt:
break
if __name__ == "__main__":
example_keymap = {
'e': "sound.mp3",
'.': "smooth.mp3"
}
soundboard(example_keymap)
Here is my code.