如下所示:
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)