使用Python进行录音,你可以使用`pyaudio`库。以下是使用`pyaudio`进行录音的基本步骤和示例代码:
步骤
1. 安装`pyaudio`库。
3. 打开一个音频流,设置输入参数。
4. 读取音频数据并保存到WAV文件。
5. 关闭音频流。
示例代码
import pyaudioimport wavedef record_audio(file_name, duration):chunk = 1024 每次读取的音频帧大小format = pyaudio.paInt16 音频格式channels = 1 声道数rate = 44100 采样率record_seconds = duration 录制时长output_file = file_name 输出文件名创建PyAudio对象p = pyaudio.PyAudio()打开音频流stream = p.open(format=format,channels=channels,rate=rate,input=True,frames_per_buffer=chunk)print("开始录制音频...")frames = []录制音频for i in range(int(rate / chunk * record_seconds)):data = stream.read(chunk)frames.append(data)print("录制音频结束.")关闭音频流stream.stop_stream()stream.close()保存为WAV文件wf = wave.open(output_file, 'wb')wf.setnchannels(channels)wf.setsampwidth(p.get_sample_size(format))wf.setframerate(rate)wf.writeframes(b''.join(frames))wf.close()调用函数,录制5秒的音频并保存为"recording.wav"record_audio("recording.wav", 5)
注意事项
确保在开始录音前已经安装了`pyaudio`库。
根据需要调整`chunk`大小、`format`、`channels`和`rate`参数。
录制结束后,记得关闭音频流并保存WAV文件。

