forked from KikiLetGo/MyPiano
-
Notifications
You must be signed in to change notification settings - Fork 0
/
piano.py
128 lines (98 loc) · 2.38 KB
/
piano.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#!/usr/bin/python
# encoding:utf-8
import pyaudio
import wave
import threading
import time
import pygame
import sys
import os
pygame.init()
p = pyaudio.PyAudio()
screen = pygame.display.set_mode((500, 304))
pygame.display.set_caption('My-Piano') # 设置窗口标题
background=pygame.image.load(r".//music.png") #设置窗口背景
screen.blit(background,(0,0)) #对齐的坐标
pygame.display.update() #显示内容
pressDict={"1":False,"2":False,"3":False}
keyDict={
pygame.K_1:"c",
pygame.K_2:"d",
pygame.K_3:"e",
pygame.K_4:"f",
pygame.K_5:"g",
pygame.K_6:"a",
pygame.K_7:"b",
pygame.K_8:"c1",
pygame.K_9:"d1",
pygame.K_0:"e1",
pygame.K_MINUS:"f1",
pygame.K_EQUALS:'g1',
pygame.K_q:'a1',
pygame.K_w:'b1',
pygame.K_e:'c2',
pygame.K_r:'d2',
pygame.K_t:'e2',
pygame.K_y:'f2',
pygame.K_u:'g2',
pygame.K_i:'a2',
pygame.K_o:'b2',
pygame.K_p:'c3',
pygame.K_a:'d3',
pygame.K_s:'e3',
pygame.K_d:'f3',
pygame.K_f:'g3',
pygame.K_g:'a3',
pygame.K_h:'b3',
pygame.K_j:'c4',
pygame.K_k:'d4',
pygame.K_l:'e4',
pygame.K_z:'f4',
pygame.K_x:'g4',
pygame.K_c:'a4',
pygame.K_v:'b4',
pygame.K_b:'c5'
}
def play(path,key):
CHUNK = 1024
# 从目录中读取语音
wf = wave.open(path, 'rb')
# read data
data = wf.readframes(CHUNK)
# 创建播放器
global p
# 获得语音文件的各个参数
FORMAT = p.get_format_from_width(wf.getsampwidth())
CHANNELS = wf.getnchannels()
RATE = wf.getframerate()
print(keyDict[key],end=' ')
sys.stdout.flush()
# 打开音频流, output=True表示音频输出
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
frames_per_buffer=CHUNK,
output=True)
# play stream (3) 按照1024的块读取音频数据到音频流,并播放
while len(data) > 0:
stream.write(data)
data = wf.readframes(CHUNK)
# if not pressDict[key]:
# break
while True:
time.sleep(0.01)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
key = event.key
if(key == pygame.K_ESCAPE):
pygame.quit()
elif key in keyDict.keys():
fileName = "./audios/"+str(keyDict[key])+".wav"
if os.path.exists(fileName):
threading.Thread(target=play, args=(fileName,key)).start()
elif event.type == pygame.KEYUP:
#time.sleep(0.5)
key = event.key
pressDict[key]=False