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)."""
class SpeechRecognition:
    """ Initialize the speech recognition with the passed in list of words """
    def __init__(self):
        # 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(constants.SGDSActive)
        # And add an event handler that's called back when recognition occurs
        self.eventHandler = ContextEvents(self.context)      
    """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)
        tekst = newResult.PhraseInfo.GetText()
        speaker = win32com.client.Dispatch("SAPI.SpVoice")
        speaker.Speak(tekst)
        print "You said: ",tekst
    
if __name__=='__main__':
    speechReco = SpeechRecognition()    
    speechReco.say("I am sitting in a room different from the one you are in now. I am recording the sound of my speaking voice and I am going to play it back into the room again.");
    
    while 1:
        pythoncom.PumpWaitingMessages()
