Python:win32com.client.getevents("SAPI.SpSharedRecoContext“)返回非

2024-06-16 13:15:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我下载了一段代码,展示了如何在Windows7上使用Python2.7.3解释器使用WindowsSpeechAPI(SAPI5.1),并在我的系统上安装了Pywin32Build218。代码的一切都很好:

from win32com.client import constants
import win32com.client
import pythoncom

"""Sample code for using the Microsoft Speech SDK 5.1 via COM in Python.
    Requires that the SDK be installed; it's a free download from
            http://microsoft.com/speech
    and that MakePy has been used on it (in PythonWin,
    select Tools | COM MakePy Utility | Microsoft Speech Object Library 5.1).

    After running this, then saying "One", "Two", "Three" or "Four" should
    display "You said One" etc on the console. The recognition can be a bit
    shaky at first until you've trained it (via the Speech entry in the Windows
    Control Panel."""
class SpeechRecognition:
    """ Initialize the speech recognition with the passed in list of words """
    def __init__(self, wordsToAdd):
        # For text-to-speech
        self.speaker = win32com.client.Dispatch("SAPI.SpVoice")
        # For speech recognition - first create a listener
        self.listener = win32com.client.Dispatch("SAPI.SpSharedRecognizer")
        # Then a recognition context
        self.context = self.listener.CreateRecoContext()
        # which has an associated grammar
        self.grammar = self.context.CreateGrammar()
        # Do not allow free word recognition - only command and control
        # recognizing the words in the grammar only
        self.grammar.DictationSetState(0)
        # Create a new rule for the grammar, that is top level (so it begins
        # a recognition) and dynamic (ie we can change it at runtime)
#         self.wordsRule = self.grammar.Rules.Add("wordsRule",constants.SRATopLevel + constants.SRADynamic, 0)

        # Clear the rule (not necessary first time, but if we're changing it
        # dynamically then it's useful)
#         self.wordsRule.Clear()
        self.wordsRule = self.grammar.Rules.Add("wordsRule",1)
        self.wordsRule.Clear()
        # And go through the list of words, adding each to the rule
        [ self.wordsRule.InitialState.AddWordTransition(None, word) for word in wordsToAdd ]
        # Set the wordsRule to be active
        self.grammar.Rules.Commit()
        self.grammar.CmdSetRuleState("wordsRule", 1)
        # Commit the changes to the grammar
        self.grammar.Rules.Commit()
        # And add an event handler that's called back when recognition occurs
        self.eventHandler = ContextEvents(self.context)
        # Announce we've started using speech synthesis
        self.say("Started successfully")
    """Speak a word or phrase"""
    def say(self, phrase):
        self.speaker.Speak(phrase)


"""The callback class that handles the events raised by the speech object.
    See "Automation | SpSharedRecoContext (Events)" in the MS Speech SDK
    online help for documentation of the other events supported. """
class ContextEvents(win32com.client.getevents("SAPI.SpSharedRecoContext")):
    """Called when a word/phrase is successfully recognized  -
        ie it is found in a currently open grammar with a sufficiently high
        confidence"""
    def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result):
        newResult = win32com.client.Dispatch(Result)
        print "You said: ",newResult.PhraseInfo.GetText()

if __name__=='__main__':
    wordsToAdd = [ "One", "Two", "Three", "Four" ]
    speechReco = SpeechRecognition(wordsToAdd)
    while 1:
        pythoncom.PumpWaitingMessages()

但我有个例外: 类上下文事件(win32com.client.getevents("SAPI.SpSharedRecoContext")): TypeError:调用元类基时出错 无法创建“NoneType”实例

我在网上搜遍了,唯一找到的是: TypeError: Error when calling the metaclass bases

它没有帮助,所以我搜索了更多,并对部分代码做了一些调查,所以我发现win32com.client.getevents("SAPI.SpSharedRecoContext“)不返回,因此当它用作基类时,将引发该异常。在

那么,有什么问题?我怎样才能解决这个问题?否则,我可以用其他方法使用SAPI 5.1进行语音识别吗?在

注意:我知道SpeechPy项目,但我必须使用windowsapi。在

谢谢。在


Tags: theinselfclientforthatitspeech
2条回答

你忘了运行MakePy。
如果安装了pyWin32,它也安装了PythonWin。在

打开PythonWin,然后选择工具| COM MakePy Utility | Microsoft Speech Object Library 5.4

我对Python一无所知,但我注意到您没有对上下文设置任何事件兴趣,所以SAPI永远不会给您回电话。 你也没有启用上下文(通过上下文状态)也可以。在

至少,你需要

self.context.EventInterests = 16
self.context.State = 1
self.eventHandler = ContextEvents(self.context)

告诉SAPI您对识别事件感兴趣,并启用上下文。在

SAPI events的完整列表可在MSDN上找到

相关问题 更多 >