66 import playsound
77 import keyboard
88except :
9- sys .exit ()
9+ # if can not import main module it will exit
10+ sys .exit ()
1011
1112# for packing program
13+ # if you need to pack file in the program
14+ # I recommend this func to redirect your path to right path
1215def resource_path (relative ):
1316 if hasattr (sys , "_MEIPASS" ):
1417 absolute_path = os .path .join (sys ._MEIPASS , relative )
@@ -17,22 +20,55 @@ def resource_path(relative):
1720 return absolute_path
1821
1922class KeyBoardSound :
20- def __init__ (self , mode = 'random_sound' ):
21- self .mode = mode
23+ def __init__ (self , path = 'setting.txt' ):
2224 self .sound_list = os .listdir ('sound' )
2325 if len (self .sound_list )< 0 :
24- sys .exit ()
26+ sys .exit ()
27+ # record pressed key for play sound
28+ self .pressed_key = None
29+ # load setting path can be init at the first
30+ self .setting_path = path
31+ self .setting = dict ()
32+ # this func will load setting and init mode
33+ self .load_setting ()
34+
2535 keyboard .hook (self .keyboard_sound_program )
26- # stop when press 'esc'
36+ # stop when press 'esc' or it will repeated upon line
2737 keyboard .wait ('esc' )
38+
39+ def load_setting (self ):
40+ try :
41+ with open (self .setting_path ) as f :
42+ for line in f .readlines ():
43+ line = line .replace ('\n ' , '' ).replace ('\r ' ,'' )
44+ if 'mode=' in line :
45+ self .mode = line .split ('=' )[- 1 ]
46+ elif ':' in line :
47+ line = line .split (':' )
48+ self .setting [line [0 ]]= line [- 1 ]
49+ except :
50+ print ('can not read setting!' )
51+ self .mode = 'random'
52+
53+
2854 def play_sound (self ):
29- sound_file = 'sound/' + self .sound_list [random .randint (0 , len (self .sound_list )- 1 )]
30- playsound .playsound (sound_file )
55+ if self .mode == 'random' :
56+ # random mode will randomly play any sound in sound folder
57+ sound_file = 'sound/' + self .sound_list [random .randint (0 , len (self .sound_list )- 1 )]
58+ playsound .playsound (sound_file )
59+ elif self .mode == 'custom' :
60+ # custom mode
61+ try :
62+ sound_file = 'sound/' + self .setting [self .pressed_key ]
63+ playsound .playsound (sound_file )
64+ except :
65+ pass
3166
3267 def keyboard_sound_program (self , event ):
3368 if event .event_type == 'down' :
34- print (event )
35- # print(event.name)
69+ # set key to the pressed key
70+ self .pressed_key = event .name
71+ # using thread to play multiple sound at same time
3672 threading .Thread (target = self .play_sound ).start ()
3773
3874if __name__ == '__main__' :
0 commit comments