对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设计】。

相关文章

Python读取Excel的方法实例分析

本文实例讲述了Python读取Excel的方法。分享给大家供大家参考。具体如下: 今天需要从一个Excel文档(.xls)中导数据到数据库的某表,开始是手工一行行输的。后来想不能一直这样...

python实现的文件夹清理程序分享

使用: 复制代码 代码如下: foldercleanup.py -d 10 -k c:\test\keepfile.txt c:\test 表示对c:\test目录只保留最近10天的子...

在Python中使用SimpleParse模块进行解析的教程

与大多数程序员一样,我经常需要标识存在于文本文档中的部件和结构,这些文档包括:日志文件、配置文件、分隔的数据以及格式更自由的(但还是半结构化的)报表格式。所有这些文档都拥有它们自己的“小...

Python二叉树的遍历操作示例【前序遍历,中序遍历,后序遍历,层序遍历】

本文实例讲述了Python二叉树的遍历操作。分享给大家供大家参考,具体如下: # coding:utf-8 """ @ encoding: utf-8 @ author: lixia...

Python语言实现百度语音识别API的使用实例

未来的一段时间,人工智能在市场上占有很重的位置,Python语言则是研究人工智能的最佳编程语言,下面,就让我们来感受一下它的魅力吧! 百度给的样例程序,不论C还是Java版,都分为met...