导入所需的库
import speech_recognition as sr
创建一个Recognizer对象
r = sr.Recognizer()
使用麦克风录音
with sr.Microphone() as source:
print("Please speak your sentence:")
audio = r.listen(source)
使用Google Speech Recognition进行语音识别
try:
sentence = r.recognize_google(audio)
print("You said: " + sentence)
except sr.UnknownValueError:
print("Sorry, I could not understand what you said.")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
完整代码:
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
print("Please speak your sentence:")
audio = r.listen(source)
try:
sentence = r.recognize_google(audio)
print("You said: " + sentence)
except sr.UnknownValueError:
print("Sorry, I could not understand what you said.")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
需要注意的是,本程序需要联网才能使用Google Speech Recognition进行语音识别。