RecognitionResult.GetAudioForWordRange Method (RecognizedWordUnit, RecognizedWordUnit)

 

Gets a section of the audio that is associated with a specific range of words in the recognition result.

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

public RecognizedAudio GetAudioForWordRange(
	RecognizedWordUnit firstWord,
	RecognizedWordUnit lastWord
)

Parameters

firstWord
Type: System.Speech.Recognition.RecognizedWordUnit

The first word in the range.

lastWord
Type: System.Speech.Recognition.RecognizedWordUnit

The last word in the range.

Return Value

Type: System.Speech.Recognition.RecognizedAudio

The section of audio associated with the word range.

Exception Condition
NullReferenceException

The recognizer generated the result from a call to EmulateRecognize or EmulateRecognizeAsync methods of the SpeechRecognizer or SpeechRecognitionEngine objects.

To get the complete audio associated with the recognition result, use the Audio property.

The following example creates a grammar to accept name input and attaches to it a handler for the SpeechRecognized event. The grammar uses a wildcard for the name element of the phrase. The event handler uses the audio from the wildcard to create and play a greeting prompt.


private Grammar CreateNameInputGrammar()
{
  GrammarBuilder wildcardBuilder = new GrammarBuilder();
  wildcardBuilder.AppendWildcard();
  SemanticResultKey nameKey =
    new SemanticResultKey("Name", wildcardBuilder);

  GrammarBuilder nameBuilder =
    new GrammarBuilder("My name is");
  nameBuilder.Append(nameKey);

  Grammar nameGrammar = new Grammar(nameBuilder);
  nameGrammar.Name = "Name input";

  nameGrammar.SpeechRecognized +=
    new EventHandler<SpeechRecognizedEventArgs>(
      NameInputHandler);

  return nameGrammar;
}

// Handle the SpeechRecognized event for the name grammar.
private void NameInputHandler(object sender, SpeechRecognizedEventArgs e)
{
  if (e.Result == null) return;

  RecognitionResult result = e.Result;
  SemanticValue semantics = e.Result.Semantics;

  if (semantics.ContainsKey("Name"))
  {
    RecognizedAudio nameAudio =
      result.GetAudioForWordRange(
        result.Words[3], result.Words[result.Words.Count - 1]);

    // Save the audio. Create a directory and file as necessary.
    FileInfo fi = new FileInfo(@"C:\temp\temp.wav");
    if (!fi.Directory.Exists)
    {
      fi.Directory.Create();
    }
    FileStream stream = new FileStream(fi.FullName, FileMode.Create);
    nameAudio.WriteToWaveStream(stream);
    stream.Close();

    // Greet the person using the saved audio.
    SpeechSynthesizer synthesizer = new SpeechSynthesizer();
    PromptBuilder builder = new PromptBuilder();
    builder.AppendText("Hello");
    builder.AppendAudio(fi.FullName);
    synthesizer.Speak(builder);
  }
}

.NET Framework
Available since 3.0
Return to top
Show: