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://www.jb51.net/article/195212.htm
到此這篇關於python之語音識別speech模組的文章就介紹到這了,更多相關python 語音識別內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!