Skip to content

Commit cf705cf

Browse files
authored
Create keyboard_sound_pygame.py
1 parent 86cff94 commit cf705cf

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

script/keyboard_sound_pygame.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import os
2+
import sys
3+
import random
4+
try:
5+
import pygame
6+
pygame.init()
7+
pygame.mixer.init()
8+
except:
9+
sys.exit()
10+
11+
def resource_path(relative):
12+
if hasattr(sys, "_MEIPASS"):
13+
absolute_path = os.path.join(sys._MEIPASS, relative)
14+
else:
15+
absolute_path = os.path.join(relative)
16+
return absolute_path
17+
18+
class KeyBoardSound_pygame:
19+
def __init__(self):
20+
self.sounds = os.listdir('sound')
21+
self.keyboard_sound_program()
22+
23+
def play_sound(self):
24+
sound_file = 'sound/' + self.sounds[random.randint(0, len(self.sounds)-1)]
25+
pygame.mixer.music.load(resource_path(sound_file))
26+
pygame.mixer.music.play()
27+
28+
def keyboard_sound_program(self):
29+
screen = pygame.display.set_mode((640, 480))
30+
while 1:
31+
for event in pygame.event.get():
32+
if event.type == pygame.QUIT:
33+
pygame.quit()
34+
sys.exit()
35+
if event.type == pygame.KEYDOWN:
36+
print(event)
37+
self.play_sound()
38+
39+
if __name__ == '__main__':
40+
keyboard_sound = KeyBoardSound_pygame()

0 commit comments

Comments
 (0)