对Python 语音识别框架详解
如下所示:
fromwin32com.clientimportconstants
importos
importwin32com.client
importpythoncom
speaker=win32com.client.Dispatch("SAPI.SPVOICE")
classSpeechRecognition:
def__init__(self,wordsToAdd):
self.speaker=win32com.client.Dispatch("SAPI.SpVoice")
self.listener=win32com.client.Dispatch("SAPI.SpSharedRecognizer")
self.context=self.listener.CreateRecoContext()
self.grammar=self.context.CreateGrammar()
self.grammar.DictationSetState(0)
self.wordsRule=self.grammar.Rules.Add("wordsRule",constants.SRATopLevel+constants.SRADynamic,0)
self.wordsRule.Clear()
[self.wordsRule.InitialState.AddWordTransition(None,word)forwordinwordsToAdd]
self.grammar.Rules.Commit()
self.grammar.CmdSetRuleState("wordsRule",1)
self.grammar.Rules.Commit()
self.eventHandler=ContextEvents(self.context)
self.say("Startedsuccessfully")
defsay(self,phrase):
self.speaker.Speak(phrase)
classContextEvents(win32com.client.getevents("SAPI.SpSharedRecoContext")):
defOnRecognition(self,StreamNumber,StreamPosition,RecognitionType,Result):
newResult=win32com.client.Dispatch(Result)
print("小伙子你在说",newResult.PhraseInfo.GetText())
speechstr=newResult.PhraseInfo.GetText()
ifspeechstr=="张三":
speaker.Speak("zhaodahailovefengjie")
elifspeechstr=="你好":
speaker.Speak("helloworld")
elifspeechstr=="国庆快乐":
speaker.Speak("Happynationalday")
elifspeechstr=="新年快乐":
speaker.Speak("happyNewYear")
elifspeechstr=="李四":
speaker.Speak("abeautybaby")
elifspeechstr=="王五":
speaker.Speak("alittleboy")
elifspeechstr=="赵六":
speaker.Speak("aboycancoding")
else:
pass
if__name__=='__main__':
speaker.Speak("语音识别开启")
wordsToAdd=["张三",
"你好",
"国庆快乐",
"新年快乐",
"李四",
"王五",
"赵六",]
speechReco=SpeechRecognition(wordsToAdd)
whileTrue:
pythoncom.PumpWaitingMessages()
以上这篇对Python语音识别框架详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。