录音我在python 开发IEnglish (二) 录音讲解过,回顾一下:
"""
本录音程序参考
https://blog.csdn.net/qq_45030271/article/details/106304565
"""
import pyaudio # 下载不对请见https://blog.csdn.net/qq_43280079/article/details/99683448
import wave
class recording:
# 定义录音配置类
CHUNK = 1024 # 最大字节数
FORMAT = pyaudio.paInt16 # 录音格式
CHANNELS = 1 # 通道
RATE = 8000 # 频率
def record(save_path, seconds=60):
"""
录音函数
@save_path: 音频保存路径,wav格式
@seconds: 录音秒数,默认1分钟
"""
p = pyaudio.PyAudio() # 创建PyAudio对象
stream = p.open(
format=recording.FORMAT,
channels=recording.CHANNELS,
rate=recording.RATE,
input=True,
frames_per_buffer=recording.CHUNK
) # 创建音频流
frames = []
for n in range(0, int(recording.RATE / recording.CHUNK * seconds)):
data = stream.read(recording.CHUNK)
frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(save_path, 'wb') # 创建音频文件并打开
wf.setnchannels(recording.CHANNELS)
wf.setsampwidth(p.get_sample_size(recording.FORMAT))
wf.setframerate(recording.RATE)
wf.writeframes(b''.join(frames)) # 写入音频
wf.close() # 关闭音频文件 (这里用try最好)