欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

对Python 语音识别框架详解

程序员文章站 2022-05-27 21:47:42
如下所示: from win32com.client import constants import os import win32com.client i...

如下所示:

from win32com.client import constants
import os
import win32com.client
import pythoncom
 
speaker = win32com.client.dispatch("sapi.spvoice")
 
 
class speechrecognition:
 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) for word in wordstoadd]
  self.grammar.rules.commit()
  self.grammar.cmdsetrulestate("wordsrule", 1)
  self.grammar.rules.commit()
  self.eventhandler = contextevents(self.context)
  self.say("started successfully")
 def say(self, phrase):
  self.speaker.speak(phrase)
class contextevents(win32com.client.getevents("sapi.spsharedrecocontext")):
 def onrecognition(self, streamnumber, streamposition, recognitiontype, result):
  newresult = win32com.client.dispatch(result)
  print("小伙子你在说 ", newresult.phraseinfo.gettext())
  speechstr=newresult.phraseinfo.gettext()
  if speechstr=="张三":
   speaker.speak("zhaodahai love fengjie")
  elif speechstr=="你好":
   speaker.speak("hello world")
  elif speechstr=="国庆快乐":
   speaker.speak("happy nationalday")
  elif speechstr=="新年快乐":
   speaker.speak("happy new year")
  elif speechstr=="李四":
   speaker.speak("a beauty baby")
  elif speechstr=="王五":
   speaker.speak("a little boy")
  elif speechstr=="赵六":
   speaker.speak("a boy can coding")
  else:
   pass
 
if __name__ == '__main__':
 
 speaker.speak("语音识别开启")
 wordstoadd = ["张三",
     "你好",
     "国庆快乐",
     "新年快乐",
     "李四",
     "王五",
     "赵六",]
 speechreco = speechrecognition(wordstoadd)
 while true:
  pythoncom.pumpwaitingmessages()
 

以上这篇对python 语音识别框架详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。