RecognizeCompletedEventArgs RecognizeCompletedEventArgs RecognizeCompletedEventArgs RecognizeCompletedEventArgs Class

Определение

Предоставляет данные для события RecognizeCompleted, вызываемого объектом SpeechRecognitionEngine или SpeechRecognizer.Provides data for the RecognizeCompleted event raised by a SpeechRecognitionEngine or a SpeechRecognizer object.

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

Примеры

В следующем примере выполняется асинхронное распознавание речи в грамматике распознавания речи с SpeechRecognitionEngine.RecognizeAsync помощью метода и внутрипроцессного распознавателя.The following example performs asynchronous speech recognition on a speech recognition grammar, using the SpeechRecognitionEngine.RecognizeAsync method with the in-process recognizer. В примере используются Choices объекты GrammarBuilder и для создания грамматики распознавания речи Grammar перед их созданием в объекте.The example uses Choices and GrammarBuilder objects to create the speech recognition grammar before building it into a Grammar object. Обработчик SpeechRecognitionEngine.RecognizeCompleted события выводит сведения об операции распознавания в консоль.A handler for the SpeechRecognitionEngine.RecognizeCompleted event outputs information about the recognition operation to the console.

using System;  
using System.Speech.Recognition;  

namespace SampleRecognition  
{  
  class Program  
  {  
    private static SpeechRecognitionEngine recognizer;  
    public static void Main(string[] args)  
    {  

      // Initialize a SpeechRecognitionEngine object and set its input.  
      recognizer = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));  
      recognizer.SetInputToDefaultAudioDevice();  

      // Configure recognition parameters.  
      recognizer.InitialSilenceTimeout = TimeSpan.FromSeconds(5.0);  
      recognizer.BabbleTimeout = TimeSpan.FromSeconds(3.0);  
      recognizer.EndSilenceTimeout = TimeSpan.FromSeconds(1.0);  
      recognizer.EndSilenceTimeoutAmbiguous = TimeSpan.FromSeconds(1.0);  

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

      // Add a handler for the RecognizeCompleted event.  
      recognizer.RecognizeCompleted +=   
        new EventHandler<RecognizeCompletedEventArgs>(recognizer_RecognizeCompleted);  

      // Create a speech recognition grammar and build it into a Grammar object.  
      Choices bankingMenu = new Choices(new string[]   
      { "Access accounts", "Transfer funds", "Pay bills", "Get loan balance" });  
      GrammarBuilder banking = new GrammarBuilder(bankingMenu);  
      Grammar bankGrammar = new Grammar(banking);  
      bankGrammar.Name = "Banking Menu";  

      // Load the Grammar objects to the recognizer.  
      recognizer.LoadGrammarAsync(bankGrammar);  

      // Start asynchronous, continuous recognition.  
      recognizer.RecognizeAsync();  

      // Keep the console window open.  
      Console.ReadLine();  
    }  

    // Handle the RecognizeCompleted event.  
    static void recognizer_RecognizeCompleted(object sender, RecognizeCompletedEventArgs e)  
    {  
      if (e.Error != null)  
      {  
        Console.WriteLine(  
          "RecognizeCompleted, error occurred during recognition: {0}", e.Error);  
        return;  
      }  

      if (e.InitialSilenceTimeout || e.BabbleTimeout)  
      {  
        Console.WriteLine(  
          "RecognizeCompleted: BabbleTimeout({0}), InitialSilenceTimeout({1}).",  
          e.BabbleTimeout, e.InitialSilenceTimeout);  
        return;  
      }  

      if (e.InputStreamEnded)  
      {  
        Console.WriteLine(  
          "RecognizeCompleted: AudioPosition({0}), InputStreamEnded({1}).",  
          e.AudioPosition, e.InputStreamEnded);  
      }  

      if (e.Result != null)  
      {  
        Console.WriteLine(  
          "RecognizeCompleted: Grammar ({0}), Text ({1}), Confidence ({2}), AudioPosition ({3}).",  
          e.Result.Grammar.Name, e.Result.Text, e.Result.Confidence, e.AudioPosition);  
      }  

      else  
      {  
        Console.WriteLine("RecognizeCompleted: No result.");  
      }   

      Console.WriteLine();  
      Console.WriteLine("Press any key to exit...");  
      Console.ReadKey();  
    }  

    // Handle the LoadGrammarCompleted event.   
    static void recognizer_LoadGrammarCompleted(object sender, LoadGrammarCompletedEventArgs e)  
    {  
      string grammarName = e.Grammar.Name;  
      bool grammarLoaded = e.Grammar.Loaded;  
      bool grammarEnabled = e.Grammar.Enabled;  

      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 and {2} enabled.", grammarName,   
        (grammarLoaded) ? "is" : "is not", (grammarEnabled) ? "is" : "is not");  
    }  
  }            
}  

Комментарии

RecognizeCompleted Экземпляр создается, SpeechRecognitionEngine когда SpeechRecognizer объект RecognizeAsync или вызывает событие после завершения операции. SpeechRecognizedAn instance of RecognizeCompleted is created when the SpeechRecognitionEngine or the SpeechRecognizer object raises its SpeechRecognized event after completing a RecognizeAsync operation. Дополнительные сведения о событиях распознавания речи см. в разделе Использование событий распознавания речи.For more information about speech recognition events, see Using Speech Recognition Events.

Свойства

AudioPosition AudioPosition AudioPosition AudioPosition

Получает расположение в потоке звука на устройстве ввода, связанном с событием RecognizeCompleted.Gets the location in the input device's audio stream associated with the RecognizeCompleted event.

BabbleTimeout BabbleTimeout BabbleTimeout BabbleTimeout

Получает значение, указывающее, было ли событие RecognizeCompleted создано в связи с истечением времени ожидания окончания помех.Gets a value that indicates whether a babble timeout generated the RecognizeCompleted event.

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)
InitialSilenceTimeout InitialSilenceTimeout InitialSilenceTimeout InitialSilenceTimeout

Получает значение, указывающее, было ли событие RecognizeCompleted создано в связи с истечением времени ожидания окончания начального молчания.Gets a value that indicates whether an initial silence timeout generated the RecognizeCompleted event.

InputStreamEnded InputStreamEnded InputStreamEnded InputStreamEnded

Получает значение, указывающее, завершен ли входной поток.Gets a value indicating whether the input stream ended.

Result Result Result Result

Получает результат распознавания.Gets the recognition result.

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)

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

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