对Python 语音识别框架详解

yipeiwu_com6年前Python基础

如下所示:

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 语音识别框架详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

web.py获取上传文件名的正确方法

直接切入主题,从HTML页面上传文件,Python接收处理。但其中发现有些小问题,把它写出来,算是积累吧! HTML页面代码: 复制代码 代码如下: <form action="/...

Python实现将HTML转成PDF的方法分析

Python实现将HTML转成PDF的方法分析

本文实例讲述了Python实现将HTML转成PDF的方法。分享给大家供大家参考,具体如下: 主要使用的是wkhtmltopdf的Python封装——pdfkit 安装 1. Instal...

python数据结构之二叉树的建立实例

先建立二叉树节点,有一个data数据域,left,right 两个指针域复制代码 代码如下:# -*- coding: utf - 8 - *-   &nb...

Django 请求Request的具体使用方法

Django 请求Request的具体使用方法

1 URL路径参数 在定义路由URL时,使用正则表达式提取参数的方法从URL中获取请求参数,Django会将提取的参数直接传递到视图的传入参数中。 未命名参数按顺序传递, 如 url...

python基础教程项目三之万能的XML

这个项目的名称与其叫做万能的XML不如叫做自动构建网站,根据一份XML文件,生成对应目录结构的网站,不过只有html还是太过于简单了,如果要是可以连带生成css那就比较强大了。这个有待后...