用python实现如下功能:输入1后,开始录制一段五秒的音频,并保存下来
时间: 2023-06-02 11:02:24 浏览: 97
使用Python实现此功能需要用到PyAudio库。您可以使用以下代码实现:
```python
import pyaudio
import wave
# 设置参数
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
# 初始化PyAudio
audio = pyaudio.PyAudio()
# 开始录制
print("开始录制音频...")
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)
frames = []
for i in range(0, int(RATE/CHUNK*RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("录制完成!")
# 停止录制
stream.stop_stream()
stream.close()
audio.terminate()
# 保存录音文件
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(audio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
print("音频已保存为:", WAVE_OUTPUT_FILENAME)
```
运行该代码,将会开始录制五秒钟的音频,然后保存为名为output.wav的文件。
阅读全文