Skip to content

Commit 86cff94

Browse files
authored
Create keyboard_sound.py
1 parent 7a00b69 commit 86cff94

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

script/keyboard_sound.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import os
2+
import random
3+
import threading
4+
import sys
5+
try:
6+
import playsound
7+
import keyboard
8+
except:
9+
sys.exit()
10+
11+
# for packing program
12+
def resource_path(relative):
13+
if hasattr(sys, "_MEIPASS"):
14+
absolute_path = os.path.join(sys._MEIPASS, relative)
15+
else:
16+
absolute_path = os.path.join(relative)
17+
return absolute_path
18+
19+
class KeyBoardSound:
20+
def __init__(self, mode='random_sound'):
21+
self.mode = mode
22+
self.sound_list = os.listdir('sound')
23+
keyboard.hook(self.keyboard_sound_program)
24+
# stop when press 'esc'
25+
keyboard.wait('esc')
26+
def play_sound(self):
27+
sound_file = 'sound/' + self.sound_list[random.randint(0, len(self.sound_list)-1)]
28+
playsound.playsound(resource_path(sound_file))
29+
30+
def keyboard_sound_program(self, event):
31+
if event.event_type == 'down':
32+
print(event)
33+
threading.Thread(target=self.play_sound).start()
34+
35+
if __name__ == '__main__':
36+
key_board_sound = KeyBoardSound()

0 commit comments

Comments
 (0)