SpeechRecognitionEngine.LoadGrammar Method

Synchronously loads a Grammar object.

Namespace:  Microsoft.Speech.Recognition
Assembly:  Microsoft.Speech (in Microsoft.Speech.dll)

public void LoadGrammar(
	Grammar grammar


Type: Microsoft.Speech.Recognition.Grammar
The grammar object to load.


grammar is a null reference (Nothing in Visual Basic).


grammar is not in a valid state.

The recognizer throws an exception if the Grammar object is already loaded, is being asynchronously loaded, or has failed to load into any recognizer. You cannot load the same Grammar object into multiple instances of SpeechRecognitionEngine. Instead, create a new Grammar object for each SpeechRecognitionEngine instance.

If the recognizer is running, applications must use RequestRecognizerUpdate() to pause the speech recognition engine before loading, unloading, enabling, or disabling a grammar.

When you load a grammar, it is enabled by default. To disable a loaded grammar, use the Enabled property.

To load a Grammar object asynchronously, use the LoadGrammarAsync(Grammar) method.

The following example creates a simple grammar from a string using a GrammarBuilder object. The example then constructs a Grammar object from the GrammarBuilder and loads it into the SpeechRecognitionEngine instance. A handler for the LoadGrammarCompleted event writes the name of the Grammar object to the console when it is loaded. A handler for the SpeechRecognized event writes the result of recognition to the console.

using System;
using Microsoft.Speech.Recognition;

namespace SampleRecognition
  class Program
    static void Main(string[] args)

    // Initialize a SpeechRecognitionEngine object.
      using (SpeechRecognitionEngine recognizer =
         new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US")))

        // Create and load a grammar.
        GrammarBuilder test = new GrammarBuilder("testing");
        Grammar testGrammar = new Grammar(test);
        testGrammar.Name = "Test";

        // Configure recognizer input.

        // Attach an event handler for the LoadGrammarCompleted event.
        recognizer.LoadGrammarCompleted += new EventHandler<LoadGrammarCompletedEventArgs>(recognizer_LoadGrammarCompleted);

        // Attach an event handler for the SpeechRecognized event.
        recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

        // Start recognition.
        Console.WriteLine("Starting asynchronous recognition...");

        // Keep the console window open 

    // Handle the SpeechRecognized event.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
      Console.WriteLine("Speech recognized: " + e.Result.Text);

    // Handle the LoadGrammarCompleted event.
    static void recognizer_LoadGrammarCompleted(object sender, LoadGrammarCompletedEventArgs e)
      Console.WriteLine("Grammar loaded: " + e.Grammar.Name);