写一段语音识别python代码
时间: 2024-09-19 08:13:33 浏览: 74
在Python中,我们可以使用` SpeechRecognition`库来实现基本的语音识别功能。以下是一个简单的例子,它会通过麦克风录制音频并尝试将其转换为文本:
```python
# 首先安装必要的库(如果没有安装)
!pip install SpeechRecognition pocketsphinx
from speech_recognition import Recognizer
from pydub import AudioSegment
import os
# 初始化Recognizer
recognizer = Recognizer()
# 检查麦克风权限
if not recognizer.is_recognizing_audio():
# 使用默认录音设备录音
with AudioSegment.from_wav(os.environ["MICROPHONE"]).channels_first().resample(16000) as audio:
print("Please speak now...")
audio.export("temp.wav", format="wav")
# 将音频文件转为语音识别
with open("temp.wav", "rb") as source:
audio_data = source.read()
try:
text = recognizer.recognize_google(audio_data, language="zh-CN")
print(f"You said: {text}")
except Exception as e:
print(f"Error occurred: {e}")
```
这段代码首先检查麦克风权限,然后录制一段音频,并尝试使用Google语音识别API将它转化为文字。注意,你需要在运行此代码前设置环境变量`MICROPHONE`指向你的麦克风设备。
阅读全文