I'm making a small script which plays audio file when you press a key on you'r keyboard. Now after switching multiple libraries I landed on pyglet + pynput combo. The script is working fine, but the audio plays in infinite loop which isn't desired, and the audio gets stacked. I coudln't find anything about this, any ideas?
*ffmpeg is installed
Here is the code;
import string, random, pyglet
from pynput.keyboard import Key, Listener
pyglet.options['search_local_libs'] = True
spec_keys = ['Key.caps_lock', 'Key.shift', 'Key.delete', 'Key.backspace', 'Key.enter', 'Key.up', 'Key.left', 'Key.down', 'Key.right']
caps = ['Key.caps_lock', 'Key.shift']
delete = ['Key.delete', 'Key.backspace']
move = ['Key.up', 'Key.left', 'Key.down', 'Key.right']
ks1 = pyglet.media.load('key-press-1.mp3', streaming=False)
ks2 = pyglet.media.load('key-press-2.mp3', streaming=False)
ks3 = pyglet.media.load('key-press-3.mp3', streaming=False)
ks4 = pyglet.media.load('key-press-4.mp3', streaming=False)
ks_list = [ks1, ks2, ks3, ks4]
k_caps = pyglet.media.load('key-caps.mp3', streaming=False)
k_conf = pyglet.media.load('key-confirm.mp3', streaming=False)
k_del = pyglet.media.load('key-delete.mp3', streaming=False)
k_move = pyglet.media.load('key-movement.mp3', streaming=False)
def on_press(key):
x = str(key)
x = x.strip("'")
if x not in spec_keys:
ks_sound = random.choice(ks_list)
ks_sound.play()
elif x in caps:
k_caps.play()
elif x in delete:
k_del.play()
elif x in move:
k_move.play()
elif x == 'Key.enter':
k_conf.play()
with Listener(on_press = on_press) as listener:
listener.join()
pyglet.app.run()
使用 OpenAL 解决了它
pyglet.options['audio'] = ('openal', 'pulse', 'directsound', 'silent')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.