-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudio.py
48 lines (42 loc) · 1.52 KB
/
audio.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
import pyaudio
import wave
input_filename = "input.wav" # 麦克风采集的语音输入
input_filepath = "./" # 输入文件的path
in_path = input_filepath + input_filename
def get_audio(filepath):
aa = str(input("是否开始录音? (是/否)"))
if aa == str("是") :
CHUNK = 256
FORMAT = pyaudio.paInt16
CHANNELS = 1 # 声道数
RATE = 11025 # 采样率
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = filepath
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("*"*10, "开始录音:请在5秒内输入语音")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("*"*10, "录音结束\n")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
elif aa == str("否"):
exit()
else:
print("无效输入,请重新选择")
get_audio(in_path)
# 联合上一篇博客代码使用,就注释掉下面,单独使用就不注释
get_audio(in_path)