python之語音識別(speech模塊)


1.原理

語音操控分為 語音識別和語音朗讀兩部分。

這兩部分本來是需要自然語言處理技能相關知識以及一系列極其復雜的算法才能搞定,可是這篇文章將會跳過此處,如果你只是對算法和自然語言學感興趣的話,就只有請您移步了,下面沒有一個字會講述到這些內容。

早在上世紀90年代的時候,IBM就推出了一款極為強大的語音識別系統-vio voice , 而其后相關產品層出不窮,不斷的進化和演變着。 我們這里將會使用SAPI實現語音模塊。

2. 什么是SAPI?

SAPI是微軟Speech API , 是微軟公司推出的語音接口,而細心的人會發現從WINXP開始,系統上就已經有語音識別的功能了,可是用武之地相當之少,他並沒有給出一些人性化的自定義方案,僅有的語音操控命令顯得相當雞脅。 那么這篇文章的任務就是利用SAPI進行個性化的語音識別

代碼

前提:打開win7的語音自動識別(控制面板--輕松訪問--語音識別)

#!/usr/bin/env python
# -*- codinfg:utf-8 -*-
'''
@author: Jeff LEE
@file: .py
@time: 2018-07-19 11:15
@desc:
'''
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=="記事本":
            os.system('notepad')  
        elif  speechstr=="寫字板":
            os.system('write')
        elif  speechstr=="畫圖板":
            os.system('mspaint')
        else:
            pass

if __name__ == '__main__':

    speaker.Speak("語音識別開啟")
    wordsToAdd = ["記事本", "寫字板","畫圖板",]
    speechReco = SpeechRecognition(wordsToAdd)
    while True:
        pythoncom.PumpWaitingMessages()

  調試遇到問題

python調用語音模塊時,遇見TypeError:NoneTypetakesnoarguments這種錯誤類型該如何解決

報錯的原因是:不能調用語音開發包

解決方法:(如果你已經安裝了pyWin32,它也安裝了PythonWin)

1.在python35目錄中找到pythonwin文件夾下的pythonwin.exe

2.雙擊Pythonwin運行,然后選擇工具tools/commakepyutility

3.然后選擇MicrosoftSpeechObjectLibrary5.4,點擊OK鍵

4.運行結果如下,問題解決

 

后記

推薦一個不錯的語音識別文檔:https://blog.csdn.net/j2IaYU7Y/article/details/79878310


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM