python声音采集
时间: 2023-11-22 10:50:22 浏览: 129
test_2.zip_Python音频数据_python 声音采集_python信号_python声卡采集_信号 python
5星 · 资源好评率100%
以下是使用Python进行声音采集的示例代码:
```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()
# 打开音频流
stream = audio.open(format=FORMAT, channels=CHANNELS,
rate=RATE, input=True,
frames_per_buffer=CHUNK)
print("开始录音......")
# 录音缓存
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()
# 写入录音文件
with wave.open(WAVE_OUTPUT_FILENAME, 'wb') as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(audio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
print("录音文件已保存:", WAVE_OUTPUT_FILENAME)
```
这段代码使用PyAudio库进行声音采集,将采集到的音频数据写入WAV文件中。你可以根据自己的需求修改参数,例如录音时长、采样率等。
阅读全文