使用python代码写一个语音识别代码
时间: 2024-02-01 22:02:35 浏览: 83
要编写一个语音识别代码,需要使用语音识别API,这里以Google的Speech Recognition API为例。以下是使用Python编写的基本代码:
1. 安装SpeechRecognition库
```python
pip install SpeechRecognition
```
2. 导入SpeechRecognition库
```python
import speech_recognition as sr
```
3. 创建Recognizer实例
```python
r = sr.Recognizer()
```
4. 使用麦克风录音
```python
with sr.Microphone() as source:
print("请开始说话:")
audio = r.listen(source)
```
5. 将录音转换为文本
```python
try:
text = r.recognize_google(audio, language='zh-CN')
print("您说的是:" + text)
except Exception as e:
print("抱歉,无法识别。")
```
完整代码如下:
```python
import speech_recognition as sr
# 创建Recognizer实例
r = sr.Recognizer()
# 使用麦克风录音
with sr.Microphone() as source:
print("请开始说话:")
audio = r.listen(source)
# 将录音转换为文本
try:
text = r.recognize_google(audio, language='zh-CN')
print("您说的是:" + text)
except Exception as e:
print("抱歉,无法识别。")
```
注意:使用语音识别API需要联网,而且准确率不一定高,可能会出现无法识别的情况。
阅读全文