Speech Recognition

From IronPython Cookbook

Speech Recognition

Set up a simple grammar (with just four words) and start the speech recognition engine. Recognized words will be printed to the console. Press any key to terminate the application. To run this code, you will need to have .NET 3.x installed.

Note that, in IronPython, you have to start the recognition engine in a different thread (but for some reason this is not required in Python.NET).

Recognize Console Screenshot

import clr
clr.AddReference("System.Speech, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
from System.Speech.Recognition import (SpeechRecognitionEngine, GrammarBuilder,
        Grammar, Choices, RecognizeMode)

count = 0

def main():
    sre = SpeechRecognitionEngine()
    sre.SetInputToDefaultAudioDevice()
    sre.UnloadAllGrammars()

    gb = GrammarBuilder()
    gb.Append(Choices('cut', 'copy', 'paste', 'delete'))
    sre.LoadGrammar(Grammar(gb))

    def OnSpeechRecognized(sender, e):
        global count
        count += 1
        print '%d. %s' % (count, e.Result.Text)
    sre.SpeechRecognized += OnSpeechRecognized

    sre.RecognizeAsync(RecognizeMode.Multiple)

    raw_input('Press ENTER to quit\n\n')

if __name__ == '__main__':
    import sys

    if sys.platform == 'cli':
        from System.Threading import Thread, ThreadStart
        thread = Thread(ThreadStart(main))
        thread.Start()
    else:
        main()


Back to Contents.

TOOLBOX
LANGUAGES