需要安装pyaudio库。
直接上代码:
import pyaudio import wave AUDIO_FILE = '录音文件.wav' def get_audio(filepath, audio_time): #录音 CHUNK = 256 FORMAT = pyaudio.paInt16 CHANNELS = 1 # 声道数 RATE = 16000 # 采样率 RECORD_SECONDS = audio_time WAVE_OUTPUT_FILENAME = "录音文件.wav" p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print("*"*10, "开始录音:请在%d秒内输入语音"% (audio_time)) frames = [] for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) print("*"*10, "录音结束 ") 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() if __name__ == '__main__': get_audio(AUDIO_FILE,10)