LoadGrammarCompletedEventArgs LoadGrammarCompletedEventArgs LoadGrammarCompletedEventArgs LoadGrammarCompletedEventArgs Class

Определение

Предоставляет данные для события LoadGrammarCompleted объекта SpeechRecognizer или SpeechRecognitionEngine.Provides data for the LoadGrammarCompleted event of a SpeechRecognizer or SpeechRecognitionEngine object.

public ref class LoadGrammarCompletedEventArgs : System::ComponentModel::AsyncCompletedEventArgs
public class LoadGrammarCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
type LoadGrammarCompletedEventArgs = class
    inherit AsyncCompletedEventArgs
Public Class LoadGrammarCompletedEventArgs
Inherits AsyncCompletedEventArgs
Наследование
LoadGrammarCompletedEventArgsLoadGrammarCompletedEventArgsLoadGrammarCompletedEventArgsLoadGrammarCompletedEventArgs

Примеры

В следующем примере создается общий распознаватель речи, а затем создаются два типа грамматики для распознавания конкретных слов и для принятия бесплатной диктовки.The following example creates a shared speech recognizer, and then creates two types of grammars for recognizing specific words and for accepting free dictation. В примере асинхронно загружается все созданные грамматики в распознаватель.The example asynchronously loads all the created grammars to the recognizer. Обработчики для событий распознавателя LoadGrammarCompleted и SpeechRecognized сообщают о результатах распознавания и грамматике, использованной для распознавания.Handlers for the recognizer's LoadGrammarCompleted and SpeechRecognized events report the results of recognition and which grammar was used to perform the recognition.

using System;  
using System.Speech.Recognition;  
  
namespace SampleRecognition  
{  
  class Program  
  {  
    private static SpeechRecognizer recognizer;  
    public static void Main(string[] args)  
    {  
  
      // Initialize a shared speech recognition engine.  
      recognizer = new SpeechRecognizer();  
  
        // Add a handler for the LoadGrammarCompleted event.  
        recognizer.LoadGrammarCompleted +=  
          new EventHandler<LoadGrammarCompletedEventArgs>(recognizer_LoadGrammarCompleted);  
  
        // Add a handler for the SpeechRecognized event.  
        recognizer.SpeechRecognized +=  
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);  
  
        // Add a handler for the StateChanged event.  
        recognizer.StateChanged +=  
          new EventHandler<StateChangedEventArgs>(recognizer_StateChanged);  
  
        // Create the "yesno" grammar and build it into a Grammar object.  
        Choices yesChoices = new Choices(new string[] { "yes", "yup", "yah}" });  
        SemanticResultValue yesValue =  
            new SemanticResultValue(yesChoices, (bool)true);  
        Choices noChoices = new Choices(new string[] { "no", "nope", "nah" });  
        SemanticResultValue noValue =  
            new SemanticResultValue(noChoices, (bool)false);  
        SemanticResultKey yesNoKey =  
            new SemanticResultKey("yesno", new Choices(new GrammarBuilder[] { yesValue, noValue }));  
        Grammar yesnoGrammar = new Grammar(yesNoKey);  
        yesnoGrammar.Name = "yesNo";  
  
        // Create the "done" grammar within the constructor of a Grammar object.  
        Grammar doneGrammar =  
        new Grammar(new GrammarBuilder(new Choices(new string[] { "done", "exit", "quit", "stop" })));  
        doneGrammar.Name = "Done";  
  
        // Create a dictation grammar.  
        Grammar dictation = new DictationGrammar();  
        dictation.Name = "Dictation";  
  
        // Load grammars to the recognizer.  
        recognizer.LoadGrammarAsync(yesnoGrammar);  
        recognizer.LoadGrammarAsync(doneGrammar);  
        recognizer.LoadGrammarAsync(dictation);  
  
        // Keep the console window open.  
        Console.ReadLine();  
      }  
  
    // Handle the SpeechRecognized event.  
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)  
    {  
      Console.WriteLine("Grammar({0}): {1}", e.Result.Grammar.Name, e.Result.Text);  
  
      // Add event handler code here.  
    }  
  
    // Handle the LoadGrammarCompleted event.   
    static void recognizer_LoadGrammarCompleted(object sender, LoadGrammarCompletedEventArgs e)  
    {  
      string grammarName = e.Grammar.Name;  
      bool grammarLoaded = e.Grammar.Loaded;  
  
      if (e.Error != null)  
      {  
  
        Console.WriteLine("LoadGrammar for {0} failed with a {1}.",  
        grammarName, e.Error.GetType().Name);  
  
        // Add exception handling code here.  
      }  
  
      Console.WriteLine("Grammar {0} {1} loaded.",  
      grammarName, (grammarLoaded) ? "is" : "is not");  
    }  
  
    // Put the shared speech recognizer into "listening" mode.   
    static void recognizer_StateChanged(object sender, StateChangedEventArgs e)  
    {  
      if (e.RecognizerState != RecognizerState.Stopped)  
      {  
        recognizer.EmulateRecognizeAsync("Start listening");  
      }  
    }  
  }  
}  
  

Комментарии

LoadGrammarCompletedEventArgs Экземпляр создается, SpeechRecognitionEngine когда SpeechRecognitionEngine.LoadGrammarCompleted объектвызываетLoadGrammarCompleted его объект или вызываетсобытие.SpeechRecognizerAn instance of LoadGrammarCompletedEventArgs is created when the SpeechRecognitionEngine object raises its SpeechRecognitionEngine.LoadGrammarCompleted or the SpeechRecognizer object raises its LoadGrammarCompleted event. События вызываются при завершении вызовов LoadGrammarAsync методов.The events are raised when calls to the LoadGrammarAsync methods complete.

Чтобы получить сведения о Grammar загруженном объекте, Grammar обратитесь к свойству в обработчике события.To obtain information about the Grammar object that was loaded, access the Grammar property in the handler for the event.

Если Error распознаватель встречает исключение во время операции, для свойства задается исключение, Loaded а свойство связанного Grammar свойства может иметь falseзначение.If the recognizer encounters an exception during the operation, the Error property is set to the exception and the Loaded property of the associated Grammar may be false.

Свойства

Cancelled Cancelled Cancelled Cancelled

Возвращает значение, показывающее, была ли отменена асинхронная операция.Gets a value indicating whether an asynchronous operation has been canceled.

(Inherited from AsyncCompletedEventArgs)
Error Error Error Error

Возвращает значение, показывающее, какая ошибка произошла в течение асинхронной операции.Gets a value indicating which error occurred during an asynchronous operation.

(Inherited from AsyncCompletedEventArgs)
Grammar Grammar Grammar Grammar

Объект Grammar, завершивший загрузку.The Grammar object that has completed loading.

UserState UserState UserState UserState

Возвращает уникальный идентификатор для асинхронной задачи.Gets the unique identifier for the asynchronous task.

(Inherited from AsyncCompletedEventArgs)

Методы

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Определяет, равен ли заданный объект текущему объекту.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Служит хэш-функцией по умолчанию.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object.

(Inherited from Object)
RaiseExceptionIfNecessary() RaiseExceptionIfNecessary() RaiseExceptionIfNecessary() RaiseExceptionIfNecessary()

Вызывает предоставленное пользователем исключение в случае неудачного выполнения асинхронной операции.Raises a user-supplied exception if an asynchronous operation failed.

(Inherited from AsyncCompletedEventArgs)
ToString() ToString() ToString() ToString()

Возвращает строку, представляющую текущий объект.Returns a string that represents the current object.

(Inherited from Object)

Применяется к

Дополнительно