python代码实现语音转换成文字
时间: 2023-07-23 16:08:11 浏览: 102
要实现语音转换成文字,可以使用Python中的SpeechRecognition库,具体步骤如下:
1. 安装SpeechRecognition库:
```python
pip install SpeechRecognition
```
2. 导入SpeechRecognition库并创建Recognizer对象:
```python
import speech_recognition as sr
r = sr.Recognizer()
```
3. 使用Microphone对象获取音频输入:
```python
with sr.Microphone() as source:
print("请说话:")
audio = r.listen(source)
```
4. 使用Recognizer对象识别音频:
```python
try:
text = r.recognize_google(audio, language='zh-CN')
print("识别结果:%s" % text)
except sr.UnknownValueError:
print("无法识别音频")
except sr.RequestError as e:
print("请求出错:%s" % e)
```
完整代码如下:
```python
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
print("请说话:")
audio = r.listen(source)
try:
text = r.recognize_google(audio, language='zh-CN')
print("识别结果:%s" % text)
except sr.UnknownValueError:
print("无法识别音频")
except sr.RequestError as e:
print("请求出错:%s" % e)
```
注意:在运行代码之前需要确保电脑上已经安装了麦克风设备。
阅读全文