扣丁学堂Python开发之调用语音模块时报错及解决方法
2018-03-09 11:45:57
3346浏览
python调用语音模块时,遇见TypeError:NoneTypetakesnoarguments这种错误类型该如何解决
下面是一个用python实现语音识别的例子:
fromwin32com.clientimportconstants
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())
s=newResult.PhraseInfo.GetText()
ifs=="生日快乐":
speaker.Speak("HappyBirthday")
else:
pass
if__name__=='__main__':
speaker.Speak("语音识别开启")
wordsToAdd=["生日快乐"]
speechReco=SpeechRecognition(wordsToAdd)
whileTrue:
pythoncom.PumpWaitingMessages()
报错:
classContextEvents(win32com.client.getevents("SAPI.SpSharedRecoContext")):
TypeError:NoneTypetakesnoarguments
报错的原因是:不能调用语音开发包
解决方法:(如果你已经安装了pyWin32,它也安装了PythonWin)
1.在python36目录中找到pythonwin文件夹
python36/lib/site-packages/pythonwin
2.在pythonwin文件夹下找到Pythonwin文件
3.双击Pythonwin运行
4.然后选择工具tools/commakepyutility
5.然后选择MicrosoftSpeechObjectLibrary5.4,点击OK键
6。运行结果
好了,问题解决,现在可以执行代码了,执行结果:(弹出语音识别设置)
OK,开始你的语音识别之旅吧,最后想要了解更多关于Python发展前景趋势,请关注扣丁学堂python培训官网、微信等平台,扣丁学堂IT职业在线学习教育平台为您提供最新的Python视频教程系统,通过千锋扣丁学堂金牌讲师在线录制的Python视频教程课程,让你快速掌握Python从入门到精通开发实战技能。扣丁学堂Python开发工程师技术交流群:279521237。
【关注微信公众号获取更多学习资料】
标签:
Python视频教程
Python基础教程
Python爬虫
Python培训
Python开发工程师