使用Python做语音识别
时间: 2024-03-28 15:31:42 浏览: 117
使用Python进行语音识别可以使用第三方库SpeechRecognition。下面是一个简单的例子:
```python
import speech_recognition as sr
# 创建一个Recognizer对象
r = sr.Recognizer()
# 打开麦克风并开始录音
with sr.Microphone() as source:
print("请开始说话:")
audio = r.listen(source)
# 使用Google Web Speech API进行语音识别
try:
print("Google Speech Recognition thinks you said: " + r.recognize_google(audio, language='zh-CN'))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
```
上述代码使用了Google Web Speech API进行语音识别,需要联网才能使用。如果想要使用离线语音识别,可以使用PocketSphinx库。下面是一个使用PocketSphinx进行离线语音识别的例子:
```python
import speech_recognition as sr
# 创建一个Recognizer对象
r = sr.Recognizer()
# 打开麦克风并开始录音
with sr.Microphone() as source:
print("请开始说话:")
audio = r.listen(source)
# 使用PocketSphinx进行语音识别
try:
print("PocketSphinx thinks you said: " + r.recognize_sphinx(audio, language='zh-CN'))
except sr.UnknownValueError:
print("PocketSphinx could not understand audio")
except sr.RequestError as e:
print("Could not request results from PocketSphinx service; {0}".format(e))
```
阅读全文