python麦克风采集的语音输入
时间: 2024-10-03 16:00:20 浏览: 32
在Python中,你可以使用`pyaudio`库或者`sounddevice`库来从麦克风采集音频输入,特别是语音。以下是简单的步骤:
**使用pyaudio库**:
```python
import pyaudio
import wave
# 初始化 PyAudio 对象
p = pyaudio.PyAudio()
# 设置录音参数
chunk_size = 1024
sample_rate = 44100
record_secs = 5 # 录音秒数
# 创建流对象并开始录音
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=sample_rate,
input=True,
frames_per_buffer=chunk_size)
audio_data = []
for _ in range(int(sample_rate / chunk_size * record_secs)):
data = stream.read(chunk_size)
audio_data.append(data)
# 结束录音并关闭流
stream.stop_stream()
stream.close()
p.terminate()
# 将数据保存到WAV文件
wave_file = wave.open("recording.wav", "wb")
wave_file.setnchannels(1)
wave_file.setsampwidth(p.get_sample_size(pyaudio.paInt16))
wave_file.setframerate(sample_rate)
wave_file.writeframes(b''.join(audio_data))
wave_file.close()
```
**使用sounddevice库**:
```python
from sounddevice import record, play
duration = 5 # 录音秒数
myRecording = record(samplerate=44100, channels=1, duration=duration)
play(myRecording) # 如果需要回放录制的声音
```
这两个库都提供了一种简单的方式来处理音频输入,并允许你进一步处理音频数据,如转为文本(通过语音识别API)。
阅读全文