Python 语音

实现语音操控的原理

语音操控分为语音识别和语音朗读两部分

我们使用speech模块实现语音模块(python 2.7)

SAPI是微软Speech API , 是微软公司推出的语音接口,而细心的人会发现从WINXP开始,系统上就已经有语音识别的功能了,可是用武之地相当之少,他并没有给出一些人性化的自定义方案,仅有的语音操控命令显得相当鸡胁。
  • Python pywin32,可以使Python调用WIN32COM接口,选择对应版本下载(区分32位/64位),直接双击运行即可

  • 安装speech模块:pip install speech

实现个简易的控制电脑做事情的小程序:

  • 首先,来个测试文件

此处仅为启动和关闭语音系统

import speech
while True:
phrase =speech.input()
speech.say("You said %s"%phrase)
if phrase =="turn off":
break

  • 自制个中文库
phrase = {"closeMainSystem" : "关闭人机交互"
, "film" : "我要看电影"
, "listenMusic" : "我好累啊"
, "blog" : "看博客"
, "cmd" : "cmd" }
  • 设计语音对应的电脑操作

def callback(phr, phrase):
if phr == phrase["closeMainSystem"]:
speech.say("Goodbye. 人机交互即将关闭,谢谢使用")
speech.stoplistening()
sys.exit()
elif phr == phrase["film"]:
speech.say("正在为您打开优酷")
webbrowser.open_new("http://www.youku.com/")
elif phr == phrase["listenMusic"]:
speech.say("即将为你启动豆瓣电台")
webbrowser.open_new("http://douban.fm/")
elif phr == phrase["blog"]:
speech.say("即将进入Dreamforce.me")
webbrowser.open_new("http://www.cnblogs.com/darksouls/")
elif phr == phrase["cmd"]:
speech.say("即将打开CMD")
os.popen("C:\Windows\System32\cmd.exe") # 可以继续用 elif 写对应的自制中文库中的对应操作
  • 主程序
while True:
phr = speech.input()
speech.say("You said %s" % phr)
callback(phr, phrase)
  • 完整代码
# _*_ coding:utf-8 _*_

import os
import sys
import speech
import webbrowser phrase = {"closeMainSystem" : "关闭人机交互"
, "film" : "我要看电影"
, "listenMusic" : "我好累啊"
, "blog" : "看博客"
, "cmd" : "cmd" } def callback(phr, phrase):
if phr == phrase["closeMainSystem"]:
speech.say("Goodbye. 人机交互即将关闭,谢谢使用")
speech.stoplistening()
sys.exit()
elif phr == phrase["film"]:
speech.say("正在为您打开优酷")
webbrowser.open_new("http://www.youku.com/")
elif phr == phrase["listenMusic"]:
speech.say("即将为你启动豆瓣电台")
webbrowser.open_new("http://douban.fm/")
elif phr == phrase["blog"]:
speech.say("即将进入Dreamforce.me")
webbrowser.open_new("http://www.cnblogs.com/darksouls/")
elif phr == phrase["cmd"]:
speech.say("即将打开CMD")
os.popen("C:\Windows\System32\cmd.exe") # 可以继续用 elif 写对应的自制中文库中的对应操作 while True:
phr = speech.input()
speech.say("You said %s" % phr)
callback(phr, phrase)

发现网上有个语音识别框架:

# _*_ coding:utf-8 _*_

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("lisi")
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入门 —— 06语音识别的更多相关文章

  1. Python学习【第二篇】Python入门

    Python入门 Hello World程序 在linux下创建一个叫hello.py,并输入 print("Hello World!") 然后执行命令:python hello. ...

  2. 老鸟的Python入门教程

    转自老鸟的Python入门教程 重要说明 这不是给编程新手准备的教程,如果您入行编程不久,或者还没有使用过1到2门编程语言,请移步!这是有一定编程经验的人准备的.最好是熟知Java或C,懂得命令行,S ...

  3. [转][RabbitMQ+Python入门经典] 兔子和兔子窝

    [转][RabbitMQ+Python入门经典] 兔子和兔子窝 http://blog.csdn.net/linvo/article/details/5750987 RabbitMQ作为一个工业级的消 ...

  4. Python入门篇-基础数据类型之整型(int),字符串(str),字节(bytes),列表(list)和切片(slice)

    Python入门篇-基础数据类型之整型(int),字符串(str),字节(bytes),列表(list)和切片(slice) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Py ...

  5. Python 入门之 内置模块 -- time模块

    Python 入门之 内置模块 -- time模块 1.time模块 ​ time翻译过来就是时间,这个模块是与时间相关的模块 import time # 内置模块 -- 标准库 (1)time.ti ...

  6. python入门简介

    Python前世今生 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC ...

  7. python入门学习课程推荐

    最近在学习自动化,学习过程中,越来越发现coding能力的重要性,不会coding,基本不能开展自动化测试(自动化工具只是辅助). 故:痛定思痛,先花2个星期将python基础知识学习后,再进入自动化 ...

  8. Python运算符,python入门到精通[五]

    运算符用于执行程序代码运算,会针对一个以上操作数项目来进行运算.例如:2+3,其操作数是2和3,而运算符则是“+”.在计算器语言中运算符大致可以分为5种类型:算术运算符.连接运算符.关系运算符.赋值运 ...

  9. Python基本语法[二],python入门到精通[四]

    在上一篇博客Python基本语法,python入门到精通[二]已经为大家简单介绍了一下python的基本语法,上一篇博客的基本语法只是一个预览版的,目的是让大家对python的基本语法有个大概的了解. ...

随机推荐

  1. Python学习系列----第四章 函数

    4.1 函数定义   函数是python中重要的工具.函数用关键字 def 来定义.def 关键字后跟一个函数的标识符名称,然后跟一对圆括号.圆括号之中可以包括一些变量名,该行以冒号结尾.接下来是一块 ...

  2. Java基础之Java中的泛型

    1.为什么要使用泛型 这里我们俩看一段代码; List list = new ArrayList(); list.add("CSDN_SEU_Cavin"); list.add(1 ...

  3. shell编程报错:“syntax error near unexpected token `”

    今天写了个shell脚本,在自己机器上运行正常,给同事,运行报错syntax error near unexpected token `,左看右看shell脚本没有问题,没有办法google搜索,发现 ...

  4. css best practice for big team and project

    推荐查看以下文章: https://segmentfault.com/a/1190000000704006 关于BEM,SMACSS,OOCSS的通俗易懂的介绍 http://philipwalton ...

  5. SQL Server ->> 深入探讨SQL Server 2016新特性之 --- Row-Level Security(行级别安全控制)

    SQL Server 2016 CPT3中包含了一个新特性叫Row Level Security(RLS),允许数据库管理员根据业务需要依据客户端执行脚本的一些特性控制客户端能够访问的数据行,比如,我 ...

  6. CefSharp开发

    CefSharp是用chromium内核开发的.net版本浏览器工具.目前只支持X86模式.所以在调试的时候要把平台改为X86 CefSharp开发指引:https://ourcodeworld.co ...

  7. Hadoop学习---Ubuntu中hadoop完全分布式安装教程

    软件版本 Hadoop版本号:hadoop-2.6.0-cdh5.7.0: VMWare版本号:VMware 9或10 Linux系统:CentOS 6.4-6.5 或Ubuntu版本号:ubuntu ...

  8. Go语言(三)反射机制

    package main import( "fmt" "reflect" ) func main(){ // iterate through the attri ...

  9. Fcoin和Coinex,谁更值得投资?

    2018年是数字货币市场很熊的一年,大部分币种在这一年下跌超过了90%.但是这一年对于数字货币的发展也是不平凡的,可以说是至关重要的一年.通证经济商业模型在这一年萌芽,并茁壮成长,2018是通证经济元 ...

  10. Junit4所需jar包

    在eclipse中新建一个Junit类,运行时出现java.lang.NoClassdeffounderror:org/apache/commons/logging/LogFactory错误,原来是缺 ...