Microsoft Speech Platform SDK 11 Documentation

[image]

Microsoft Speech Platform SDK 11 Documentation
See Also Send Feedback

The Microsoft Speech Platform SDK 11 provides a comprehensive set of development tools for building server-side, voice-enabled applications. You can use the technologies and tools in the Speech Platform SDK 11 to give applications the ability to recognize spoken words (speech recognition) and to generate synthesized speech (text-to-speech or TTS). Using this SDK, you can give users an effective and natural way to interact with your applications, complementing the use of mice, keyboards, controllers, and gestures.

The documentation for the Speech Platform SDK 11 includes a programming guide and reference sections to help you learn to use the speech application programming interfaces (APIs) to manage the Microsoft Speech Platform Runtime 11 and engines for speech recognition and TTS. The programming guide and reference sections contain sample code, and additional samples are available in the folders where you installed the Speech Platform SDK 11.

In This SDK

  • Speech Programming Guide

    Contains conceptual information and examples that you can use to add speech to your applications, and includes references for markup language used to create documents for speech recognition and speech synthesis (TTS).

  • VoiceXML Support (Microsoft.Speech)

    Describes support for processing VoiceXML documents.

  • Microsoft Grammar Development Tools

    Contains reference manuals for tools that help you to test and optimize your voice applications.

  • Microsoft.Speech Managed Code Class Library

    Contains reference documentation for the classes of the managed-code Microsoft.Speech namespaces.

  • Microsoft.Speech.VoiceXml Class Library

    Contains reference documentation for the Microsoft.Speech.VoiceXML namespace.

  • Microsoft Speech Platform Native Code API

    Contains reference and conceptual documentation for the COM-based, native-code API of the Speech Platform SDK 11.

See Also

Concepts

Legal Information (Microsoft Speech Platform SDK 11)

Other Resources

Microsoft Online Privacy Notice
Accessibility in Microsoft Products
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Legal Information (Microsoft Speech Platform SDK 11)

[image]

Legal Information (Microsoft Speech Platform SDK 11)
Send Feedback

This document is provided "as-is". Information and views expressed in this document, including URL and other Internet Web site references, may change without notice. You bear the risk of using it.

Some examples depicted herein are provided for illustration only and are fictitious. No real association or connection is intended or should be inferred.

This document does not provide you with any legal rights to any intellectual property in any Microsoft product. You may copy and use this document for your internal, reference purposes. You may modify this document for your internal, reference purposes.

© 2011 Microsoft. All rights reserved.

Microsoft, Active Directory, DirectX, Internet Explorer, MS-DOS, MSN, Outlook, Visual Basic, Visual C#, Visual C++, Visual Studio, Win32, Windows, Windows Media, Windows Server, and Windows Vista are trademarks of the Microsoft group of companies. All other trademarks are property of their respective owners.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Speech Programming Guide

[image]

Speech Programming Guide
Send Feedback

This programming guide provides an introduction to developing speech applications for Windows Server using the Microsoft.Speech namespaces in the Microsoft Speech Platform SDK 11.

The concepts and examples presented in this documentation will show you how to incorporate speech recognition and speech synthesis (text-to-speech or TTS) into applications running on Windows Server. We recommend that you read the sections titled Speech Synthesis and Speech Recognition before beginning a speech application.

In the section titled Speech Recognition (Microsoft.Speech), you will find discussion and examples that will help you accomplish the following:

  • Create grammars

  • Initialize and manage a speech recognition engine

  • Interpret the results returned by a speech recognition engine

  • Work with speech recognition events

The section titled Speech Synthesis (Microsoft.Speech) includes concepts and examples that will help you accomplish the following:

  • Author content for TTS

  • Generate speech in your application

  • Select and modify a voice

  • Work with speech synthesis events

In addition, you will find reference sections to industry-standard XML markup languages including speech recognition, speech synthesis, semantics, and pronunciation lexicons, as supported by the Speech Platform SDK 11.

In This Section

  • Benefits of Using the Microsoft Speech Platform SDK 11

  • What's New in the Microsoft Speech Platform SDK 11

  • Microsoft Speech Platform SDK 11 Requirements and Installation

  • Speech Recognition (Microsoft.Speech)

  • Speech Synthesis (Microsoft.Speech)

  • Language Support

  • Lexicons and Phonetic Alphabets (Microsoft.Speech)

  • Speech Glossary (Microsoft.Speech)

Reference

This programming guide includes links to documentation for specific classes and members of the Microsoft.Speech namespaces. You can find detailed documentation of all the classes and members of the Microsoft.Speech namespaces at the links listed below.

  • Microsoft.Speech

    Gives applications control over loading resources.

  • Microsoft.Speech.AudioFormat

    Contains the types that specify the audio format used in speech recognition.

  • Microsoft.Speech.Recognition

    Contains the types for implementing speech recognition in an application.

  • Microsoft.Speech.Recognition.SrgsGrammar

    Contains managed code types that correspond to the elements and attributes of the W3C Speech Recognition Grammar Specification Version 1.0.

  • Microsoft.Speech.Synthesis

    Contains the types for implementing speech synthesis in an application.

  • Microsoft.Speech.Text

    Represents the results of text normalization.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Benefits of Using the Microsoft Speech Platform SDK 11

[image]

Benefits of Using the Microsoft Speech Platform SDK 11
Send Feedback

Speech is an effective and natural way for people to interact with applications, complementing or even replacing the use of mice, keyboards, controllers, and gestures. A hands-free, yet accurate way to communicate with applications, speech lets people be productive and stay informed in a variety of situations where other interfaces will not.

Microsoft Speech Platform SDK 11

The Microsoft Speech Platform SDK 11 includes both managed-code and native-code application programming interfaces (APIs).

The Microsoft.Speech managed-code namespaces provide you with easy access to the advanced speech recognition and speech synthesis technologies supported by the Microsoft Speech Platform Runtime 11. The functionality that the managed code APIs expose is a subset of the native-code APIs and will satisfy the majority of speech application scenarios.

The native-code APIs implement all the low-level details needed to control and manage the real-time operations of various speech engines.

You do not need to create your own engines for speech recognition and text-to-speech because you can download and install any of the 26 language packs (speech engines) for speech development. See What's New in the Microsoft Speech Platform SDK 11.

Speech Recognition

Speech recognition allows users to interact with and control your applications by speaking. Using the APIs in the Speech Platform SDK 11, you can acquire and monitor speech input, create speech recognition grammars that produce both literal and semantic recognition results, capture information from events generated by the speech recognition, and configure and manage speech recognition engines. See Speech Recognition (Microsoft.Speech).

Speech Synthesis (text-to-speech or TTS)

The speech synthesis APIs in the Speech Platform SDK 11 will have your application talking with just a few lines of code. You get control over many aspects of voice expression, including volume, speaking rate, word emphasis, pitch contour, and other attributes of speech. See Speech Synthesis (Microsoft.Speech).

Standards Compatible

For both speech recognition and speech synthesis, you get your choice of authoring formats. You can author content programmatically, using the members of the Microsoft.Speech namespaces. Or you can create industry-standard, XML-format speech documents for consumption by the Speech Platform Runtime 11. You can even alternate authoring formats based on your preferences and combine programmatic content with XML-format content.

Grammar Development Tools

The Speech Platform SDK 11 provides tools that you can use to debug and tune grammars that you create for use with the Speech Platform Runtime 11. The functionality of the Microsoft Grammar Development Tools includes grammar validation, phrase generation, confusability detection, batch-mode simulated speech recognition, analysis of simulated recognition results including graphs, and grammar compiling. The Grammar Development Tools will help you to identify problem areas that are hard to detect through standard speech application testing, and to identify problems earlier in the application development life cycle. See Microsoft Grammar Development Tools.

Cost Efficient

The Speech Platform SDK 11 can significantly reduce the amount of work necessary to implement speech in applications for Windows Server. By providing access to the Speech Platform Runtime 11 and engines for speech recognition and speech synthesis, the Speech Platform SDK 11 gives you the tools to create sophisticated speech applications for Windows Server while shortening development cycles and reducing development costs.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


What's New in the Microsoft Speech Platform SDK 11

[image]

What's New in the Microsoft Speech Platform SDK 11
Send Feedback

The following functionality has been recently added or updated in the Microsoft Speech Platform SDK .

VoiceXML Support

The managed-code Microsoft.Speech.VoiceXML namespace contains classes with which you can add the ability to process VoiceXML documents to your speech applications. The added functionality includes a VoiceXML runtime that interprets VoiceXML markup and a Browser class that allows users to communicate with a VoiceXML application. For more information, see VoiceXML Support (Microsoft.Speech).

Grammar Development Tools

The Microsoft Grammar Development Tools are a collection of command-line applications that you can use to test and optimize your voice applications without first deploying them to a live service. Using the Grammar Development Tools, you can do the following:

  • Create configuration files that select a speech recognition engine and set its properties.

  • Analyze grammars statically for errors.

  • Generate lists of phrases that a grammar will produce.

  • Find out whether a grammar contains a specific phrase.

  • Identify phrases in a grammar that may be confused with other phrases.

  • Perform simulated speech recognition on grammars.

  • Analyze recognition results for batches of utterances.

  • Compile grammar files to binary formats.

For more information, see Microsoft Grammar Development Tools.

Expanded Language Support

The Microsoft Speech Platform Runtime 11 now supports 26 languages. You must download and install a language pack for each language that you want to program against in your applications. There are separate language packs for speech recognition and speech synthesis. The version of the language packs you use for development, for example version 11.0, must match the version of the Speech Platform Runtime that you installed.

Use the following links to download language packs that match your Speech Platform Runtime version.

  • Microsoft Speech Platform - Server Runtime Languages v11.0

  • Microsoft Speech Platform - Server Runtime Languages v10.2

  • Microsoft Speech Platform - Server Runtime Languages v10.1

  • Microsoft Speech Platform - Server Runtime Languages v10.0 (13 languages only)

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Microsoft Speech Platform SDK 11 Requirements and Installation

[image]

Microsoft Speech Platform SDK 11 Requirements and Installation
Send Feedback

This page provides software and hardware requirements and installation instructions for the Microsoft Speech Platform Runtime 11 and the Microsoft Speech Platform SDK 11.

Software Requirements

The following operating systems provide support for the Speech Platform SDK 11.

Operating System | Edition | Processor Type
Windows Vista | All editions except Starter Edition | 32-bit, 64-bit
Windows 7 | All editions except Starter Edition | 32-bit, 64-bit
Windows Server 2008 | Service Pack 2 | 32-bit, 64-bit
Windows Server 2008 | R2 | 64-bit

Important note Important

All features and functionality of the Speech Platform SDK 11 (with the exception of the Microsoft Grammar Development Tools) are NOT supported by Windows XP.

Note Note

Development of speech-enabled applications is supported on:

  • Windows Vista or later

  • Windows 2003 Server or later

  • Windows 2008 Server or later

Deployment of speech-enabled applications is supported on:

  • Windows 2003 Server or later

  • Windows 2008 Server or later

Hardware Requirements

The following are the minimum and recommended hardware requirements for the .

Minimum Hardware Requirements

  • 1 GHz CPU

  • 512 MB RAM

  • 10 GB hard drive

  • Ethernet network adapter

  • DX9-compatible video card, with 2.0 pixel shader and vertex shader support (used by some of the graphics and user interface development tools included with the XDK)

  • USB 2.0

Recommended Hardware Configuration

  • Dual 2GHz CPU

  • 1 GB RAM

  • 40+ GB SATA hard drive

  • Ethernet network adapter

  • DX9-compatible video card, with 3.0 pixel shader and vertex shader support (when available)

  • Two USB 2.0 host controllers, which are required when you use DVD emulation and performance analysis tools simultaneously

Installing the Microsoft Speech Platform SDK 11

Use the following steps to install the Microsoft Speech Platform SDK 11.

To install the Microsoft Speech Platform SDK 11

  1. Uninstall any previous version of the Speech Platform SDK and the Microsoft Speech Platform Runtime from your computer.

  2. Verify that you have installed the Microsoft .NET Framework version 4.0. If necessary, download the .NET Framework 4.0 using this link. The .NET Framework must be installed before you install the Speech Platform Runtime 11 and the Speech Platform SDK 11.

  3. Determine whether you are using a 32-bit or 64-bit operating system.

  4. Download the Speech Platform Runtime 11 that matches your operating system using this link.

  5. Download the Speech Platform SDK 11 that matches your operating system using this link.

  6. Install the SpeechPlatformRuntime.msi.

  7. Install the MicrosoftSpeechPlatformSDK.msi.

Important note Important

The Speech Platform Runtime 11 and the Speech Platform SDK 11 do not include engines for speech recognition or for speech synthesis (TTS or text-to-speech). You must install them separately. You can download language packs containing engines for speech recognition and speech synthesis using this link. The version of language packs that you download (for example, version 11.0) must match the version of the Speech Platform Runtime that you have installed.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Speech Recognition (Microsoft.Speech)

[image]

Speech Recognition (Microsoft.Speech)
Send Feedback

The Microsoft.Speech.Recognition namespace provides functionality with which you can acquire and monitor speech input, create speech recognition grammars that produce both literal and semantic recognition results, capture information from events generated by the speech recognition and, and configure and manage speech recognition engines.

Speech Input

With the input functionality of speech recognition, your application can monitor the state, level, and format of the input signal, and receive notification about problems that might interfere with successful recognition. See Audio Input for Recognition (Microsoft.Speech).

Grammars

You can create grammars programmatically using constructors and methods on the GrammarBuilder and Choices classes. Your application can dynamically modify programmatically created grammars while it is running. The structure of grammars authored using these classes is independent of the Speech Recognition Grammar Specification (SRGS) 1.0. See Create Grammars Using GrammarBuilder (Microsoft.Speech).

To create dynamic grammars programmatically that conform to the SRGS specification, see Create Grammars Using SrgsGrammar (Microsoft.Speech). The classes of the Microsoft.Speech.Recognition.SrgsGrammar namespace map closely to the elements and attributes of the SRGS specification.

You can also create grammars as static files, using SRGS-compliant XML markup, that your application can load at runtime. See Create Grammars Using SRGS XML (Microsoft.Speech).

Use the constructors on the Grammar class to compile grammars created with any of the above methods into Grammar objects that the speech recognition can load and use to perform recognition.

Semantics

Recognition engines use the semantic information in grammars to interpret recognition results. To add semantic information to programmatically-created grammars, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech). You can add semantic information to XML-format grammars using ECMAScript (JavaScript, JScript) in the tag elements. See Semantic Interpretation Markup (Microsoft.Speech). For information about semantic results returned by speech recognition engines, see Create and Access Semantic Content (Microsoft.Speech).

Debugging Tools

The Microsoft Speech Platform SDK 11 includes a comprehensive suite of command-line tools with which you can test, debug, and optimize your voice applications without first deploying them to a live service. See Microsoft Grammar Development Tools for more information.

In addition, Microsoft.Speech has special emulated recognition modes that allow you to provide text instead of audio to the speech recognition engine. You can use the simulated recognition results for debugging and optimizing speech recognition grammars. See Emulate Spoken Commands (Microsoft.Speech).

Events

Your application can register for events that the speech recognition engine generates when completing important stages during speech processing such as loading grammars or recognizing speech. See Use Speech Recognition Events (Microsoft.Speech).

Recognition Engines

Using the members of the SpeechRecognitionEngine class, you can select a speech recognition engine, configure its input, start and stop recognition, load and unload grammars, and modify properties of the speech recognition engine that affect recognition. See Initialize and Manage a Speech Recognition Engine (Microsoft.Speech).

In addition, the speech engines for Microsoft.Speech will recognize the dual-tone multi-frequency (DTMF) tones that are important for developing applications that interact with users by telephone. See DTMF Recognition.

In This Section

  • How Speech Recognition Works (Microsoft.Speech)

  • Get Started with Speech Recognition (Microsoft.Speech)

  • Audio Input for Recognition (Microsoft.Speech)

  • Initialize and Manage a Speech Recognition Engine (Microsoft.Speech)

  • Use Speech Recognition Events (Microsoft.Speech)

  • Create and Access Semantic Content (Microsoft.Speech)

  • Emulate Spoken Commands (Microsoft.Speech)

  • Grammars Overview (Microsoft.Speech)

  • Create Grammars (Microsoft.Speech)

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


How Speech Recognition Works (Microsoft.Speech)

[image]

How Speech Recognition Works (Microsoft.Speech)
See Also Send Feedback

A speech recognition engine (or speech recognizer) takes an audio stream as input and turns it into a text transcription. The speech recognition process can be thought of as having a front end and a back end.

Convert Audio Input

The front end processes the audio stream, isolating segments of sound that are probably speech and converting them into a series of numeric values that characterize the vocal sounds in the signal.

Match Input to Speech Models

The back end is a specialized search engine that takes the output produced by the front end and searches across three databases: an acoustic model, a lexicon, and a language model.

  • The acoustic model represents the acoustic sounds of a language, and can be trained to recognize the characteristics of a particular user's speech patterns and acoustic environments.

  • The lexicon lists a large number of the words in the language, and provides information on how to pronounce each word.

  • The language model represents the ways in which the words of a language are combined.

For any given segment of sound, there are many things the speaker could potentially be saying. The quality of a recognizer is determined by how good it is at refining its search, eliminating the poor matches, and selecting the more likely matches. This depends in large part on the quality of its language and acoustic models and the effectiveness of its algorithms, both for processing sound and for searching across the models.

Grammars

While the built-in language model of a recognizer is intended to represent a comprehensive language domain (such as everyday spoken English), a speech application will often need to process only certain utterances that have particular semantic meaning to that application. Rather than using the general purpose language model, an application should use a grammar that constrains the recognizer to listen only for speech that is meaningful to the application. This provides the following benefits:

  • Increases the accuracy of recognition

  • Guarantees that all recognition results are meaningful to the application

  • Enables the recognition engine to specify the semantic values inherent in the recognized text

The Microsoft Speech Platform SDK 11 provides processes for authoring grammars programmatically, and also supports grammars authored using industry-standard markup language. See Create Grammars (Microsoft.Speech).

See Also

Concepts

Grammars Overview (Microsoft.Speech)
How Speech Synthesis Works (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Get Started with Speech Recognition (Microsoft.Speech)

[image]

Get Started with Speech Recognition (Microsoft.Speech)
Send Feedback

A speech recognition application will typically perform the following basic operations:

  • Start the speech recognizer.

  • Create a recognition grammar.

  • Load the grammar into the speech recognizer.

  • Register for speech recognition event notification.

  • Create a handler for the speech recognition event.

The following provides information about how to program each of these operations.

Start the Speech Recognizer

To start the speech recognizer, create a new SpeechRecognitionEngine instance. The following example does not show the declaration of the sre object.

C# Copy image Copy Code
// Create a new SpeechRecognitionEngine instance.
sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));

Create a Speech Recognition Grammar

One way to create a speech recognition grammar is to use the constructors and methods on the GrammarBuilder and Choices classes. The following example creates a simple grammar that recognizes the words "red", "green", or "blue". The words are added using a Choices object. For a match between user speech and the grammar to occur, the user must speak exactly one of the elements added by the Choices instance. Each of the words is added by a call to the Add(array<String>[]()[][]) method.

After the Choices instance is created and set with the option strings, the example creates a GrammarBuilder instance. Using the Append(Choices) method, the example appends the colors object to the GrammarBuilder instance. In the last line, the example creates a Grammar instance and initializes it with the GrammarBuilder instance.

C# Copy image Copy Code
Choices colors = new Choices();
colors.Add(new string[] {"red"});
colors.Add(new string[] {"green"});
colors.Add(new string[] {"blue"});

GrammarBuilder gb = new GrammarBuilder();
gb.Append(colors);

// Create the Grammar instance.
Grammar g = new Grammar(gb);

Alternatively, the first four lines of code can be collapsed to a single line by using the Choices constructor to initialize the instance with an array of string options, as follows:

Choices colors = new Choices(new string[] {"red", "green", "blue"});

For more information about creating grammars, see Create Grammars (Microsoft.Speech).

Load the Grammar into a Speech Recognizer

After the grammar is created, it must be loaded into the speech recognizer. The following example loads the grammar by calling the LoadGrammar(Grammar) method, passing the grammar created in the previous operation.

C# Copy image Copy Code
sre.LoadGrammar(g);

Register for Speech Recognition Event Notification

The speech recognizer raises a number of events during its operation, including the SpeechRecognized event. For more information, see Use Speech Recognition Events (Microsoft.Speech). The speech recognizer raises the SpeechRecognized event when it matches a user utterance with a grammar. An application registers for notification of this event by appending an EventHandler instance as shown in the following example. The argument to the EventHandler constructor, sre_SpeechRecognized, is the name of the developer-written event handler.

C# Copy image Copy Code
sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);

Create a Speech Recognition Event Handler

When you register a handler for a particular event, the Intellisense feature in Microsoft Visual Studio creates a skeleton event handler if you press the TAB key. This process ensures that parameters of the correct type are used. The handler for the SpeechRecognized event shown in the following example displays the text of the recognized word using the Result property on the SpeechRecognizedEventArgs parameter, e.

C# Copy image Copy Code
void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
  MessageBox.Show(e.Result.Text);
}

Speech Recognition Example

The following examples are components of a Windows System.Windows.Forms application that features speech recognition. Although the application displays a form when it starts, nothing of interest happens with the form. The first example contains the code for the handler for the form's Load event, which is raised when the form is loaded.

Almost everything of interest in this application occurs in the Form1_Load method. The method builds a grammar incrementally using a Choices instance to add the strings "red", "green", and "blue". It then creates a GrammarBuilder instance using the Choices object. The method then initializes a Grammar instance with the GrammarBuilder object created earlier. The grammar, which is capable of recognizing the words "red", "green", or "blue", is then loaded into the speech recognizer. Finally, the Form1_Load method registers an event handler for the SpeechRecognized()()()() event.

The sre_SpeechRecognized method, which executes when the speech recognizer raises the SpeechRecognized()()()() event, displays whichever of the three colors the user spoke. The following illustration shows the interaction between the user's speech and the speech recognizer with its grammar. When the utterance matches an element in the grammar, the speech recognizer makes a recognition, and produces a recognition result.

C# Copy image Copy Code
using Microsoft.Speech.Recognition;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

      // Create a new SpeechRecognitionEngine instance.
      sre = new SpeechRecognitionEngine();

      // Create a simple grammar that recognizes "red", "green", or "blue".
      Choices colors = new Choices();
      colors.Add(new string[] {"red", "green", "blue"});

      // Create a GrammarBuilder object and append the Choices object.
      GrammarBuilder gb = new GrammarBuilder();
      gb.Append(colors);

      // Create the Grammar instance and load it into the speech recognition engine.
      Grammar g = new Grammar(gb);
      sre.LoadGrammar(g);

      // Register a handler for the SpeechRecognized event.
      sre.SpeechRecognized +=
        new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);
    }

    // Create a simple handler for the SpeechRecognized event.
    void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      MessageBox.Show(e.Result.Text);
    }

    SpeechRecognitionEngine sre;
  }
}

The following example is autogenerated code for a Windows Forms application.

C# Copy image Copy Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  static class Program
  {

    // The main entry point for the application.
    [STAThread]
    static void Main()
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Form1());
    }
  }
}
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Audio Input for Recognition (Microsoft.Speech)

[image]

Audio Input for Recognition (Microsoft.Speech)
Send Feedback

Your application can configure and monitor the audio input to a speech recognition engine using the members and types described below.

Configure the Audio Input

Applications can configure a SpeechRecognitionEngine instance to receive input using any of the SetInputToAudioStream(Stream, SpeechAudioFormatInfo), SetInputToWaveFile(String), or SetInputToWaveStream(Stream) methods. In addition, you can set the input to null with the SetInputToNull()()()() method, which is useful for emulating recognition or to cancel another input setting. Currently the SetInputToDefaultAudioDevice()()()() has the same functionality as the SetInputToNull()()()() method.

Monitor the Audio Input

To get information about the level, format, and state of audio being received for recognition, an application can register handlers for events or query the properties of the SpeechRecognitionEngine class.

The AudioLevelUpdatedEventArgs class provides information about changes in the audio level when an AudioLevelUpdated event is raised. The AudioStateChangedEventArgs class provides information about changes in the state of the incoming audio when an AudioStateChanged event is raised, using a member of the AudioState enumeration.

In addition, the SpeechRecognitionEngine class has AudioLevel and AudioState properties that provide current information to the application. Detailed information about the format of the audio coming in to the speech recognition engine is available from the SpeechRecognitionEngine..::..AudioFormat property.

When an SpeechRecognitionEngine..::..AudioSignalProblemOccurred event is raised, applications can query the AudioSignalProblem property of the AudioSignalProblemOccurredEventArgs class to get a description of the problem.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Initialize and Manage a Speech Recognition Engine (Microsoft.Speech)

[image]

Initialize and Manage a Speech Recognition Engine (Microsoft.Speech)
Send Feedback

You can use the SpeechRecognitionEngine class to manage any speech recognition engine that is installed on the system. You will typically use a SpeechRecognitionEngine object to manage an installed speech recognition engine as follows:

  • Select and initialize an engine to use for speech recognition.

  • Configure and monitor the input to the speech recognition engine.

  • Configure parameters for recognition.

  • Register for notification of events and handle the events.

  • Load and unload speech recognition grammars.

  • Start, pause, and stop recognition operations.

Select and Initialize a Speech Recognition Engine

You can use the parameters provided by constructors of the SpeechRecognitionEngine class to select a an installed speech recognition engine that matches specific criteria, such as language-culture, the recognizer name, and other attributes.

Configure and Monitor the Input

You can configure the input to the SpeechRecognitionEngine to receive audio in a Wave stream, a Wave file, or an audio stream. See Audio Input for Recognition (Microsoft.Speech) for more information.

When the SpeechRecognitionEngine is receiving audio, you can monitor the incoming signal by querying the AudioState and AudioLevel properties and by registering a handler for the AudioSignalProblemOccurred event.

Configure Parameters for Recognition

To fine-tune how the recognizer responds to background noise and silence that accompanies speech input, set the values of the BabbleTimeout, EndSilenceTimeout, and EndSilenceTimeoutAmbiguous properties.

Speech recognition operations produce multiple recognition result candidates, evaluate the accuracy of each result candidate with respect to the spoken input, and return the recognition candidate that most likely matches the received speech. You can control the number of alternate recognition results that the speech engine returns by setting the MaxAlternates property. You can also query the settings of a speech recognition engine that affect recognition, such as confidence thresholds, using the QueryRecognizerSetting(String) method and modify those settings with one of the UpdateRecognizerSetting()()()() methods.

Register for Events and Author Handlers

The SpeechRecognitionEngine automatically raises events that return information to your application about the incoming signal, loading grammars, detecting speech, preliminary recognition results, final recognition results, and the end of a recognition operation. Your application can stay informed of the status and progress of recognition operations by registering for the SpeechRecognitionEngine's events. You can author code in the handlers for the events that creates an appropriate response by your application when events are received. See Use Speech Recognition Events (Microsoft.Speech).

The SpeechHypothesized, SpeechRecognized, SpeechRecognitionRejected, RecognizeCompleted events all return a RecognitionResult object that contains detailed information about the results of recognition. This information includes the Text of the recognized word or phrase, the Semantics associated with the recognition, the Confidence score assigned by the speech recognition engine, as well as other information.

Load and Unload Grammars

Load a Grammar object using the LoadGrammar(Grammar) or LoadGrammarAsync(Grammar) methods. You can unload a specific Grammar object using the UnloadGrammar(Grammar) method, or unload all currently loaded Grammar objects with a call to UnloadAllGrammars()()()(). If the SpeechRecognitionEngine is running, you can use one of the RequestRecognizerUpdate()()()() methods to pause it before loading or unloading Grammar objects.

Start, Pause, and Stop Recognition

To start recognition operation, use one of the Recognize()()()() or RecognizeAsync()()()() methods.

To stop an asynchronous recognition operation, use the RecognizeAsyncCancel()()()() or RecognizeAsyncStop()()()() methods.

You can pause a running SpeechRecognitionEngine instance to update its configuration or to load and unload grammars using one of the RequestRecognizerUpdate()()()() methods.

The SpeechRecognitionEngine can perform an additional mode of recognition (called emulation) during which it accepts text, rather than speech, as input. Emulated recognition can be useful for debugging grammars. The speech recognizer raises the SpeechDetected, SpeechHypothesized, SpeechRecognitionRejected, and SpeechRecognized events as if the recognition operation is not emulated. To initiate emulated recognition, call one of the EmulateRecognize()()()() or EmulateRecognizeAsync()()()() methods and pass in text or an array of words for which you want to perform emulated recognition.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Use Speech Recognition Events (Microsoft.Speech)

[image]

Use Speech Recognition Events (Microsoft.Speech)
Send Feedback

During speech recognizer run-time operations, the recognizer raises a number of events for which applications can register to be notified. For each event the application intends to handle, it must provide a handler for that event. For more information, see the example at the end of this topic.

The SpeechRecognitionEngine class provides the following events.

Event | Description
AudioLevelUpdated | Raised when a change in the audio level is detected.
AudioSignalProblemOccurred | Raised when an error is detected in a SpeechRecognitionEngine instance.
AudioStateChanged | Raised when a change in the current state of the audio input in a recognition engine is detected.
EmulateRecognizeCompleted | Raised when an asynchronous emulation of speech recognition is finished.
LoadGrammarCompleted | Raised when the asynchronous loading of a Grammar object into a speech recognizer is finished.
RecognizeCompleted | Raised when an asynchronous recognition operation completes.
RecognizerUpdateReached | Raised when the Windows Desktop Speech Technology recognition engine pauses to allow an atomic update that is requested by one of the RequestRecognizerUpdate()()()() overloaded methods.
SpeechDetected | Raised when speech is detected.
SpeechHypothesized | Raised when the recognition engine detects speech and part of the audio input speech is tentatively recognized.
SpeechRecognitionRejected | Raised when the recognition engine detects speech, but is able to return only candidate phrases that have low confidence levels.
SpeechRecognized | Raised when the recognition detects speech, and has found one or more phrases with sufficiently high confidence levels.

AudioLevelUpdated

A recognizer raises this event when the audio level changes. This event is associated with the AudioLevelUpdatedEventArgs class, which contains the AudioLevel property.

AudioSignalProblemOccurred

A recognizer raises this event when there is a problem with the audio signal. The kinds of problems that are reported are values in the AudioSignalProblem enumeration. This event is associated with the AudioSignalProblemOccurredEventArgs class, which contains properties that provide information about the audio signal problem: the audio level (AudioLevel), the position in the input device's audio stream at which the problem occurred (AudioPosition), the particular audio signal problem (AudioSignalProblem), and the position in the recognizer's audio stream at which the problem occurred (RecognizerAudioPosition).

AudioStateChanged

A recognizer raises this event when the audio state changes from one value in the AudioState enumeration to another (such as from Speech to Silence). This event is associated with the AudioStateChangedEventArgs class, which contains the new audio state of the recognizer (AudioState).

EmulateRecognizeCompleted

A recognizer raises this event on completion of one of the EmulateRecognizeAsync()()()() overloaded methods. This event is associated with the EmulateRecognizeCompletedEventArgs class, which returns the recognition result (Result).

LoadGrammarCompleted

A recognizer raises this event on completion of the asynchronous loading of a grammar. This event is associated with the LoadGrammarCompletedEventArgs class, which contains a property that is a reference to the grammar that was loaded (Grammar).

RecognizeCompleted

A recognizer raises this event on the completion of an asynchronous recognition operation initiated by calls to the RecognizeAsync()()()() overloaded methods. This event is associated with the RecognizeCompletedEventArgs class, which contains several properties that describe the recognition operation.

RecognizerUpdateReached

A recognizer raises this event when it receives a request to update its state. An application makes this request using one of the RequestRecognizerUpdate overloaded methods on the SpeechRecognitionEngine class (the RequestRecognizerUpdate()()()() overloads). This event is associated with the RecognizerUpdateReachedEventArgs class, which contains a property for the audio position (AudioPosition) and a user token property (UserToken).

SpeechDetected

A recognizer raises this event when it detects speech in the input audio. This event is associated with the SpeechDetectedEventArgs class, which contains a property that indicates the audio position at which speech occurs (AudioPosition).

SpeechHypothesized

A recognizer raises this event when it detects speech and a portion of the speech is tentatively recognized. This event is associated with the SpeechHypothesizedEventArgs class, which contains the Result property (inherited from the RecognitionEventArgs class).

SpeechRecognitionRejected

A recognizer raises this event when it detects speech, but returns only candidate phrases with low confidence levels. This event is associated with the SpeechRecognitionRejectedEventArgs class, which contains the Result property (inherited from the RecognitionEventArgs class).

SpeechRecognized

A recognizer raises this event when it detects speech, and has found one or more phrases with sufficiently high confidence levels. This event is associated with the SpeechRecognizedEventArgs class, which contains the Result property (inherited from the RecognitionEventArgs class).

Example

The method in the following example creates a SpeechRecognitionEngine instance named recognizer. The example then registers event handlers for the LoadGrammarCompleted, SpeechDetected, SpeechHypothesized, SpeechRecognized, and RecognizeCompleted events. Following this method are simple event handlers for these events. The variable recognizer is a SpeechRecognitionEngine instance that is assumed to be declared at the class level.

C# Copy image Copy Code
  static void Main(string[] args)
  {
    recognizer = new SpeechRecognitionEngine();
    recognizer.LoadGrammarCompleted += new EventHandler<LoadGrammarCompletedEventArgs>(recognizer_LoadGrammarCompleted);
    recognizer.SpeechDetected += new EventHandler<SpeechDetectedEventArgs>(recognizer_SpeechDetected);
    recognizer.SpeechHypothesized += new EventHandler<SpeechHypothesizedEventArgs>(recognizer_SpeechHypothesized);
    recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
    recognizer.RecognizeCompleted += new EventHandler<RecognizeCompletedEventArgs>(recognizer_RecognizeCompleted);
  }
C# Copy image Copy Code
  static void recognizer_LoadGrammarCompleted(object sender, LoadGrammarCompletedEventArgs e)
  {
    Console.WriteLine("Grammar loaded:  " + e.Grammar.Name);
  }

  static void recognizer_SpeechDetected(object sender, SpeechDetectedEventArgs e)
  {
    Console.WriteLine("Speech detected at audio position: " + e.AudioPosition);
  }

  static void recognizer_SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
  {
    Console.WriteLine("Speech hypothesized: " + e.Result.Text);
  }

  static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
  {
    Console.WriteLine("Speech recognized:  " + e.Result.Text);
  }

  static void recognizer_RecognizeCompleted(object sender, RecognizeCompletedEventArgs e)
  {
    Console.WriteLine("Recognize completed at audio position: " + e.AudioPosition);
  }
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Create and Access Semantic Content (Microsoft.Speech)

[image]

Create and Access Semantic Content (Microsoft.Speech)
See Also Send Feedback

While performing recognition, a speech recognition engine returns recognition results to the speech application that include semantic information about the recognized speech input, as well as the text of recognized words and phrases. The semantic information contained in a recognition result is often more meaningful to an application than the recognized text. You can author semantic content and the code that retrieves semantics from recognition results to provide actionable information to your application.

Create Semantic Content

Although the speech recognition engine generates some semantic content by default, you can create the semantic structure for recognized speech by assigning the semantic values and semantic keys that the speech recognition engine returns in the recognition result. The mechanism for authoring semantic content depends on the process you use to author a grammar.

Create Dynamic Grammars Programmatically

  • For grammars created programmatically using the GrammarBuilder and Choices classes, you can assign semantic values using the Append(SemanticResultValue) method and assign semantic keys using the Append(SemanticResultKey) method. You can assign semantic value to items in a list within a Choices object by passing a SemanticResultValue object to the Add(array<GrammarBuilder>[]()[][]) method. For more information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

  • For grammars created programmatically using classes of the Microsoft.Speech.Recognition.SrgsGrammar namespace, you can assign semantic content using the constructors on the SrgsSemanticInterpretationTag class.

Create Static Grammars as Files

  • For grammars created in XML-format that comply with Speech Recognition Grammar Specification (SRGS) Version 1.0, you enter semantic content in tag elements (tag Element (Microsoft.Speech)) that are a children of either an item Element (Microsoft.Speech) or a rule Element (Microsoft.Speech). For more information, see Using the tag Element (Microsoft.Speech).

Access the Recognition Result

An application registers to be notified of events that the speech recognition engine raises when it is processing speech input. A SpeechRecognitionEngine instance raises the SpeechHypothesized, SpeechRecognitionRejected or SpeechRecognized, and RecognizeCompleted events to provide information about a recognition operation. Event arguments for these events are provided by, respectively, the SpeechHypothesizedEventArgs, SpeechRecognitionRejectedEventArgs, SpeechRecognizedEventArgs, and RecognizeCompletedEventArgs classes. All of these classes inherit from the RecognitionEventArgs class. Importantly, all these classes inherit the Result property on RecognitionEventArgs.

You can access the Result property using the second parameter, which is usually named e, on the event handler. The following example shows an empty handler for the SpeechRecognized event. Event handlers for the SpeechHypothesized, SpeechRecognitionRejected, and RecognizeCompleted events are similar.

C# Copy image Copy Code
void sr_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
  // Handle SpeechRecognized event.
}

The Result property is a reference to a RecognitionResult instance, which has properties that contain information about alternate recognition results, the audio associated with the recognized phrase, the degree of certainty for the recognized phrase, and a number of other items of interest about the recognized phrase.

Access the Semantics in the Recognition Result

Semantics is an important property of RecognitionResult that contains a reference to a SemanticValue instance, which can be thought of as a collection of key/value pairs that represents the semantic organization of a recognized phrase. You can access the keys and values for the semantics of a recognition result using the IDictionary<(Of <<'(String, SemanticValue>)>>)..::..Keys and IDictionary<(Of <<'(String, SemanticValue>)>>)..::..Values properties, respectively.

The following illustration shows the properties on RecognitionResult and SemanticValue classes, which you can access using the Result property.

See Also

Reference

RecognizedPhrase

Concepts

Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech)
Use a SemanticResultKey to Extract a SemanticResultValue (Microsoft.Speech)
Semantic Interpretation Markup (Microsoft.Speech)
Semantic Markup Language Reference (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Emulate Spoken Commands (Microsoft.Speech)

[image]

Emulate Spoken Commands (Microsoft.Speech)
Send Feedback

Emulation of spoken commands is useful for debugging a speech recognition application during its development. The EmulateRecognize()()()() and EmulateRecognizeAsync()()()() overloaded methods on the SpeechRecognitionEngine class can be used to programmatically emulate speech.

Example

The following example shows a speech recognition engine loading a simple grammar that can recognize "hello world". It then calls EmulateRecognize(String) to send the string "hello world" to the speech recognition engine, which should return that text as the recognized string within the RecognitionResult object.

C# Copy image Copy Code
namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));
      GrammarBuilder gb = new GrammarBuilder("Hello world");
      Grammar g = new Grammar(gb);
      sre.LoadGrammar(g);
      RecognitionResult rr = sre.EmulateRecognize("Hello world");
      if (rr != null && rr.Text != null)
      {
        Console.WriteLine("Recognized: " + rr.Text);
      }
      Close();
    }

    SpeechRecognitionEngine sre;
  }
}
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammars Overview (Microsoft.Speech)

[image]

Grammars Overview (Microsoft.Speech)
Send Feedback

Speech recognition requires a speech recognition engine, speech input, and a grammar. A speech recognition grammar consists of a structured list of rules that identify words or phrases that the speech recognition engine should attempt to identify in the spoken input.

Grammar rules can identify simple one-word commands, such as "Open" or "Print", and more complex sentence structures such as "I'd like to book a flight from Seattle to Denver, departing next Tuesday". Grammars typically define a limited vocabulary that is focused on a specific task or set of tasks that a user expects to be able to accomplish by speaking.

A grammar must define structured, logical speech statements that apply to specific situations. At the same time, a grammar must be flexible enough to allow slight variations in spoken input to enable a more natural speaking style and to provide a better user experience. For example, a coffee ordering application must accept and respond to multiple ways that a user can order coffee:

  • "I would like a decaf latte"

  • "I want a decaf latte"

  • "Gimme a decaf latte"

A coffee ordering application must also process and respond to orders for different types of coffee drinks in multiple variations. For example, an application must be able to substitute the word "latte" for "cappuccino" or "mocha" and must be able to insert variations of those drinks such as "decaf" or "iced." However, a coffee ordering application does not need to process and respond to orders for airline tickets; a grammar need only include words and phrases for a specific situation or task.

You can use rules and semantic definitions to organize a grammar's content into logical groupings. This reduces the amount of work that an application needs to perform during recognition by decreasing the amount of information that the application must process and by returning only the most actionable information.

This section contains conceptual information about grammars, including their role in recognition, descriptions of grammar elements, and options for authoring grammars in the Microsoft Speech Platform SDK 11.

In This Section

  • About Speech Recognition Grammars (Microsoft.Speech)

  • Purpose of Grammars (Microsoft.Speech)

  • Grammar Authoring Processes (Microsoft.Speech)

  • Grammar Rules (Microsoft.Speech)

  • Introduction to XML Grammar Elements (Microsoft.Speech)

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


About Speech Recognition Grammars (Microsoft.Speech)

[image]

About Speech Recognition Grammars (Microsoft.Speech)
See Also Send Feedback

A speech recognition engine matches spoken input to words and phrases that are defined by the rules in a speech recognition grammar. A simple grammar can be designed to recognize a small set of phrases. A more complex grammar can be designed to recognize and organize semantic content from a variety of user utterances. A speech recognition grammar also defines a set of properties that are specific to the grammar, such as locale, semantic format, and mode.

Rules

A speech recognition grammar contains one or more rules. Each rule defines a set of language constraints that a speech recognition engine uses to restrict the possible word or sentence choices during the speech recognition process. Speech recognition engines use grammar rules to control the elements of sentence construction using a predetermined list of recognized word or phrase choices. For more information, see Grammar Rules (Microsoft.Speech) and rule Element (Microsoft.Speech).

A grammar can define which rules are active when the grammar loads. For XML-format grammars that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0 and grammars created using members of the Microsoft.Speech.Recognition.SrgsGrammar namespace, the grammar designates one rule as the root rule of the grammar, which is active when the grammar loads. Any rules that the root rule references are also active when the grammar loads.

States and Transitions

Each rule in a grammar can be represented as a directed graph data structure that describes all of the possible phrases defined by that rule. The graph can be presented as a set of states, each with a set of possible transitions to other states. Each rule is defined by a single start state, a single end state, and a set of zero or more intermediate states.

The following illustration shows a graph representation of a rule that recognizes sentences such as "Today is Monday" and "Tomorrow will be Tuesday" or any other valid paths through the rule. A speaker must first say any of three different words "Yesterday", "Today", or "Tomorrow", causing a transition to, respectively, State 1, State 2, or State 3. From any of these intermediate states, a specific word must be spoken to cause a transition to the next intermediate state, State 4. From State 4, the user can say the name of any day of the week (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday) to cause a transition to the end state of the rule.

Rule Reference Transitions

All of the transitions between states in the preceding illustration occur as a result of an application user speaking the word shown in the transition arc. In addition to representing words, transitions can also represent references to other rules within the grammar. For example, instead of listing the names of the days of the week explicitly, the rule represented in the preceding illustration could have had a reference to a DayName rule as the transition from State 4 to the end state. For more information about rule references, see ruleref Element (Microsoft.Speech), the SrgsRuleRef class, the AppendRuleReference()()()() methods, and Grammar Rule Reference Referencing (Microsoft.Speech).

Properties of Grammars

You can set the properties of grammars to optimize them for specific recognition environments and tasks. For example, grammar properties specify the language that the grammar contains, whether the grammar is used for recognizing speech or dial tones, which of the grammar's rules to use, and the format for the grammar's semantic content.

How you specify a grammar's properties depends on the authoring format.

  • You specify the properties for grammars created using the GrammarBuilder class by setting properties on the class.

  • You specify the properties for grammars created using members of the Microsoft.Speech.Recognition.SRGSGrammar namespace by setting values for SrgsDocument properties.

  • You specify the properties for SRGS-compliant, XML-format grammars by entering values for attributes and elements within the grammar Element (Microsoft.Speech).

Whether the authoring format is GrammarBuilder, Microsoft.Speech.Recognition.SRGSGrammar, or XML, a completed grammar must be built into a Grammar object, using one of the constructors on the class, before it can be loaded by a speech recognition engine. A Grammar object has additional properties that describe whether the grammar is loaded by a speech recognition engine, whether it is enabled for recognition, its priority relative to other grammars, its weight (degree of influence) in ranking of recognition alternatives, and other properties.

See Also

Concepts

Purpose of Grammars (Microsoft.Speech)
Grammar Authoring Processes (Microsoft.Speech)
Create Grammars Using GrammarBuilder (Microsoft.Speech)
Create Grammars Using SrgsGrammar (Microsoft.Speech)
Create Grammars Using SRGS XML (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Purpose of Grammars (Microsoft.Speech)

[image]

Purpose of Grammars (Microsoft.Speech)
Send Feedback

A speech recognition grammar is a container of language rules that define a set of constraints that a speech recognizer can use to perform recognition. These rules provide the guidelines that an application uses when collecting spoken input.

A grammar helps an application perform speech recognition in the following ways:

  • Limits Vocabulary. A grammar contains only the exact words or phrases that an application needs to match for successful recognition of spoken input. An application might need to recognize only a few words that appear in a grammar structure, therefore, the speech recognition engine does not need to search the entire dictionary. Explicitly providing words in a grammar also improves the recognition accuracy, because the speech recognition engine must process speech only to the extent of confirming a match.

  • Customizes Vocabulary. A grammar customizes a vocabulary for a particular application. Although grammar structures need to be flexible and accommodate a multitude of phrases and phrasing, grammar structures also need to restrict the spoken input to a specific situation or task. Each application has its own natural language. A coffee ordering system, for example, concentrates on language used to order coffee, not language used to order airline tickets.

  • Filters Recognition Results. A grammar filters the results of recognition that are sent to an application. The speech recognition engine processes all audio signals it receives, regardless of what is contained in the grammars. The engine identifies and matches a word or phrase in the spoken input with a word or phrase defined in the grammar. The advantage of a grammar is that the speech recognition engine returns a successful recognition event only if the grammar is matched. Otherwise, the application would receive many additional recognition results, few of which have meaning to the application.

  • Identifies Rules. Each rule in a grammar contains an identifier (ID) that is unique within the grammar. When a successful recognition occurs, the speech recognition engine processes the rule ID as part of the recognition result and passes this information back to the speech application.

    A grammar may define all the variations for expressing a specific intent in a single rule, which has a unique name. For example, an application may allow a customer to order coffee by saying any of the following:

    • "I would like a coffee"

    • "I'd like coffee"

    • "Get me a coffee"

    • "Coffee please"

    Each phrase is different, but the intent is the same: the customer wants coffee. It makes no difference which phrase in the rule is actually spoken. If the spoken phrase is defined within that rule, the rule is considered successfully matched by the application. The speech recognition engine returns the recognition back to the application with a single rule name. The application uses that name to process the coffee order. For more information, see Grammar Rules (Microsoft.Speech).

  • Defines Semantics. A grammar can assign an alternate meaning (semantic) to a word or phrase used to recognize spoken input. The semantic meaning of a word or phrase can be more useful to an application than its literal content. For example, a grammar may assign a semantic meaning of "yes" to any of the speech inputs "yeah", "yup", "yep" "affirmative", or "uh-huh". The semantics assigned to a word or phrase by a grammar are returned in the recognition result when that word or phrase is recognized. Semantics allow an application to identify and parse the text returned by recognition. For more information, see Using the tag Element (Microsoft.Speech), Referencing Grammar Rule Variables (Microsoft.Speech), SML Output Overview (Microsoft.Speech) and Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Authoring Processes (Microsoft.Speech)

[image]

Grammar Authoring Processes (Microsoft.Speech)
Send Feedback

You can author grammars for applications based on Microsoft.Speech using any of the following processes:

  • Create Dynamic Grammars Programmatically

    • Author grammars programmatically using members of the GrammarBuilder and Choices classes in the Microsoft.Speech.Recognition namespace.

    • Use constructors and methods on classes in the Microsoft.Speech.Recognition.SrgsGrammar namespace to programmatically create SRGS-compliant grammars.

  • Create Static Grammars as Files

    • Use XML to create grammar documents that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0, the W3C standard for speech recognition grammars.

Create Dynamic Grammars Programmatically

Use the following to create grammars within the code of your speech application.

GrammarBuilder and Choices

The GrammarBuilder and Choices classes in the Microsoft.Speech.Recognition namespace provide methods for programmatically creating grammar definitions that do not rely on or conform to the SRGS specification. This lightweight, programmatic approach to authoring grammars will efficiently accomplish many common tasks for grammar creation. Authoring with GrammarBuilder is best suited to grammars that have a single rule containing lists, or perhaps lists of lists. See Create Grammars Using GrammarBuilder (Microsoft.Speech).

To programmatically build grammars that have multiple rules, or that need to make internal rule references, use the classes of the Microsoft.Speech.Recognition.SrgsGrammar namespace.

SrgsGrammar Namespace

The classes of the Microsoft.Speech.Recognition.SrgsGrammar namespace map closely to the elements and attributes defined by the SRGS specification. Using members of the Microsoft.Speech.Recognition.SrgsGrammar namespace, you can programmatically create SRGS-compliant grammars and even write the results to an XML file. In addition, you can build a grammar in the Microsoft.Speech.Recognition.SrgsGrammar namespace from an XML-format grammar document or from a GrammarBuilder object. See Create Grammars Using SrgsGrammar (Microsoft.Speech).

Create Static Grammars as Files

Use the following to create grammars as static files, external to your speech application's code. Your speech application can load external grammar files at runtime.

SRGS XML Format

The SRGS specification defines the structure of grammars and grammar rules that use XML markup. Using a text editor, you can add XML elements, XML attributes, and plain text to define the content and sequence of the spoken input or dial tones that the grammar will recognize. A typical use for static grammars is to store lists of data that does not change frequently, for example lists of cities or grammars that process phone numbers. See Create Grammars Using SRGS XML (Microsoft.Speech) and SRGS Grammar XML Reference (Microsoft.Speech).

Building Grammar Objects

After creating a grammar using any of the processes described above, you must build the grammar into a Grammar object, using a constructor on the class. A SpeechRecognitionEngine instance will only load grammars as Grammar objects.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Rules (Microsoft.Speech)

[image]

Grammar Rules (Microsoft.Speech)
See Also Send Feedback

The basic unit of a speech recognition grammar is the rule. A grammar rule defines a pattern or sequence of words or phrases. If the user's statement matches that pattern, the rule is matched by the application. A grammar must contain at least one rule.

A grammar rule has an identifier that distinguishes it from other rules and that provides a handle by which other rules can reference it. A grammar rule's identifier must be unique within a containing grammar.

Rules can contain references to other rules within the same grammar or to rules contained in a separate grammar. A grammar can expose rules for use externally by other grammars. This concept is very similar to the software concept of public or private scoping. Rules that are publicly scoped can be used by other grammars. Rules that are designated as private can only be used by the grammar in which they exist.

The definition of a grammar rule can also include semantic content, which is information about the words and phrases recognized by the speech recognition engine. For more information, see Create and Access Semantic Content (Microsoft.Speech) and Semantic Interpretation Markup (Microsoft.Speech).

Although the GrammarBuilder and Choices classes do not explicitly define a rule construct, their contents serve the same function as rules in SRGS-compliant grammars: to define the language constraints and the semantic content for speech recognition.

Examples

Each of the following examples creates the same rule in a grammar using one of the three authoring processes: XML-format grammar, Microsoft.Speech.Recognition.SrgsGrammar namespace, and GrammarBuilder class. The rule matches input phrases such as the following:

  • "Find albums in the jazz category"

  • "Find artists in the rock category"

The category selection is made by a rule reference to a second rule in the grammar, named genres.

XML Format

This first example builds a grammar using the XML format defined by the Speech Recognition Grammar Specification (SRGS) Version 1.0.

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" mode="voice" root="mediaMenu"
xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="mediaMenu" scope="public">

  Find

    <one-of>
      <item> albums </item>
      <item> artists </item>
    </one-of>

  in the

    <ruleref uri="#genres"/>

  category.

  </rule>

  <rule id="genres" scope="public">
    <one-of>
      <item> Blues </item>
      <item> Classical </item>
      <item> Gospel </item>
      <item> Jazz </item>
      <item> Rock </item>
    </one-of>
  </rule>
</grammar>

Given the file name "MediaMenuGrammar.grxml", the XML grammar above can be built into a Grammar object using the following code snippet:

Copy image Copy Code
// Build a Grammar object from the XML grammar.
Grammar mediaMenuGrammar = new Grammar("C:\\MediaMenuGrammar.grxml");

SRGSGrammar Namespace

The example that follows uses classes of the Microsoft.Speech.Recognition.SrgsGrammar namespace to build the same grammar as in the previous example. The classes of the Microsoft.Speech.Recognition.SrgsGrammar namespace match closely to the elements and attributes defined by the SRGS specification.

C# Copy image Copy Code
SrgsDocument mediaMenu = new SrgsDocument();

// Create rules and one-of elements.
SrgsRule displayList = new SrgsRule("selectList");
displayList.Scope = SrgsRuleScope.Public;
SrgsRule genres = new SrgsRule("musicGenres");
genres.Scope = SrgsRuleScope.Public;
SrgsOneOf listTypes = new SrgsOneOf(new string[] {"albums", "artists"});
SrgsOneOf genreTypes = new SrgsOneOf(new string[] {"blues", "classical", "gospel", "jazz", "rock"});
genres.Add(genreTypes);

// Add the rules to the grammar and set the root rule.
mediaMenu.Rules.Add(displayList);
mediaMenu.Rules.Add(genres);
mediaMenu.Root = displayList;

// Assemble the grammar components.
displayList.Elements.Add(new SrgsItem ("Find"));
displayList.Elements.Add(listTypes);
displayList.Elements.Add(new SrgsItem("in the"));
displayList.Elements.Add(new SrgsRuleRef(genres));
displayList.Elements.Add(new SrgsItem("category."));

// Build a Grammar object from the SrgsDocument.
Grammar mediaMenuGrammar = new Grammar(mediaMenu);

GrammarBuilder Class

The following example uses the GrammarBuilder and Choices classes in the Microsoft.Speech.Recognition namespace to build a grammar that is functionally identical to the previous two examples. The Choices class serves the same function as the one-of element in SRGS-compliant grammars.

C# Copy image Copy Code
//  Create lists of alternative choices.
Choices listTypes = new Choices(new string[] {"albums", "artists"});
Choices genres = new Choices(new string[] {"blues", "classical", "gospel", "jazz", "rock"});

// Create a GrammarBuilder object and assemble the grammar components.
GrammarBuilder mediaMenu = new GrammarBuilder("Find");
mediaMenu.Append(listTypes);
mediaMenu.Append("in the");
mediaMenu.Append(genres);
mediaMenu.Append("category.");

// Build a Grammar object from the GrammarBuilder.
Grammar mediaMenuGrammar = new Grammar(mediaMenu);

Remarks

Each of the completed grammars in the examples above must be built into a Grammar object before it can be loaded by a speech recognition engine. You can build an XML-format grammar into a Grammar object using the path and file name of the grammar as a string argument to the constructor.

See Also

Concepts

Grammar Authoring Processes (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Introduction to XML Grammar Elements (Microsoft.Speech)

[image]

Introduction to XML Grammar Elements (Microsoft.Speech)
See Also Send Feedback

An XML-format grammar consists of rule elements which define the speech input that a speech recognition engine will recognize. Rule elements contain the sets of words or phrases that the speech recognition engine uses to match user input, and also specify the required sequence of phrases that a user can speak. Any of the grammar elements or unmarked text sequences within a rule element is called a rule expansion.

A grammar rule must contain at least one rule expansion that contains text that a user can speak. You place elements, such as item elements, token elements, and ruleref elements (which contain references to other rules, including those in other grammars) in a specific sequential order. This allows grammars to offer multiple variations of word combinations that can be recognized.

Examples

The following information describes some commonly used grammar elements.

  • item element. May contain a word that can be spoken, a ruleref element, a tag element, or any logical combination of these.

    When an item element contains a combination of rule expansions (for example, a combination of words), the sequence of the words in that item element must match the sequence of the words spoken by the user for recognition to be successful. For example, given the following grammar, the spoken input must contain the phrase "metallic red" for recognition to be successful.

    XML Copy image Copy Code
    <grammar version="1.0" xml:lang="en-US" mode="voice" root="ruleColors"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="ruleColors" scope="public">
    <item> metallic red </item>
  </rule>

</grammar>

    See item Element (Microsoft.Speech) for more information.

  • one-of element. Contains a set of alternative rule expansions, any of which can be used to recognize spoken input. This increases the flexibility of the grammar by requiring that the input match only one of the alternatives. For example, in the following grammar, the input must contain the initial phrase "I would like the car in" for recognition to be successful. However, the phrase can be completed by any of the words: "red", "white", or "green".

    XML Copy image Copy Code
    <grammar version="1.0" xml:lang="en-US" mode="voice" root="ruleColors"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="ruleColors" scope="public">
    <item> I would like the car in </item>
    <one-of>
      <item> red </item>
      <item> white </item>
      <item> green </item>
    </one-of>
  </rule>

</grammar>

    See one-of Element (Microsoft.Speech) for more information.

  • ruleref element. Specifies a pointer to another rule that spoken input must match as part of a successful recognition of the current rule.

    Grammars reference rules using ruleref elements.The following example defines a rule element named ruleColors that contains alternative selections for colors. The root rule, buyShirt, then uses a ruleref element to reference the ruleColors rule twice.

    XML Copy image Copy Code
    <grammar version="1.0" xml:lang="en-US" mode="voice" root="buyShirt"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="buyShirt" scope="public">
    <item>
      Get me a <ruleref uri="#ruleColors" />
      shirt and a <ruleref uri="#ruleColors"/>
      tie
    </item>
  </rule>

  <rule id="ruleColors" scope="public">
    <one-of>
      <item> red </item>
      <item> white </item>
      <item> green </item>
    </one-of>
  </rule>

</grammar>

    The customer requests a color item twice, but the grammar need define ruleColors only once.

See ruleref Element (Microsoft.Speech) for more information.

See Also

Concepts

Create Grammars Using SRGS XML (Microsoft.Speech)
SRGS Grammar XML Reference (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Create Grammars (Microsoft.Speech)

[image]

Create Grammars (Microsoft.Speech)
Send Feedback

Grammars are at the core of speech recognition and are perhaps the most important component under control of the speech application developer that affects the accuracy of speech recognition. Grammars work in conjunction with the speech recognition engine and its lexicons and speech models to define the factors that affect speech recognition performance.

The Microsoft Speech Platform SDK 11 provides programmatic processes for authoring speech recognition grammars and also offers support for XML-format grammars authored in compliance with industry standards.

You can create speech recognition grammars in the Speech Platform SDK 11 using any of the following processes:

  • Create Dynamic Grammars Programmatically

    • Author grammars programmatically using members of the GrammarBuilder and Choices classes in the Microsoft.Speech.Recognition namespace.

    • Use constructors and methods on classes in the Microsoft.Speech.Recognition.SrgsGrammar namespace to programmatically create SRGS-compliant grammars.

  • Create Static Grammars as Files

    • Use XML to create grammar documents that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0, the W3C standard for speech recognition grammars.

In This Section

  • Create Grammars Using GrammarBuilder (Microsoft.Speech)

  • Create Grammars Using SrgsGrammar (Microsoft.Speech)

  • Create Grammars Using SRGS XML (Microsoft.Speech)

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Create Grammars Using GrammarBuilder (Microsoft.Speech)

[image]

Create Grammars Using GrammarBuilder (Microsoft.Speech)
Send Feedback

The GrammarBuilder class provides a lightweight, programmatic approach to authoring grammars that is powerful enough to meet the requirements of many common speech recognition scenarios.

Using constructors and methods on the GrammarBuilder class, you can create individual phrases from strings, SemanticResultValue objects, and wildcards. You can combine these phrases with instances of Choices objects, which you can use to create lists of alternative words and phrases, any one of which may be used in recognition. You can also use a GrammarBuilder object to incorporate rules from external XML-format grammar files using a rule reference to the file or to a specific rule within the file.

Authoring with GrammarBuilder is best suited to grammars that have a single rule containing lists, or perhaps lists of lists. Grammars that have multiple rules, or that need to make internal rule references should be built using the Microsoft.Speech.Recognition.SrgsGrammar classes instead. For more information, see Create Grammars Using SrgsGrammar (Microsoft.Speech).

In This Section

  • Use a String to Create a GrammarBuilder (Microsoft.Speech)

  • Use a Choices Object to Create a GrammarBuilder (Microsoft.Speech)

  • SetMinimum and Maximum Repeat Values (Microsoft.Speech)

  • Add Content Using GrammarBuilder Methods (Microsoft.Speech)

  • Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech)

  • Use a SemanticResultKey to Extract a SemanticResultValue (Microsoft.Speech)

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Use a String to Create a GrammarBuilder (Microsoft.Speech)

[image]

Use a String to Create a GrammarBuilder (Microsoft.Speech)
See Also Send Feedback

You can use GrammarBuilder to create a simple grammar that will recognize a single word or short phrase. When a user of your application speaks the word or phrase, the speech recognition engine performs recognition by matching the user's utterance to phrase defined by the GrammarBuilder.

The following code fragment uses the GrammarBuilder(String) constructor to create a recognizable phrase from a string:

C# Copy image Copy Code
GrammarBuilder gb = new GrammarBuilder("one two three");

Strings serve as a starting point for building complex grammars using the methods and constructors on the GrammarBuilder class.

See Also

Concepts

Create Grammars Using GrammarBuilder (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Use a Choices Object to Create a GrammarBuilder (Microsoft.Speech)

[image]

Use a Choices Object to Create a GrammarBuilder (Microsoft.Speech)
See Also Send Feedback

You can use a Choices instance to represent an element in a phrase that can have one of several values. You incorporate each of the possible values into the Choices instance.

The following example creates a simple GrammarBuilder grammar that recognizes "The card suit is <suit>"; where <suit> is a placeholder that can be replaced by "hearts", "diamonds", "clubs", or "spades" during speech recognition. The possible values for <suit> are created by the Choices(array<String>[]()[][]) constructor, which takes an array of String objects as its parameter. The example uses the Append(Choices) method to add the Choices object to the grammar.

C# Copy image Copy Code
GrammarBuilder gb = new GrammarBuilder("The card suit is");
Choices suits = new Choices(new string[] {"hearts", "diamonds", "clubs", "spades"});
gb.Append(suits);

A Choices instance is similar to the SRGS one-of Element (Microsoft.Speech), as defined in the Speech Recognition Grammar Specification (SRGS) Version 1.0, and an SrgsOneOf instance.

See Also

Concepts

Create Grammars Using GrammarBuilder (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Content Using GrammarBuilder Methods (Microsoft.Speech)

[image]

Add Content Using GrammarBuilder Methods (Microsoft.Speech)
See Also Send Feedback

An application can use one of the Append()()()() overloaded methods to build an existing GrammarBuilder instance in an incremental fashion. A number of types can be appended to a GrammarBuilder instance, including a Choices instance, a SemanticResultKey instance, a SemanticResultValue instance, a String, or another GrammarBuilder instance.

In addition to the Append()()()() overloaded methods, there are five static Add()()()() methods on the GrammarBuilder class. All of these static methods return a GrammarBuilder instance that is created from a Choices instance and a GrammarBuilder instance (GrammarBuilder can precede Choices), a string and a GrammarBuilder instance (GrammarBuilder can precede the string), or two GrammarBuilder instances. In addition to these methods, the GrammarBuilder class has five static overloads for the addition operator, permitting the same kinds of combinations that are used for the Add()()()() methods.

The following example creates a grammar in a console application that recognizes input phrases such as "I would like to fly from New York to Dallas". The example first appends the string "I would like to fly from" to the empty GrammarBuilder instance. Then the example appends the Choices instance cities, and then the string "to", and finally appends the cities object a second time. A handler for the SpeechRecognized event can determine the sentence spoken by the application user but cannot parse the component parts of the sentence, particularly the "from" and "to" cities.

C# Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

    // Initialize an in-process speech recognition engine.
    {
      using (SpeechRecognitionEngine recognizer =
         new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US")))
      {

        // Create a grammar.
        Choices cities = new Choices(new string[] {
          "Los Angeles", "New York", "Chicago", "San Francisco", "Miami", "Dallas" });

        GrammarBuilder gb = new GrammarBuilder();
        gb.Append("I want to fly from");
        gb.Append(cities);
        gb.Append("to");
        gb.Append(cities);

        // Create a Grammar object and load it to the recognizer.
        Grammar g = new Grammar(gb);
        g.Name = ("City Chooser");
        recognizer.LoadGrammarAsync(g);

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

        // Set the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

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

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

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

The next example is nearly identical to the previous example, but presents a more sophisticated grammar that can parse out the departure city and destination city. This example uses SemanticResultKey instances that associate the Choices instance (cities) with separate semantic keys that represent the departure city and destination city. The example uses the Append()()()() method to incorporate the SemanticResultKey objects in the GrammarBuilder instance. A handler for the SpeechRecognized event can extract information about the two cities involved in a flight by using the semantic keys "DepartureCity" and "DestinationCity." For more information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech) and Use a SemanticResultKey to Extract a SemanticResultValue (Microsoft.Speech).

C# Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

    // Initialize an in-process speech recognition engine.
    {
      using (SpeechRecognitionEngine recognizer =
         new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US")))
      {

        // Create a grammar.
        Choices cities = new Choices(new string[] {
          "Los Angeles", "New York", "Chicago", "San Francisco", "Miami", "Dallas" });

        GrammarBuilder gb = new GrammarBuilder();
        gb.Append("I would like to fly from");
        gb.Append(new SemanticResultKey("DepartureCity", cities));
        gb.Append("to");
        gb.Append(new SemanticResultKey("DestinationCity", cities));

        // Create a Grammar object and load it to the recognizer.
        Grammar g = new Grammar(gb);
        g.Name = ("City Chooser");
        recognizer.LoadGrammarAsync(g);

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

        // Set the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

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

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

    // Handle the SpeechRecognized event.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine("Speech recognized: " + e.Result.Text);
      Console.WriteLine();
      Console.WriteLine("Semantic results:");
      Console.WriteLine("  The departure city is: " +
        e.Result.Semantics["DepartureCity"].Value);
      Console.WriteLine("  The destination city is: " +
        e.Result.Semantics["DestinationCity"].Value);
    }
  }
}

See Also

Concepts

Create Grammars Using GrammarBuilder (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetMinimum and Maximum Repeat Values (Microsoft.Speech)

[image]

SetMinimum and Maximum Repeat Values (Microsoft.Speech)
See Also Send Feedback

You can use GrammarBuilder to create a grammar element that specifies a minimum repeat value and a maximum repeat value for successful recognition. A minimum repeat value of zero indicates that the element is optional. If this value is combined with a maximum repeat value of one, the element can be spoken at most one time. The minimum repeat count must be zero or larger and the maximum repeat count must be at least as large as the minimum repeat count.

To create a GrammarBuilder instance with repeat values, use one of the following constructors:

  • GrammarBuilder(GrammarBuilder, Int32, Int32)

  • GrammarBuilder(String, Int32, Int32)

The first of these constructors takes an existing GrammarBuilder instance as its first argument, and the minimum and maximum repeat counts, respectively. The second constructor takes a word or phrase as its first argument, and the minimum and maximum repeat counts.

You can also use the following methods on the GrammarBuilder class to assign minimum and maximum repeat counts:

  • Append(GrammarBuilder, Int32, Int32)

  • Append(String, Int32, Int32)

See Also

Concepts

Create Grammars Using GrammarBuilder (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech)

[image]

Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech)
See Also Send Feedback

The SemanticResultValue and SemanticResultKey classes can be used to create grammars that process semantic values or meaning from an input phrase.

The grammar in the following example recognizes the English (U.S.) numbers "zero" through "nine" and returns the numeric values. If an application user says "three", this grammar returns the semantic value 3. Each call to Add(array<GrammarBuilder>[]()[][]) implicitly converts temp to a GrammarBuilder instance.

C# Copy image Copy Code
Choices digits = new Choices();
GrammarBuilder digitValues = new GrammarBuilder();

SemanticResultValue temp = new SemanticResultValue("zero", 0);
digits.Add(temp);
digitValues.Append(temp);

temp = new SemanticResultValue("one", 1);
digits.Add(temp);
digitValues.Append(temp);

temp = new SemanticResultValue("two", 2);
digits.Add(temp);
digitValues.Append(temp);

temp = new SemanticResultValue("three", 3);
digits.Add(temp);
digitValues.Append(temp);

// Code omitted follows a predictable pattern.

temp = new SemanticResultValue("eight", 8);
digits.Add(temp);
digitValues.Append(temp);

temp = new SemanticResultValue("nine", 9);
digits.Add(temp);
digitValues.Append(temp);

In the preceding example, each call to the SemanticResultValue(String, Object) constructor pairs a potential input word with its semantic value.

A SemanticResultKey instance can be used to access a semantic value established by a SemanticResultValue instance. Creating a SemanticResultKey establishes a pairing between a key name and an array of GrammarBuilder instances or strings. The grammar in the following example creates a grammar that combines the GrammarBuilder instance from the previous example with two SemanticResultKey instances, "first_value" and "second_value". The goal of this grammar is to recognize phrases such as "four plus nine equals" and to return the semantic values of the numbers in this phrase. For more information, see Use a SemanticResultKey to Extract a SemanticResultValue (Microsoft.Speech).

Visual Basic Copy image Copy Code
GrammarBuilder gb = new GrammarBuilder();
gb.Append(new SemanticResultKey("first_value", digits));
gb.Append("plus");
gb.Append(new SemanticResultKey("second_value", digits));
gb.Append("equals");
Grammar g = new Grammar(gb);
sre.LoadGrammar(g);

See Also

Concepts

Create Grammars Using GrammarBuilder (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Use a SemanticResultKey to Extract a SemanticResultValue (Microsoft.Speech)

[image]

Use a SemanticResultKey to Extract a SemanticResultValue (Microsoft.Speech)
See Also Send Feedback

After creating a SemanticResultValue instance and a SemanticResultKey instance to provide access to the semantic value, the semantic key is frequently used to obtain the semantic value in a handler for the SpeechRecognized event on the SpeechRecognitionEngine class.

The e parameter of the SpeechRecognized event handler is of type SpeechRecognizedEventArgs. This class provides access to the Result property, which in turn provides access to the Semantics collection (a collection of key and value pairs) and other useful properties. Given a key (the SemanticResultKey instance), you can determine the associated value (a SemanticResultValue instance) by evaluating the following expression:

e.Result.Semantics["key"].Value.

The example in the topic Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech) creates a GrammarBuilder grammar from a collection of words for the English (U.S.) numbers "zero" through "nine" defined by a Choices object. The following excerpt shows how the example creates a SemanticResultValue value for each of the possible recognized words, pairing each word with its semantic (and in this case, numeric) value.

C# Copy image Copy Code
Choices digits = new Choices();
GrammarBuilder digitValues = new GrammarBuilder();

SemanticResultValue temp = new SemanticResultValue("zero", 0);
digits.Add(temp);
digitValues.Append(temp);

temp = new SemanticResultValue("one", 1);
digits.Add(temp);
digitValues.Append(temp);
temp = new SemanticResultValue("two", 2);
digits.Add(temp);
digitValues.Append(temp);
.
.
.

After creating the GrammarBuilder instance (digitValues), the example creates a new GrammarBuilder instance named gb to associate a SemanticResultKey key with a recognized value from the digitsChoices instance. The event handler for the SpeechRecognized event can use this association to determine the semantic value of a word spoken in an input phrase. The following example reproduces the portion of code in Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

C# Copy image Copy Code
GrammarBuilder gb = new GrammarBuilder();
gb.Append(new SemanticResultKey("first_value", digits));
gb.Append("plus");
gb.Append(new SemanticResultKey("second_value", digits));
gb.Append("equals");Grammar g = new Grammar(gb);
sre.LoadGrammar(g);

With the SemanticResultValue and SemanticResultKey infrastructure in place, the event handler for the SpeechRecognized event is able to determine semantic values from an input phrase. When a user speaks a phrase such as "five plus seven equals," the event handler in the following example gets the semantic values for "five" and "seven" (namely, 5 and 7), and adds them to produce their sum. When the user finishes speaking the input phrase, the recognizer raises the SpeechRecognized event, which causes the event handler shown in the following example to be called.

Note Note

In the following example, the application is assumed to have registered to be notified of the SpeechRecognized event and has supplied a handler for the event.

The e.Result.Semantics expression represents the dictionary of semantic key-value pairs. The e.Result.Semantics["first_value"].Value expression represents the semantic value of the first number word in the input phrase, and the e.Result.Semantics["second_value"].Value expression represents the semantic value of the second number word in the input phrase.

C# Copy image Copy Code
void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
  int a = 0;
  int b = 0;
  bool errorCondition = false;

  if (e.Result != null)
  {
    if (e.Result.Semantics != null)
    {
      a = (int)e.Result.Semantics["first_value"].Value;
      b = (int)e.Result.Semantics["second_value"].Value;
    }

    else
    // Error: e.Result.Semantics == null
    {
      errorCondition = true;
    }
  }

  else
  // Error: e.Result == null
  {
    errorCondition = true;
  }

  if (!errorCondition)
  {
    string str = a.ToString();
    str += " + ";
    str += b.ToString();
    str += " = ";
    int result = a + b;
    str += result.ToString();
    MessageBox.Show(str);
  }
  else
  {
    MessageBox.Show("Error occurred");
  }
}

See Also

Concepts

Create Grammars Using GrammarBuilder (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Create Grammars Using SrgsGrammar (Microsoft.Speech)

[image]

Create Grammars Using SrgsGrammar (Microsoft.Speech)
Send Feedback

Using the classes in the Microsoft.Speech.Recognition.SrgsGrammar namespace, you can programmatically create grammars that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0, as implemented by the Microsoft Speech Platform SDK 11. The types of the Microsoft.Speech.Recognition.SrgsGrammar namespace map closely to the elements and attributes defined by SRGS.

In This Section

  • Create SrgsDocument Objects (Microsoft.Speech)

  • Use the SrgsGrammar Building Blocks (Microsoft.Speech)

  • Use SrgsGrammar Classes to Create a Grammar (Microsoft.Speech)

  • Compile SRGS Grammars (Microsoft.Speech)

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Create SrgsDocument Objects (Microsoft.Speech)

[image]

Create SrgsDocument Objects (Microsoft.Speech)
See Also Send Feedback

You can use an SrgsDocument instance to build strongly-typed grammars that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0. An SrgsDocument instance is a container for the components that comprise a speech recognition grammar:

  • The root rule (Root), which is active when the grammar is loaded.

  • The collection of rules that are defined for the grammar (Rules).

  • The recognition mode, either voice or dual-tone multi-frequency (DTMF) (Mode).

  • The phonetic alphabet (PhoneticAlphabet) to use when creating inline pronunciations for SrgsToken objects.

  • The language and locale that the grammar supports (Culture).

  • The grammar's base Uniform Resource Identifier (URI) (XmlBase).

Creating an SrgsDocument Instance

You can use any of five overloaded constructors to create an SrgsDocument instance. The constructor with no arguments creates an SrgsDocument instance with an empty SrgsRulesCollection, and with most of its properties set to their default values. One SrgsDocument constructor takes a GrammarBuilder instance as its argument, and another takes an SrgsRule instance as its argument.

With two of the constructors you can create an SrgsDocument instance using an existing XML grammar. One of these constructors takes a string argument that represents the file location of the XML grammar. The other constructor takes an XmlReader instance as its argument. For more information, see the example in SrgsDocument(XmlReader).

The following example shows the creation of a simple rule that can recognize the names of five different fruits. After initializing the SrgsRule object, the example uses an SrgsOneOf object to create a list of alternatives from an array of String objects. Adding the SrgsOneOf object to the rule, the example then creates the SrgsDocument instance. The rule is then added to the SrgsRulesCollection on the SrgsDocument instance, and designated as the root rule of the grammar.

C# Copy image Copy Code
// Create a rule and give it the identifier "fruitList".
SrgsRule fruitRule = new SrgsRule("fruitList");

// Create a list of alternatives containing names of fruit
// and add the list to the rule.
SrgsOneOf fruit = new SrgsOneOf(new string[] { "apple", "banana", "pear", "peach", "melon" });
fruitRule.Add(fruit);
fruitRule.Scope = SrgsRuleScope.Public;

// Create an SrgsDocument instance, add the rule, and set it as the root rule.
SrgsDocument document = new SrgsDocument();
document.Rules.Add(fruitRule);
document.Root = fruitRule;

See Also

Concepts

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Use the SrgsGrammar Building Blocks (Microsoft.Speech)

[image]

Use the SrgsGrammar Building Blocks (Microsoft.Speech)
See Also Send Feedback

You can use the classes in the Microsoft.Speech.Recognition.SrgsGrammar namespace to create a grammar dynamically, while the application is running. The classes in this namespace map closely to the elements specified in the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0, as shown in the following table. For more information, see SRGS Grammar XML Reference (Microsoft.Speech).

SrgsGrammar Namespace Member | SRGS element
SrgsItem | item
SrgsOneOf | one-of
SrgsRule | rule
SrgsRuleRef | ruleref
SrgsToken | token
SrgsSemanticInterpretationTag | tag

Using SrgsItem Objects

An SrgsItem instance can represent a word or phrase, and can also contain SrgsRuleRef, SrgsToken, SrgsSemanticInterpretationTag, SrgsOneOf instances. An SrgsItem instance can appear within an SrgsRule instance, or as one of several alternative choices in an SrgsOneOf instance.

When you create an SrgsItem instance, you can specify minimum and maximum repetition values in the constructor. For example, if you use minimum and maximum repetition counts of 0 and 1, then the item can be spoken zero or one time (recognition can be successful whether or not recognized speech contains the contents of the item). If minimum and maximum repetition counts of 1 and 1 are specified, then the item must be spoken exactly once for recognition to be successful.

In the following example, optionalItem is a grammar element that can be spoken once or not at all. The mandatoryItem object must be spoken exactly once.

C# Copy image Copy Code
SrgsItem optionalItem = new SrgsItem(0, 1, "please");
SrgsItem mandatoryItem = new SrgsItem(1, 1, "yes");

Using SrgsOneOf Objects

Use SrgsOneOf objects to represent a list of alternative utterances that a user may speak, any of which will constitute successful recognition. SrgsOneOf objects are analogous to Choices objects that are used in GrammarBuilder grammars.

The following example shows an SrgsOneOf instance that can match a user utterance containing any one of the five fruits listed.

C# Copy image Copy Code
SrgsOneOf fruits = new SrgsOneOf(new string[]
{"apple", "banana", "pear", "peach", "melon"});

The following example shows an SRGS one-of element with the same structure as the fruits object in the previous example.

XML Copy image Copy Code
<one-of>
  <item> apple </item>
  <item> banana </item>
  <item> pear </item>
  <item> peach </item>
  <item> melon </item>
</one-of>

Using SrgsRule Objects

An SrgsRule object represents an element of a grammar that defines the set of phrases that a user can speak to produce a successful recognition. A SrgsDocument object must contain at least one SrgsRule object.

An SrgsRule instance can contain objects of the following types. All of these types inherit from the abstract SrgsElement base class.

  • SrgsItem

  • SrgsOneOf

  • SrgsRuleRef

  • SrgsSemanticInterpretationTag

  • SrgsText

  • SrgsToken

You can add an instance of one of the preceding types to a rule by calling the Add(SrgsElement) method.

The following example shows the creation of an SrgsRule instance named subjRule. The example sets the Id property on subjRule to "id_Subject" when it creates the instance. The default value of the Scope property of an SrgsRule instance is Private (one of two values on the SrgsRuleScope enumeration).

After creating the subjRule instance, the example initiates an SrgsOneOf object containing six alternative words, and then adds the SrgsOneOf instance to subjRule.

C# Copy image Copy Code
// Create a rule and give it the identifier "id_Subject".
SrgsRule subjRule = new SrgsRule("id_Subject");
SrgsOneOf subjList = new SrgsOneOf(new string[] {"I", "you", "he", "she", "Tom", "Mary"});
subjRule.Add(oneOf);

The SrgsRule instance in the preceding example is functionally equivalent to the SRGS XML rule element in the following example.

XML Copy image Copy Code
<rule id="id_Subject" scope="private">
  <one-of>
    <item> I </item>
    <item> you </item>
    <item> he </item>
    <item> she </item>
    <item> Tom </item>
    <item> Mary </item>
  </one-of>
</rule>

Using SrgsRuleRef Objects

An SrgsRuleRef object specifies a reference to an SrgsRule object in the same grammar, or to a rule element in an XML-format SRGS file external to the grammar.

The following SrgsRule instance contains three SrgsRuleRef instances. When constructing each rule reference, the example passes the referenced SrgsRule object and a string (representing the semantic key) in the constructor call. The contents of the referenced rules are not shown.

C# Copy image Copy Code
// Create a rule that contains references to three other rules.
SrgsRule mainRule = new SrgsRule("Subj_Verb_Obj");
mainRule.Scope = SrgsRuleScope.Public;

// Create the first rule reference and add it to the rule.
SrgsRuleRef subjRef = new SrgsRuleRef(subjRule, "theSubject");
mainRule.Add(subjRef);

// Create the second rule reference and add it to the rule.
SrgsRuleRef verbRef = new SrgsRuleRef(verbRule, "theVerb");
mainRule.Add(verbRef);

// Add logic to handle articles: "the", "a", "and"
// occurring zero or one time.
SrgsOneOf articles = new SrgsOneOf(new SrgsItem[] {
  (new SrgsItem(0, 1, "the")), new SrgsItem(0, 1, "a"),
  new SrgsItem(0, 1, "an") });
mainRule.Add(articles);

// Create the third rule reference and add it to the rule.
SrgsRuleRef objRef = new SrgsRuleRef(objRule, "theObject");
mainRule.Add(objRef);
Note Note

A SrgsRuleRef instance references an SrgsRule object by specifying the object. However, to reference a rule element in an XML-format grammar, the SrgsRuleRef object specifies the identifier of the rule element (its id attribute).

The rule shown in the preceding example is functionally equivalent to the SRGS XML rule in the following example. This comparison assumes that:

  • The identifier for subjRule is "id_Subject".

  • The identifier for verbRule is "id_verb".

  • The identifier for objRule is "id_Object".

XML Copy image Copy Code
<rule id="Subj_Verb_Obj" scope="public">
  <item>
    <ruleref uri="#id_Subject"/>
    <tag> out.id_Subject = rules.latest()</tag>

    <ruleref uri="#id_Verb"/>
    <tag> out.id_Verb = rules.latest() </tag>

    <one-of>
      <item repeat="0-1"> the </item>
      <item repeat="0-1"> a </item>
      <item repeat="0-1"> an </item>
    </one-of>

    <ruleref uri="#id_Object"/>
    <tag> out.id_Object = rules.latest() </tag>
  </item>
</rule>

See Also

Concepts

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Use SrgsGrammar Classes to Create a Grammar (Microsoft.Speech)

[image]

Use SrgsGrammar Classes to Create a Grammar (Microsoft.Speech)
See Also Send Feedback

The classes in the Microsoft.Speech.Recognition.SrgsGrammar namespace (and described in Use the SrgsGrammar Building Blocks (Microsoft.Speech)) can be used to create a grammar. The first code example in this topic creates a grammar with enough complexity to recognize three parts of speech (subject, verb, and direct object) in a simple declarative sentence such as "Mary bought an apple." The grammar recognizes six different subjects, five verbs, and five direct objects, a total of 150 distinct sentences that it can recognize. Counting the articles "a," "an," and "the" brings the total number of recognized sentences to 600.

The second example in this topic is the definition for an event handler for the SpeechRecognized event. This event handler uses the semantic keys ("theSubject", "theVerb", and "theObject") to determine the semantic values recognized by the grammar.

The third example in this topic shows an XML-format grammar that conforms to the Speech Recognition Grammar Specification (SRGS) Version 1.0 and is functionally equivalent to the grammar created in the first example.

Example 1: Create a Dynamic Grammar using SrgsGrammar

The following example creates a grammar using the classes available in the Microsoft.Speech.Recognition.SrgsGrammar namespace.

Note Note

The SpeechRecognitionEngine instance, sre, is declared at the class level outside of the method shown in this example.
C# Copy image Copy Code
private void Form1_Load(object sender, EventArgs e)
{
  sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"))

  // Create the "Subject" rule.
  SrgsRule subjRule = new SrgsRule("id_Subject");
  SrgsOneOf subjList = new SrgsOneOf(new string[] { "I", "you", "he", "she", "Tom", "Mary" });
  subjRule.Add(subjList);

  // Create the "Verb" rule.
  SrgsRule verbRule = new SrgsRule("id_Verb");
  SrgsOneOf verbList = new SrgsOneOf(new string[] { "ate", "bought", "saw", "sold", "wanted" });
  verbRule.Add(verbList);

 // Create the "Object" rule.
  SrgsRule objRule = new SrgsRule("id_Object");
  SrgsOneOf objList = new SrgsOneOf(new string[] { "apple", "banana", "pear", "peach", "melon" });
  objRule.Add(objList);

  // Create the root rule.
  // In this grammar, the root rule contains references to the other three rules.
  SrgsRule rootRule = new SrgsRule("Subj_Verb_Obj");
  rootRule.Scope = SrgsRuleScope.Public;

  // Create the "Subject" and "Verb" rule references and add them to the SrgsDocument.
  SrgsRuleRef subjRef = new SrgsRuleRef(subjRule, "theSubject");
  rootRule.Add(subjRef);

  SrgsRuleRef verbRef = new SrgsRuleRef(verbRule, "theVerb");
  rootRule.Add(verbRef);

  // Add logic to handle articles: "the", "a", "and", occurring zero or one time.
  SrgsOneOf articles = new SrgsOneOf(new SrgsItem[] {
    (new SrgsItem(0, 1, "the")), new SrgsItem(0, 1, "a"),
    new SrgsItem(0, 1, "an") });
  rootRule.Add(articles);

  // Create the "Object" rule reference and add it to the SrgsDocument.
  SrgsRuleRef objRef = new SrgsRuleRef(objRule, "theObject");
  rootRule.Add(objRef);

  // Create an SrgsDocument object that contains all four rules.
  SrgsDocument document = new SrgsDocument();
  document.Rules.Add(new SrgsRule[] { rootRule, subjRule, verbRule, objRule });

  // Set "rootRule" as the root rule of the grammar.
  document.Root = rootRule;

  // Create a Grammar object, initializing it with the root rule.
  Grammar g = new Grammar(document, "Subj_Verb_Obj");

  // Load the Grammar object into the recognizer.
  sr.LoadGrammar(g);

  // Produce an XML file that contains the grammar.
  System.Xml.XmlWriter writer =
    System.Xml.XmlWriter.Create("c:\\test\\srgsDocument.xml");
  document.WriteSrgs(writer);
  writer.Close();

  // Attach a handler for the SpeechRecognized event.
  sre.SpeechRecognized +=
    new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);

  // Configure the input to the SpeechRecognitionEngine object.
  sre.SetInputToDefaultAudioDevice();

  // Start asynchronous recognition.
  sre.RecognizeAsync();
}

Example 2: Parse Semantic Content in Event Handler

The following is a handler for the SpeechRecognized event on the SpeechRecognitionEngine instance, sre, that is used in the preceding sample code. This handler is registered in the last line of the preceding sample. When the SpeechRecognized event is raised, the following handler is called. The e argument in this handler provides access to semantic values when speech is recognized.

C# Copy image Copy Code
void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
  string str = e.Result.Text;
  string subj = "unassigned", verb = "unassigned", obj = "unassigned";
  bool errorCondition = false;
  if (e.Result != null)
  {
    if (e.Result.Semantics != null && e.Result.Semantics.Count != 0)
    {
      SemanticValue semantics = e.Result.Semantics;
      if (e.Result.Semantics.ContainsKey("theSubject"))
      {
        subj = e.Result.Semantics["theSubject"].Value.ToString();
      }
      else errorCondition = true;

      if (e.Result.Semantics.ContainsKey("theVerb"))
      {
        verb = e.Result.Semantics["theVerb"].Value.ToString();
      }
      else errorCondition = true;

      if (e.Result.Semantics.ContainsKey("theObject"))
      {
        obj = e.Result.Semantics["theObject"].Value.ToString();
      }
      else errorCondition = true;
      if (!errorCondition)
      {
        MessageBox.Show(String.Format(
              "Reco string: {0}\nSubject: {1}\nVerb: {2}\nObject: {3}",
              str, subj, verb, obj));
      }
      else
      {
        MessageBox.Show(
              "e.Result.Semantics is null or e.Result.Semantics.Count == 0");
      }
    }
  else
  {
    MessageBox.Show("e.Result is null");
  }
}

Example 3: SRGS XML Grammar

The following XML grammar can be used to recognize simple declarative sentences of the form <Subject><Verb><article (optional)><Object> with varying subjects, verbs, and direct objects. A typical sentence that is recognized is "Mary bought the apple."

In this grammar, the subject can be "I", "you", "he", "she", "Tom", or "Mary". The verb can be "ate", "bought", "saw", "sold", or "wanted". The object can be "apple", "banana", "pear", "peach", or "melon".

In the following illustration, a spoken sentence is recognized as long as it contains one of the words in the first one-of element, a word in the second one-of element, and a word in the fourth one-of element. The "0-1" notations on the items in the third one-of element represent the minimum and maximum repetition counts for these words, and mean that an input sentence can contain zero or one of the words in the third one-of element.

This grammar consists of four rules. The first rule, "Subj_Verb_Obj", is the root rule and consists of the following elements:

  • A ruleref element that references a rule that recognizes the valid subjects for an input sentence.

  • A ruleref that references a rule that recognizes the valid verbs for the sentence.

  • A one-of element that recognizes the articles "the", "a", and "an", which are made optional by the repeat attribute of their enclosing item elements.

  • A final ruleref element that references a rule that recognizes the valid direct objects for the sentence.

For more information about these SRGS elements, see ruleref Element (Microsoft.Speech), one-of Element (Microsoft.Speech), and item Element (Microsoft.Speech).

The following XML example is functionally equivalent to the grammar created in Example 1, above. The XML example uses syntax according the format "semantics-ms/1.0", which is declared in the opening tag of the grammar element. The symbol "$" refers to the Rule Variable of the containing rule element. The expression "$.Subject" refers to the property named "Subject" of the Rule Variable on the rule "Subj_Verb_Obj". The symbol "$$" refers to the latest result from the rule that is the target of the rule reference, and does not specify a property on the target rule. See Semantic Results Content (Microsoft.Speech) and Grammar Rule Reference Referencing (Microsoft.Speech) for more information.

XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8" ?>
<grammar version="1.0" xml:lang="en-US" mode="voice"
root="Subj_Verb_Obj" tag-format="semantics-ms/1.0"
xmlns="http://www.w3.org/2001/06/grammar" >

  <rule id="Subj_Verb_Obj" scope="public">

    <ruleref uri="#id_Subject" />
    <tag> $.Subject = $$; </tag>

    <ruleref uri="#id_Verb" />
    <tag> $.Verb = $$; </tag>

    <one-of>
      <item repeat="0-1">the</item>
      <item repeat="0-1">a</item>
      <item repeat="0-1">an</item>
    </one-of>

    <ruleref uri="#id_Object" />
    <tag> $.Object = $$; </tag>

  </rule>

  <rule id="id_Subject" scope="private">
    <one-of>
      <item> I </item>
      <item> you </item>
      <item> he </item>
      <item> she </item>
      <item> Tom </item>
      <item> Mary </item>
    </one-of>
  </rule>

  <rule id="id_Verb" scope="private">
    <one-of>
      <item> ate </item>
      <item> bought </item>
      <item> saw </item>
      <item> sold </item>
      <item> wanted </item>
    </one-of>
  </rule>

  <rule id="id_Object" scope="private">
    <one-of>
      <item> apple </item>
      <item> banana </item>
      <item> pear </item>
      <item> peach </item>
      <item> melon </item>
    </one-of>
  </rule>
</grammar>

See Also

Concepts

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile SRGS Grammars (Microsoft.Speech)

[image]

Compile SRGS Grammars (Microsoft.Speech)
See Also Send Feedback

Compiling your XML grammar to a binary grammar file with the .cfg extension can reduce the time consumed by searches for a match, especially in grammars that require recognition of a large number of words and phrases.

The SrgsGrammarCompiler class contains three overloaded Compile()()()() methods that compile a grammar to a binary grammar file with the .cfg extension. These methods can be used to:

  • Compile a dynamically-created grammar contained in an SrgsDocument instance, using Compile(SrgsDocument, Stream).

    The first parameter represents the grammar to compile, and the second is a FileStream object that represents the location to which the compiled grammar will be written.

  • Compile an existing XML grammar, using Compile(String, Stream).

    The first parameter represents the existing XML grammar to compile, and the second is a FileStream object that represents the location to which the compiled grammar will be written.

  • Compile an XmlReader grammar that can reside in memory or in physical file, using Compile(XmlReader, Stream).

    The first parameter represents the XmlReader instance to compile, and the second is a FileStream object that represents the location to which the compiled grammar will be written.

Compile an SrgsDocument

The first example in the following group of four examples uses the Compile(SrgsDocument, Stream) method to compile an SrgsDocument instance. The other examples include an event handler for the SpeechRecognized event and helper methods that the first example calls to perform three tasks:

  • Create an SrgsDocument instance

  • Create a grammar

  • Compile the grammar

The grammar that is created in the CreateGrammar method can be used to recognize phrases such as "I want to fly from Miami to Chicago." The two semantic values in the grammar are the departure city and the destination city. The semantic keys for these semantic values are "LeavingFrom" and "GoingTo."

Note Note

The SpeechRecognitionEngine instance, sre, is declared outside this method.
C# Copy image Copy Code
private void Form1_Load(object sender, EventArgs e)
{
  sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));
  sre.SetInputToDefaultAudioDevice();

  // Create an SrgsDocument instance and compile it.
  SrgsDocument srgsDoc = new SrgsDocument();
  srgsDoc = CreateGrammar();
  CompileGrammar(srgsDoc, @"C:\test\AirportCodes.cfg");
  Grammar g = new Grammar(@"C:\test\AirportCodes.cfg", "flightBooker");

  // Load the grammar to the SpeechRecognitionEngine.
  sre.LoadGrammar(g);

  // Attach a handler for the SpeechRecognized event.
  sre.SpeechRecognized +=
    new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);

  // Start asynchronous recognition.
  sre.RecognizeAsync();
  Console.WriteLine("Starting asynchronous recognition...\n");

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

The following example is the handler for the SpeechRecognized event. This handler uses the semantic keys "LeavingFrom" and "GoingTo" as indexes into the e.Result.Semantics collection.

C# Copy image Copy Code
void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
  string recoString = e.Result.Text;
  string departCity = e.Result.Semantics["LeavingFrom"].Value.ToString();
  string arriveCity = e.Result.Semantics["GoingTo"].Value.ToString();

  MessageBox.Show(String.Format("Recognized phrase: {0}\nDeparting from: {1}\nArriving at: {2}", recoString, departCity, arriveCity));
}

The following method is a helper whose job is to create the SrgsDocument instance, which makes up the bulk of the grammar used in this example. The SrgsDocument instance contains two rules whose identifiers are "flightBooker" and "cities". The rule named "cities" recognizes city names and returns the three-letter airport code for a recognized city. The "flightBooker" rule recognizes phrases of the form "I want to fly from <rule reference> to <rule reference>," where each rule reference points to the rule named "cities". The example uses SrgsSemanticInterpretationTag objects after the SrgsRuleRef objects in the "flightBooker" rule to assign semantic keys to the recognition result from the "cities" rule. The keys identify each city as the departure city or as the arrival city.

C# Copy image Copy Code
private SrgsDocument CreateGrammar()
{
  SrgsDocument srgsDoc = new SrgsDocument();

  // Create a rule for cities, assign a semantic value to each city.
  SrgsRule cities = new SrgsRule("flightCities");
  SrgsItem chi = new SrgsItem("Chicago");
  chi.Add(new SrgsSemanticInterpretationTag("$ = \"ORD\";"));
  SrgsItem bos = new SrgsItem("Boston");
  bos.Add(new SrgsSemanticInterpretationTag("$ = \"BOS\";"));
  SrgsItem mia = new SrgsItem("Miami");
  mia.Add(new SrgsSemanticInterpretationTag("$ = \"MIA\";"));
  SrgsItem dal = new SrgsItem("Dallas");
  dal.Add(new SrgsSemanticInterpretationTag("$ = \"DFW\";"));
  SrgsOneOf airports = new SrgsOneOf(chi, bos, mia, dal);
  cities.Add(airports);
  cities.Scope = SrgsRuleScope.Private;

  // Create a rule reference to the rule for cities.
  SrgsRuleRef cityRef = new SrgsRuleRef(cities);

  // Create the root rule for the grammar.
  SrgsRule bookFlight = new SrgsRule("flightBooker");
  bookFlight.Add(new SrgsItem("I want to fly from"));
  bookFlight.Add(cityRef);
  bookFlight.Add(new SrgsSemanticInterpretationTag("$.LeavingFrom=$$;"));
  bookFlight.Add(new SrgsItem("to"));
  bookFlight.Add(cityRef);
  bookFlight.Add(new SrgsSemanticInterpretationTag("$.GoingTo=$$;"));
  bookFlight.Scope = SrgsRuleScope.Public;

  // Add the rules to the SrgsDocument object and set the root rule.
  srgsDoc.Rules.Add(cities);
  srgsDoc.Rules.Add(bookFlight);
  srgsDoc.Root = bookFlight;

  // Write the completed grammar to an XML-format SRGS grammar file.
  System.Xml.XmlWriter writer =
    System.Xml.XmlWriter.Create("c:\\test\\AirportCodes.grxml");
  srgsDoc.WriteSrgs(writer);
  writer.Close();

  return srgsDoc;
}
Note Note

See SrgsSemanticInterpretationTag for more information about specifying semantics for grammars authored programmatically using members of the Microsoft.Speech.Recognition.SrgsGrammar namespace.

The final example in this section is a helper method. It creates a new FileStream object, and then calls the static method Compile(SrgsDocument, Stream) to compile the grammar created in the call to the previous example, CreateGrammar.

C# Copy image Copy Code
private void CompileGrammar(SrgsDocument srgsDoc, string cfgPath)
{
  FileStream fs = new FileStream(cfgPath, FileMode.Create);
  SrgsGrammarCompiler.Compile(srgsDoc, (Stream)fs);
  fs.Close();
}

Compile an XML Grammar in an External File

The Compile(String, Stream) method can be used to compile an existing grammar file that conforms to the Speech Recognition Grammar Specification (SRGS) Version 1.0.

The next example shows the SRGS grammar that is used as input in the C# example that follows it. The grammar recognizes sentences of the form "I would like to fly from <starting city> to <destination city>." The semantic values returned by this grammar are the three-letter airport codes.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar xml:lang="en-US" root="flightBooker"
tag-format="semantics-ms/1.0" version="1.0"
xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="flightBooker" scope="public">
    <item> I want to fly from </item>
    <ruleref uri="#flightCities" />
    <tag> $.LeavingFrom=$$; </tag>
    <item> to </item>
    <ruleref uri="#flightCities" />
    <tag> $.GoingTo=$$; </tag>
  </rule>

  <rule id="flightCities" scope="private">
    <one-of>
      <item> Chicago <tag> $="ORD"; </tag></item>
      <item> Boston <tag> $="BOS"; </tag></item>
      <item> Miami <tag> $="MIA"; </tag></item>
      <item> Dallas <tag> $="DFW"; </tag></item>
    </one-of>
  </rule>

</grammar>
Note Note

The example above uses tag elements to add semantic information to the grammar. For more information about using tag elements, see tag Element (Microsoft.Speech) and Using the tag Element (Microsoft.Speech).

The following example compiles the XML grammar shown in the preceding example to a binary grammar file with the .cfg extension, sending the compiled version to the location specified by the fs parameter in the call to the Compile(String, Stream) method. After the binary grammar file is created, it is used to create and initialize the Grammar instance named gr. The binary grammar file is then loaded into the speech recognizer by a call to the LoadGrammar(Grammar) method.

Note Note

The SpeechRecognitionEngine instance, sre, is declared outside this method.
C# Copy image Copy Code
private void Form1_Load(object sender, EventArgs e)
{
  sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));
  string grammarPath = @"C:\test\";

  FileStream fs = new FileStream(grammarPath + "AirportCodes.cfg", FileMode.Create);
  SrgsGrammarCompiler.Compile(grammarPath + "AirportCodes.grxml", (Stream)fs);
  fs.Close();
  Grammar gr = new Grammar(grammarPath + "AirportCodes.cfg", "flightBooker");

  sre.LoadGrammar(gr);

  sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);
  sre.SetInputToDefaultAudioDevice();
  sre.RecognizeAsync(RecognizeMode.Multiple);
}

Compile an XmlReader Grammar

The third Compile(XmlReader, Stream) overloaded method takes an XmlReader object as its input and it is similar to the Compile(XmlReader, Stream) overloaded method that takes an XML file as input. The difference between these two overloaded methods is that the XmlReader can exist in memory or as an external file.

The following example shows the steps involved in using this Compile(XmlReader, Stream) overloaded method. The first step is to create a FileStream instance that identifies where the compiled binary grammar file will be written. Next, a XmlReader instance is created, using the static Create method on the XmlReader class. In this example, the XmlReader instance that is created comes from an XML grammar file named "AirportCodes.grxml." At this point, the contents of the XmlReader instance are compiled and sent to the location designated by the outStream parameter, after which the FileStream instance is closed. Finally, a Grammar instance is created from the binary grammar file with the .cfg extension, and the grammar is loaded into the speech recognizer.

Note Note

The SpeechRecognitionEngine instance, sre, is declared outside this method.
C# Copy image Copy Code
string grammarPath = @"C:\test\";
string xmlGrammar = grammarPath + "AirportCodes.grxml";
string cfgGrammar = grammarPath + "AirportCodes.cfg";

FileStream fs = new FileStream(cfgGrammar, FileMode.Create);
XmlReader reader = XmlReader.Create(xmlGrammar);

SrgsGrammarCompiler.Compile(reader, (Stream)fs);
fs.Close();
Grammar g = new Grammar(cfgGrammar, "flightBooker");
sre.LoadGrammar(g);

See Also

Reference

SrgsDocument
SrgsRuleRef
SrgsSemanticInterpretationTag

Concepts

tag Element (Microsoft.Speech)
Using the tag Element (Microsoft.Speech)
Referencing Grammar Rule Variables (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Create Grammars Using SRGS XML (Microsoft.Speech)

[image]

Create Grammars Using SRGS XML (Microsoft.Speech)
See Also Send Feedback

Although you can author grammars programmatically in your application using the members of the Microsoft.Speech.Recognition and Microsoft.Speech.Recognition.SrgsGrammar namespaces, you may also want to author grammars as static files using XML. You can create grammars in XML format using any text editor. Grammars authored using XML must conform to the Speech Recognition Grammar Specification Version 1.0 (SRGS). The Microsoft Speech Platform SDK 11 provides support for importing XML-format SRGS grammar files for use in recognition by the speech recognition engine.

You can import an entire XML-format SRGS grammar file, or only a specified rule within a grammar file, using an argument for a constructor or a method on a class in the Microsoft.Speech.Recognition or Microsoft.Speech.Recognition.SrgsGrammar namespaces. An imported SRGS grammar or rule may be used in its entirety (complete and ready to load), or as a component in a larger grammar. You can load an XML-format SRGS grammar or rule at run time using the following constructors and methods:

  • Constructors on the Grammar class.

    Import your SRGS grammar directly into a Grammar object that is ready to load by the speech recognition engine. See the Grammar()()()() constructors.

  • AppendRuleReference()()()() methods.

    Create a GrammarBuilder object from an XML-format grammar file, or append the file or one of its rules to the grammar defined by the GrammarBuilder object. Use the imported grammar file or rule as a complete grammar or as a component in a grammar's broader development within the GrammarBuilder object.

  • SrgsDocument(String) constructor on the SrgsDocument class.

    You can develop the grammar further in the SrgsDocument object or build it into a Grammar object for loading by the speech recognition engine.

  • Constructors on the SrgsRuleRef class.

    This class corresponds to the ruleref element as defined by SRGS. Use these constructors to create references to existing grammar files or rules, which the speech recognition engine can use at run time. See the SrgsRuleRef()()()() constructors.

This section includes reference information and examples for creating grammars using XML. You can use the following links to learn about creating grammars, to achieve specific tasks related to speech recognition, and to get detailed information about the support for SRGS by the Speech Platform SDK 11.

In This Section

  • How to Create a Basic XML Grammar (Microsoft.Speech)

    Provides instructions for designing and authoring a simple grammar.

  • SRGS Grammar XML Reference (Microsoft.Speech)

    Lists and describes SRGS XML grammar elements as implemented in the Speech Platform SDK 11.

  • Semantic Interpretation Markup (Microsoft.Speech)

    Introduces semantic interpretation and describes how to use semantic interpretation markup in an XML-format grammar.

  • Semantic Markup Language Reference (Microsoft.Speech)

    Describes the structure and content of SML output and the serialization of semantic results into Semantic Markup Language (SML) output.

See Also

Concepts

Grammars Overview (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


How to Create a Basic XML Grammar (Microsoft.Speech)

[image]

How to Create a Basic XML Grammar (Microsoft.Speech)
Send Feedback

A grammar contains a set of rules that specify the spoken words and phrases that a speech-enabled application will recognize. A grammar must provide structured, logical speech statements that apply to specific situations. At the same time, a grammar must be general enough to allow slight variations in a statement to enable a more natural speaking style and to provide a better user experience. You can define a grammar structure that uses different elements in a specific sequence to provide the user with logical variations of phrases or single word options.

This section contains topics that demonstrate the process for designing and authoring a simple grammar from basic grammar rules. Each example builds on the previous example and adds a degree of complexity.

In This Section

  • Create a List of User Commands (Microsoft.Speech)

  • Create an XML Grammar Structure (Microsoft.Speech)

  • Create Alternative User Commands (Microsoft.Speech)

  • Create Variations of User Commands (Microsoft.Speech)

  • Create Grammars with Multiple Active Rules (Microsoft.Speech)

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Create a List of User Commands (Microsoft.Speech)

[image]

Create a List of User Commands (Microsoft.Speech)
Send Feedback

Before you begin creating grammar files, you will need to envision and define how users will interact with your application by speaking. For example you may want to consider the following factors:

  • Which application contexts are good candidates for voice interaction?

  • What actions or application behavior can a user initiate using her voice?

  • What words can a user say to initiate each action or behavior?

  • How will users know when they can speak to the application and what they can say?

Having made basic design decisions, you can begin to define the speech vocabulary for your application. Determine the words that a user of your application is likely to say.

  • Make a list of all the actions that a user can initiate in your application by speaking.

  • For each action, list the words or phrases that a user can say to initiate the action.

For example, if your application plays music files, it will likely include actions to begin, pause, and stop playback of a music file. Include these actions in your list and define the words that users can say to initiate each action, as suggested in the following table.

Action | Spoken input
Begin playback | Play, play the song, play the tune, play the track, begin, begin playback, go, start
Pause playback | Pause, pause the song, pause the tune, pause the track, pause playback, suspend, wait, hold
Stop playback | Stop, stop the song, stop the tune, stop playback, end playback, quit

See the next topic, Create an XML Grammar Structure (Microsoft.Speech), to learn how to create the structure that will contain the list of actions and spoken input that you compiled.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Create an XML Grammar Structure (Microsoft.Speech)

[image]

Create an XML Grammar Structure (Microsoft.Speech)
See Also Send Feedback

When you have identified the spoken input that your application will accept, you can enter the words and phrases into an XML grammar structure. This topic shows you how to build a basic XML grammar structure.

The structure of XML-format grammars is defined by the Speech Recognition Grammar Specification (SRGS) Version 1.0. For this example, we will use a basic SRGS-compliant grammar structure, beginning with the grammar element.

The grammar element is the root element of an SRGS grammar. All of the content of an SRGS grammar is contained within the opening and closing tags of the grammar element. See grammar Element (Microsoft.Speech) for more information. For this example, we will specify the following attributes of the grammar element:

  • version. Required identifier that specifies the version of the SRGS specification.

  • xml:lang. Required attribute in voice-mode grammars that specifies the language for the content of the grammar.

  • root. Optional attribute that specifies the name of the rule that is active when the grammar is loaded by a speech recognition engine. Rules that are not the root rule or that are not referenced by the root rule cannot be used for recognition. For this reason, the root rule often contains references to other rules that must be active when the grammar loads.

  • xmlns. Required attribute that specifies the XML namespace.

Using a text editor, enter the grammar element, using the attributes described above with some predefined values:

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" root="rootRule"
 xmlns="http://www.w3.org/2001/06/grammar">

</grammar>

Now we are ready to add a rule to the grammar. Each grammar must contain at least one rule. A grammar rule contains a word or phrase that a user can speak. See rule Element (Microsoft.Speech) for more information. The rule element has the following required attribute:

  • id. Required attribute that specifies a unique identifier for the rule. You can reference a grammar rule by using its id attribute.

Add the rule element to the grammar example, and set the value of its root attribute to rootRule:

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" root="rootRule"
 xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="rootRule">
  </rule>

</grammar>

The rule rootRule will be active when the grammar loads. At this point, the grammar cannot be used for recognition because it does not define any words that a user can speak. For this example, we will add a word to the rule element within an item element. An item element specifies a word or a phrase that a user might say. See item Element (Microsoft.Speech) for more information. A rule element may also contain a word or phrase as unmarked text.

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" root="rootRule"
 xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="rootRule">
    <item> play </item>
  </rule>

</grammar>

The example is now a complete grammar that can be used to recognize the word "play", for example to initiate playback of a selected audio file in your music player application. See the next topic, Create Variations of User Commands (Microsoft.Speech), to learn how to create rules that can match a variety of spoken input.

See Also

Concepts

grammar Element (Microsoft.Speech)
rule Element (Microsoft.Speech)
item Element (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Create Alternative User Commands (Microsoft.Speech)

[image]

Create Alternative User Commands (Microsoft.Speech)
See Also Send Feedback

You may want your application to accept any of several spoken commands to initiate a single action. Different users may vocalize the same intent using a variety of expressions. In this topic we will use the list of actions and spoken input you created in the Create a List of User Commands (Microsoft.Speech) topic to create rules that can be matched with multiple input words or phrase. To contain the list of alternative choices, we will use a new element: one-of.

The one-of element is for defining alternative words or phrases, any of which the user can speak to satisfy the rule. See one-of Element (Microsoft.Speech) for more information. For example, if you want your application to accept both "play" and "start" to initiate playback of a music file, put each word in an item element and enclose the item elements within a one-of element, as shown in the following example:

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" root="rootRule"
 xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="rootRule">
    <one-of>
      <item> play </item>
      <item> start </item>
    </one-of>
  </rule>

</grammar>

This grammar can now be used to recognize the spoken input "play" or "start", either of which will match the rule named rootRule. The application can use the match to initiate playback of a selected audio file.

Continue adding words or phrases to the rule named rootRule that can be used to initiate begin playback of an audio file. Enclose each word or phrase in an item element, and nest it within the one-of element.

See the next topic, Create Variations of User Commands (Microsoft.Speech), to learn how to combine multiple rules into a single rule by using the ruleref element to create rule references.

See Also

Concepts

item Element (Microsoft.Speech)
one-of Element (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Create Variations of User Commands (Microsoft.Speech)

[image]

Create Variations of User Commands (Microsoft.Speech)
See Also Send Feedback

To make the user commands more versatile, create rules that each contain a set of alternative choices that can be referenced by another rule. A rule can contain a reference to another rule that must also be matched in order to match the current rule. Rules that contain only alternative choices can be referenced from within a containing grammar or an external grammar.

To reference another rule element from within a rule element, use the ruleref element. See ruleref Element (Microsoft.Speech) for more information. The ruleref element has one required attribute:

  • Uri. The id of the referenced rule element. If the reference is to a rule element in an external grammar, the name of the grammar file and the id of the rule.

In this topic, you will learn how to create rules that contain multiple components, including a reference to another rule.

First, create a rule element that contains list of alternative words for the play action. Give the rule element an id and add each alternative word to an item element within a one-of element.

XML Copy image Copy Code
  <rule id="playAction">
    <one-of>
      <item> play </item>
      <item> start </item>
      <item> begin </item>
    </one-of>
  </rule>

Next, create a rule element that contains list of alternative words for the file that is the object of a play action.

XML Copy image Copy Code
  <rule id="fileWords">
    <one-of>
      <item> song </item>
      <item> tune </item>
      <item> track </item>
      <item> item </item>
    </one-of>
  </rule>

Now create a top-level rule element that references both the playAction and fileWords rules to create a flexible collection of commands that an application can recognize and use to play a selected music file. The elements within the top-level rule element must be listed in the order that the user will speak the command. This rule element will be the root rule of the grammar.

XML Copy image Copy Code
  <rule id="playCommands">
    <ruleref uri="#playAction" />
    <item> the</item>
    <ruleref uri="#fileWords" />
  </rule>

Now build the grammar by adding the rules you created. Within the opening and closing tags of the grammar element, add the rule element named playCommands, and set the value of the grammar element's root attribute to playCommands. Add the rule element named playAction, and then add the rule element named fileWords.

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" root="playCommands"
 xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="playCommands">
    <ruleref uri="#playAction" />
    <item> the </item>
    <ruleref uri="#fileWords" />
  </rule>

  <rule id="playAction">
    <one-of>
      <item> play </item>
      <item> start </item>
      <item> begin </item>
    </one-of>
  </rule>

  <rule id="fileWords">
    <one-of>
      <item> song </item>
      <item> tune </item>
      <item> track </item>
      <item> item </item>
    </one-of>
  </rule>

</grammar>

The resulting grammar can be used to recognize phrases such as "play the track", "begin the song", and "start the tune". The application can use the recognition of any phrase that can be created by a combination of the elements in the rule named playCommands, as long as the elements are used in the order listed. The grammar will not recognize "the start item".

To this point, all the examples have focused on only one end result: to begin playback of a selected music file. However, you may want to have multiple rules, which are active simultaneously, that play, pause, and stop music playback. That is the focus of the next topic: Create Grammars with Multiple Active Rules (Microsoft.Speech).

See Also

Concepts

ruleref Element (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Create Grammars with Multiple Active Rules (Microsoft.Speech)

[image]

Create Grammars with Multiple Active Rules (Microsoft.Speech)
Send Feedback

The root rule of a grammar is active and ready to use for recognition when the speech recognition engine loads the grammar. All the rules referenced by the root rule are also active when the grammar loads. However, a grammar may contain rules for separate actions that do not reference each other. Each rule is a separate and independent definition that uniquely identifies an action that the user can initiate by speaking.

In this example, we will create a grammar with rules that can be used to begin, pause, or stop playback of a music file. We will create a top-level root rule that contains a reference to the main rule element for each of the play, pause, and stop actions. The end result will be a valid path that begins at the root rule and may go to each rule in the grammar, depending on the spoken input.

We will begin with the grammar that was created in the previous topic, Create Variations of User Commands (Microsoft.Speech). This grammar can only be used to recognize spoken input for beginning the playback of an audio file.

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" root="playCommands"
 xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="playCommands">
    <ruleref uri="#playAction" />
    <item> the </item>
    <ruleref uri="#fileWords" />
  </rule>

  <rule id="playAction">
    <one-of>
      <item> play </item>
      <item> start </item>
      <item> begin </item>
    </one-of>
  </rule>

  <rule id="fileWords">
    <one-of>
      <item> song </item>
      <item> tune </item>
      <item> track </item>
      <item> item </item>
    </one-of>
  </rule>

</grammar>

We will add rules that recognize words for pausing and stopping the playback of a music file, using the list of actions and spoken input from the first topic, Create a List of User Commands (Microsoft.Speech). This next example contains the rules for recognizing pause commands.

XML Copy image Copy Code
  <rule id="pauseCommands">
    <ruleref uri="#pauseAction" />
    <item> the </item>
    <ruleref uri="#fileWords" />
  </rule>

  <rule id="pauseAction">
    <one-of>
      <item> pause </item>
      <item> suspend </item>
      <item> hold </item>
    </one-of>
  </rule>

Since the pause commands refer to the same files as the play commands, we can reuse the rule named fileWords. Now we will create the rules for the stop commands.

XML Copy image Copy Code
<rule id="stopCommands">
    <ruleref uri="#stopAction" />
    <item> the </item>
    <ruleref uri="#fileWords" />
  </rule>

  <rule id="stopAction">
    <one-of>
      <item> stop </item>
      <item> end </item>
      <item> quit </item>
    </one-of>
  </rule>

The rule element named stopCommands will also reuse the rule element named fileWords. We have added rules to pause and stop playback, but these rules are not active because they are not referenced by the root rule. We will create a rule element named top-level that contains a reference to each of the rule elements named playCommands, pauseCommands, and stopCommands. We will make the rule named top-level the root rule for the grammar. Here is the resulting grammar:

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" root="topLevel"
 xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="topLevel">
    <ruleref uri="#playCommands" />
    <ruleref uri="#pauseCommands" />
    <ruleref uri="#stopCommands" />
  </rule>

  <rule id="playCommands">
    <ruleref uri="#playAction" />
    <item> the </item>
    <ruleref uri="#fileWords" />
  </rule>

  <rule id="playAction">
    <one-of>
      <item> play </item>
      <item> start </item>
      <item> begin </item>
    </one-of>
  </rule>

  <rule id="pauseCommands">
    <ruleref uri="#pauseAction" />
    <item> the </item>
    <ruleref uri="#fileWords" />
  </rule>

  <rule id="pauseAction">
    <one-of>
      <item> pause </item>
      <item> suspend </item>
      <item> hold </item>
    </one-of>
  </rule>

<rule id="stopCommands">
    <ruleref uri="#stopAction" />
    <item> the </item>
    <ruleref uri="#fileWords" />
  </rule>

  <rule id="stopAction">
    <one-of>
      <item> stop </item>
      <item> end </item>
      <item> quit </item>
    </one-of>
  </rule>

  <rule id="fileWords">
    <one-of>
      <item> song </item>
      <item> tune </item>
      <item> track </item>
      <item> item </item>
    </one-of>
  </rule>

</grammar>

To view a grammar of greater complexity that incorporates semantic definitions, see Grammar Example: Solitaire (Microsoft.Speech).

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SRGS Grammar XML Reference (Microsoft.Speech)

[image]

SRGS Grammar XML Reference (Microsoft.Speech)
Send Feedback

The Microsoft Speech Platform SDK 11 supports grammar files that use Extensible Markup Language (XML) elements and attributes, as specified in the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0. These XML elements and attributes represent the rule structures that define the words or phrases (commands) recognized by speech recognition engines.

This section documents the elements and attributes of the SRGS specification, as implemented by the Speech Platform SDK 11. Note that support for XML-format grammars in the Speech Platform SDK 11 differs from the SRGS specification in some areas. These differences are described in the topics of the elements to which they apply.

SRGS Grammar Elements

The following table describes the XML grammar elements from the SRGS specification, listed in alphabetical order.

Element | Description | Required/Optional | Attributes
example | Specifies sample phrases that a user can say to match the containing rule. This element is illustrative and for the benefit of a developer reading the grammar; the speech recognition engine ignores it. | Optional | -
grammar | Specifies the highest level container for an XML grammar definition. | Required | version, mode, root, tag-format, xml:lang, xml:base, xmlns
item | Contains any legal rule expansion. | Optional | repeat, repeat-prob, weight
lexicon | Specifies one or more external pronunciation lexicon documents. | Optional | uri, type
meta | Specifies document metadata. | Optional | name, content
metadata | Contains information about the document in a metadata schema. | Optional | -
one-of | Specifies a set of alternative phrases that can possibly be matched by a user. | Optional | -
rule | Specifies the definition of a sequence of phrases that, if matched by user input, must be matched in the sequence specified in the definition. | Required | id, scope, sapi:dynamic
ruleref | Specifies a reference to the rule to be imported. | Optional | uri, special, type
tag | Specifies semantic information and/or ECMA-compliant script that allows for the return of additional information when an element or series of elements is recognized. | Optional | -
token | Specifies a string that a speech recognizer can convert to a phonetic representation. | Optional | sapi:pron, sapi:display
Note Note

The meta, metadata and lexicon elements must occur before all rule elements contained with the root grammar element. There are no constraints on the ordering of the metadata, meta and lexicon elements.

Additional SRGS Format Information

The following table lists elements and features of XML documents that are not specific to grammar files.

Topic | Description
XML DOCTYPE Declaration | Specifies a reference to the grammar's associated Document Type Definition (DTD).
XML Header | Specifies the XML version number, and optionally the character encodings, as part of a grammar document's XML declaration on the first line of the document.
Comments in GRXML Documents | Can be used to specify the description of a rule.
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


XML DOCTYPE Declaration (Microsoft.Speech)

[image]

XML DOCTYPE Declaration (Microsoft.Speech)
Send Feedback

Specifies a reference to a grammar's Document Type Definition (DTD), if applicable. In an XML grammar document, the DOCTYPE declaration is followed by the root grammar element.

Example

The following example illustrates referencing an external DTD.

XML Copy image Copy Code
<?xml encoding="ISO-8859-1"?>

<!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN"
    "http://www.w3.org/TR/speech-grammar/grammar.dtd">

<grammar version="1.0" xmlns="http://www.w3.org/2001/06/grammar"
    xml:lang="en-US" tag-format="semantics/1.0" ... >
   ...
</grammar>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


XML Header (Microsoft.Speech)

[image]

XML Header (Microsoft.Speech)
Send Feedback

Specifies the XML version number, and optionally the character encodings, as part of a grammar document's XML declaration on the first line of the document. This header must appear on the first line of all XML documents; therefore, all XML Grammar documents must have the XML header at the top. It is an accepted convention to use the .grxml file extension for XML-based grammar documents that conform to the Speech Recognition Grammar Specification Version 1.0 specification.

Example

The following examples demonstrate XML headers with and without the character encoding declaration.

XML Copy image Copy Code
<!-- With character encoding. -->
<?xml encoding="ISO-8859-1"?>
<grammar version="1.0" xmlns="http://www.w3.org/2001/06/grammar"
 xml:lang="en-US" tag-format="semantics/1.0" ...>
         ...
</grammar>
XML Copy image Copy Code
<!-- Without character encoding. -->
<?xml?>
<grammar version="1.0" xmlns="http://www.w3.org/2001/06/grammar"
 xml:lang="en-US" tag-format="semantics/1.0" ...>
         ...
</grammar>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Comments in .grxml Grammar Files (Microsoft.Speech)

[image]

Comments in .grxml Grammar Files (Microsoft.Speech)
Send Feedback

The Microsoft Speech Platform SDK 11 supports grammar files that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0.

It is an accepted convention to use the .grxml file extension for XML-based grammar documents that conform to the SRGS specification. Comments in .grxml grammar files are enclosed between the string sequences <!-- and -->.

Syntax

XML Copy image Copy Code
<!-- Grammar_rule_description -->

Attributes

None.

Example

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar xml:lang="en-US" root="BlueGreen" tag-format="semantics/1.0" version="1.0"
xmlns="http://www.w3.org/2001/06/grammar">

<!-- This rule recognizes the color names "blue", "indigo", "azure", "green", -->
<!-- "teal", and "emerald", and returns the text of the recognized color and -->
<!-- a semantic value. -->

  <rule id="BlueGreen" scope="public">
    <item>
      <one-of>
        <item> <ruleref uri="#Blue"/> <tag> out.color=rules.Blue; </tag> </item>
        <item> <ruleref uri="#Green"/> <tag> out.color=rules.Green; </tag> </item>
      </one-of>
    </item>
  </rule>

  <rule id="Blue" scope="public">
    <tag> out="blue"; </tag>
    <one-of>
      <item> blue </item>
      <item> indigo </item>
      <item> azure </item>
    </one-of>
  </rule>

  <rule id="Green" scope="public">
    <tag> out="green"; </tag>
    <one-of>
      <item> green </item>
      <item> teal </item>
      <item> emerald </item>
    </one-of>
  </rule>

</grammar>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


example Element (Microsoft.Speech)

[image]

example Element (Microsoft.Speech)
Send Feedback

Specifies sample phrases that a user can say to match the containing rule. This element is illustrative and for the benefit of a developer reading the grammar; the speech recognition engine ignores it.

Syntax

XML Copy image Copy Code
<example>...</example>

Attributes

None.

Example

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar xml:lang="en-US" root="BlueGreen" tag-format="semantics/1.0" version="1.0"
xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="BlueGreen" scope="public">

    <example> blue </example>
    <example> indigo </example>
    <example> green </example>
    <example> emerald </example>

    <item>
      <one-of>
        <item> <ruleref uri="#Blue"/> <tag> out.color=rules.Blue; </tag> </item>
        <item> <ruleref uri="#Green"/> <tag> out.color=rules.Green; </tag> </item>
      </one-of>
    </item>
  </rule>

  <rule id="Blue" scope="public">
    <tag> out="blue"; </tag>
    <one-of>
      <item> blue </item>
      <item> indigo </item>
      <item> azure </item>
    </one-of>
  </rule>

  <rule id="Green" scope="public">
    <tag> out="green"; </tag>
    <one-of>
      <item> green </item>
      <item> teal </item>
      <item> emerald </item>
    </one-of>
  </rule>

</grammar>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


grammar Element (Microsoft.Speech)

[image]

grammar Element (Microsoft.Speech)
Send Feedback

Specifies the highest level container for an XML grammar definition. This element is required to make a valid grammar.

Syntax

XML Copy image Copy Code
<grammar
   version = "1.0"
   mode = "voice | dtmf"
   root = "string"
   tag-format = (semantics/1.0 | semantics-ms/1.0 | semantics/1.0-literals)
   xml:lang = "language code-country/region code"
   xml:base = "grammarBaseUri"
   xmlns = "http://www.w3.org/2001/06/grammar"
   xmlns:sapi= "http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions">
   sapi:alphabet= (ipa | x-microsoft-ups | x-microsoft-sapi)
</grammar>

Attributes

Attribute

Description

version

Required. Specifies the version number of the Speech Recognition Grammar Specification used. The only accepted value is 1.0.

mode

Optional. Specifies the mode of the contained or referenced grammar. The mode can be one of the following values.

  • voice for spoken input

  • dtmf for dual tone multi-frequency (DTMF) input

If omitted, the default value is voice.

root

Optional. Specifies the name of the default grammar rule. If omitted, the grammar passes validation checks and compiles, but does not trigger recognition. The rule declared as the root rule must be defined within the scope of the grammar. The root rule can be scoped as either public or private.

tag-format

Required if a grammar contains tag elements, this attribute specifies the content type of all tag elements contained within a grammar. This attribute takes one of the following values:

  • semantics/1.0 declares that the content within tag elements is ECMAScript.

  • semantics-ms/1.0 declares that the content within tag elements is ECMAScript as implemented by Microsoft.

  • semantics/1.0-literals declares that the content within tag elements is a boolean, an integer, a float, or a string. A string CANNOT be enclosed in double quotes.

xml:lang

Required if the value of the mode attribute is voice, optional if the value of the mode attribute is dtmf. Declares the single language for the content of the containing grammar document. The value may contain either a lower-case, two-letter language code, (such as "en" for English or "fr" for French) or may optionally include an upper-case, country/region or other variation in addition to the language code. Examples with a county/region code include "es-US" for Spanish as spoken in the US, or "fr-CA" for French as spoken in Canada. See the Remarks section for additional information.

xml:base

Optional. Specifies a grammar document's base Uniform Resource Identifier (URI). The value for xml:base is used to resolve relative URIs in a grammar document. For example, a grammar file declares:
xml:base="http://www.contoso.com/"
and contains a relative reference to another document, for example:
<ruleref uri="ExternalGrammar.grxml">
This creates the following absolute path to the document:
http://www.contoso.com/ExternalGrammar.grxml.

xmlns

Required. Specifies the XML namespace for W3C speech recognition grammar. The XML namespace is http://www.w3.org/2001/06/grammar.

xmlns:xsi

Optional. Defines a namespace prefix. Required only when the grammar uses the sapi:alphabet attribute, the sapi:dynamic attribute of the rule element, or the sapi:pron attribute of the token element. When used, attribute and value must appear as follows: xmlns:sapi="http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions"

sapi:alphabet

Optional. Specifies the phonetic alphabet to use for pronunciations defined in the sapi:pron attribute of token elements. Valid values are ipa, x-microsoft-ups, and x-microsoft-sapi. When using sapi:alphabet, the grammar element must contain the following declaration: xmlns:sapi="http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions"

Remarks

The model and syntax indicated by the tag-format values semantics/1.0 and semantics/1.0-literals are defined in the W3C specification recommendation Semantic Interpretation for Speech Recognition (SISR) Version 1.0. The tag-format value semantics-ms/1.0 indicates a model and syntax defined by Microsoft. See Support for Semantic Markup for more information.

The content of tag elements in a grammar must be of the type declared in the grammar element's tag-format attribute. Using a string literal syntax when the value of tag-format is semantics/1.0 or semantics-ms/1.0 will generally result in a runtime error. Using the ECMAScript syntax when the value of tag-format is semantics/1.0-literals will not produce a runtime error, but will erroneously populate Rule Variables with ECMAScript code. See tag Element (Microsoft.Speech) for more information and examples that use the syntax for each of the values of tag-format.

For a given language code declared in the xml:lang attribute, a speech recognition engine that supports that language code must be installed for the grammar to be loaded successfully. The Microsoft Speech Platform Runtime 11 and Microsoft Speech Platform SDK 11 do not include any installed languages. You must download a language pack for each language on which you want to perform speech recognition.

The language packs are different for each version of the Speech Platform Runtime. You must download the language pack version that matches the version of the Speech Platform Runtime that you have installed. The language packs for the Speech Platform SDK 11 are for server-based applications and are different than the languages that ship with Windows Vista or Windows 7. Use the following links to download the version of the server language packs that match your Speech Platform Runtime version:

  • Server Language Packs v11.0

  • Server Language Packs v10.2

  • Server Language Packs v10.1

  • Server Language Packs v10.0

See Language Support for a list of languages for which you can download language packs.

The Speech Platform SDK 11 accepts all valid language-country codes. If the grammar element specifies only a language code, and not a country/region code, for the xml:lang attribute (such as xml:lang="en"), then any installed recognizer that expresses support for that generic, region-independent language will be able to load the grammar. See Language Identifier Constants and Strings for a comprehensive list of language codes.

The Speech Platform SDK 11 does not currently support grammars that specify multiple languages. This is a departure from the Speech Recognition Grammar Specification (SRGS) Version 1.0, which allows for a grammar processor to optionally support multiple languages. For example, the SDK does not permit a grammar such as the one shown in the following example:

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-GB" xmlns="http://www.w3.org/2001/06/grammar" root="Digits">
  <rule id="Digits">
    <one-of>
      <item xml:lang="fr-FR">deux</item>
    </one-of>
  </rule>
</grammar>

To support multiple languages for your applications, you can use multiple grammars in parallel, each with a separate single language. An application's recognition engine may load and independently enable or disable one or more grammar files.

Note Note

The Speech Platform SDK 11 does support multiple languages in Speech Synthesis Markup Language (SSML) documents used to create prompts for synthesized speech. See speak Element (Microsoft.Speech)

Example

The following is an example of a simple grammar that declares all the attributes of the grammar element:

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar
   version="1.0" mode="voice" root="Welcome"
   tag-format="semantics/1.0" xml:lang="en-US"
   xml:base="http://www.contoso.com/"
   xmlns="http://www.w3.org/2001/06/grammar"
   xmlns:sapi="http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions">

<rule id="Welcome">
   <item>
      Welcome to the managed code API for speech on servers.
   </item>
</rule>

</grammar>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


item Element (Microsoft.Speech)

[image]

item Element (Microsoft.Speech)
Send Feedback

Contains any valid rule expansion. A valid rule expansion can consist of a word or other entity that can be spoken, such as content in token elements, a ruleref element, a tag element, or any logical combination of these. When an item element contains a combination of rule expansions (for example, a combination of words), the sequence in which the contents of the item element are listed must match the sequence in which the content occurs in the input for recognition to be successful.

Syntax

XML Copy image Copy Code
<item
    repeat = (n | m-n | m- | 0-1)
    repeat-prob = (n | n. | n.nnnn | .nnnn)
    weight = (n | n. | .n | n.n)
</item>

Attributes

The item element takes the following attributes:

Attribute | Description
repeat | Optional. Specifies the number of times a contained expansion can be repeated. The value of this attribute can be any positive integer, or any range of positive integers, but cannot be 0 (zero). The value of this attribute applies to the entire content of the item element. If omitted, the content of the item element must occur exactly once in the input. A value of m- indicates that the item must occur a minimum of m times and can be repeated an infinite number of times. For example, a value of 1- indicates that the content of the item element can occur from one to any number of times. A value of 0-1 indicates that the occurrence of the content of the item element in the input is optional (a speaker can utter the content either zero times or one time).
repeat-prob | Optional. Specifies the probability of successive repetition of a repeated item. Applies only to items that have a repeat attribute. The value of this attributes is a positive floating-point value between 0.0 and 1.0 (inclusive). For example, a repeat-prob value of 0.8 indicates an 80% probability that the item is repeated.
weight | Optional. Specifies a multiplying factor that increases or decreases the likelihood that an alternative word or phrase is chosen from an expansion of alternative words or phrases. The value of this attribute is a positive floating-point value. Alternatives that do not have a weight specified have the default weight value of 1.0. A weight greater than 1.0 positively biases the alternative against alternatives that have no weight assigned, and a weight less than 1.0 negatively biases an alternative against alternatives that have no weight assigned.

Remarks

Use the item element to contain a rule expansion when it is necessary to make the rule expansion either optional or repeatable (in other words, in cases where the repeat attribute must be used). When the item element is contained in a one-of element, use the item element to contain a rule expansion when it is necessary to assign a weight to the rule expansion (in other words, in cases where the weight attribute must be used).

The effects of any tag elements contained within an item element are applied to the entire contents of the item element.

You can assign values to the weight attribute that are greater than or less than 1.0 to each alternative in an expansion. An alternative's weight in comparison to other alternatives in an expansion determines its bias. For example, if the alternatives in an expansion have weights of .2, .5, and .7, the alternative with the weight of .7 would have the highest bias, even though its weight is less than 1.0. If another alternative in the same expansion did not have an assigned weight (it receives the default weight 1.0), it would have a higher bias than the alternatives with weights of .2, .5, and .7. In the example below, "medium" has a higher bias than "small", but a lower bias than "large".

Unlike the Speech Recognition Grammar Specification (SRGS) Version 1.0 specification, the Microsoft Speech Platform SDK 11 does not support the use of the xml:lang attribute on the item element. Grammars in the Speech Platform SDK 11 can contain only one language, and this must be declared in the grammar Element (Microsoft.Speech). To support multiple languages for your applications, you can use multiple grammars in parallel, each with a separate single language.

Example

XML Copy image Copy Code
<grammar root="PizzaSize" version="1.0" xmlns="http://www.w3.org/2001/06/grammar"
 xml:lang="en-US" tag-format="semantics/1.0">
  <rule id="PizzaSize" scope="public">
   <item repeat="0-1" repeat-prob=".4"> I would like </item>
    a
    <one-of>
      <item weight=".5"> small </item>
      <item> medium</item>
      <item weight="2"> large </item>
    </one-of>
    pizza
  </rule>
</grammar>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


lexicon Element (Microsoft.Speech)

[image]

lexicon Element (Microsoft.Speech)
Send Feedback

Specifies an external pronunciation lexicon file.

Syntax

XML Copy image Copy Code
<lexicon
    uri = lexiconURI
    type = mediaType />

Attributes

Attribute | Description
uri | Required. Specifies the location of the pronunciation lexicon, which is a relative URI or an absolute URI.
type | Optional. Specifies the media type of the pronunciation lexicon document. Two values are currently supported. The value application/vdn.ms-sapi-lex indicates the lexicon format is Uncompressed Lexicon, a format created by Microsoft. The value application/pls+xml indicates that the lexicon conforms to the Pronunciation Lexicon Specification (PLS) Version 1.0 specification.

Remarks

Lexicons contain the mapping between the pronunciations and the written representations of words or short phrases. You can use lexicons to improve the accuracy of speech recognition or to customize the vocabulary and pronunciations of a synthesized voice.

In Microsoft.Speech, each grammar document can reference only one lexicon. This is a departure from the Speech Recognition Grammar Specification (SRGS) Version 1.0.

The lexicon element must be placed after the opening tag of the grammar element and before the first rule element in the grammar element.

The pronunciation information provided by a lexicon is specific to the single language declared in the xml:lang attribute of the grammar element, and is used only for content defined within the enclosing SRGS document.

Example

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" tag-format="semantics/1.0"
 xmlns="http://www.w3.org/2001/06/grammar"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.w3.org/2001/06/grammar
                     http://www.w3.org/TR/speech-grammar/grammar.xsd">

    <lexicon uri="http://www.thephone-company.com/lexicon.lex" type="application/vdn.ms-sapi-lex"/>

</grammar>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


meta Element (Microsoft.Speech)

[image]

meta Element (Microsoft.Speech)
Send Feedback

Specifies document metadata. Metadata is information about a document in contrast to the document content.

Syntax

XML Copy image Copy Code
<meta
  name = "string"
  http-equiv = "string"
  content = "string" />

Attributes

Attribute | Description
name | Optional. Specifies the property name of the metadata. All meta elements must specify a name attribute or an http-equiv attribute, but not both.
http-equiv | Optional. Binds the meta element to the HTTP response header, specifying information that should be included in that response header. All meta elements must specify a name attribute or an http-equiv attribute, but not both. Use only values that are known by the Web server or defined in the Document Type Definition (DTD).
content | Required. Specifies the value of the metadata property identified by the name attribute. When the value of the name attribute is base, the value of the content attribute must be a Uniform Resource Identifier (URI) that specifies the location of the grammar document's base URI. External rule references within the grammar that do not specify an absolute path are resolved relative to the location specified by this URI.

Remarks

The meta element must occur before all rule elements contained with the root grammar element. There are no constraints on the ordering of meta elements.

The function of <meta name="base" content="..."/> is identical to the function of the xml:base attribute of the grammar element. If both are present in a grammar file, the value of xml:base overrides <meta name="base" content="..."/>.

Example

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" tag-format="semantics/1.0"
 xmlns="http://www.w3.org/2001/06/grammar"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.w3.org/2001/06/grammar
           http://www.w3.org/TR/speech-grammar/grammar.xsd">
  <meta name="Creator" content="Adam Barr" />
  <meta name="seeAlso" content=
"http://www.adatum.com/grammar-metadata.xml" type="media-type"/>
  <meta http-equiv="Expires" content="0" />
  <meta http-equiv="Date" content="Tue, 19 Oct 2004 10:41:00 GMT" />
  <meta name="base" content="C:\grammars\" />
</grammar>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


metadata Element (Microsoft.Speech)

[image]

metadata Element (Microsoft.Speech)
Send Feedback

Contains information about the grammar document in a metadata schema.

Syntax

XML Copy image Copy Code
<metadata>...</metadata>

Attributes

None.

Remarks

The metadata element may be located either before or after meta or lexicon elements, but must occur before all rule elements contained within the root grammar element.

The metadata element is a container in which authors can place information about the document using a metadata schema. Authors can use any metadata schema. However, the Speech Recognition Grammar Specification (SRGS) Version 1.0 recommends that authors use the Resource Description Format (RDF) schema in conjunction with the general metadata properties (for example, Title, Creator, Subject, Description, and Copyrights) defined in the Dublin Core Metadata Initiative.

Example

XML Copy image Copy Code
<?xml version="1.0"?>
<grammar
    xmlns="http://www.w3.org/2001/06/grammar" version="1.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.w3.org/2001/06/grammar
    http://www.w3.org/TR/speech-grammar/grammar.xsd"
    xml:lang="en-US">

  <metadata>
   <rdf:RDF
       xmlns:rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
       xmlns:rdfs = "http://www.w3.org/TR/1999/PR-rdf-schema-19990303#"
       xmlns:dc = "http://purl.org/metadata/dublin_core#">

   <!-- Metadata about the grammar document -->
   <rdf:Description about="http://www.example.com/meta.grxml"
       dc:Title="Digit Grammar"
       dc:Description="Digit Grammar in W3C XML Form"
       dc:Publisher="W3C"
       dc:Language="en"
       dc:Date="2002-02-14"
       dc:Rights="Copyright 2002 Jan Smith"
       dc:Format="application/srgs+xml" >
       <dc:Creator>
          <rdf:Seq ID="CreatorsAlphabeticalBySurname">
             <rdf:li>Jackie Crystal</rdf:li>
             <rdf:li>Jan Smith</rdf:li>
          </rdf:Seq>
       </dc:Creator>
   </rdf:Description>
  </rdf:RDF>
 </metadata>

</grammar>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


one-of Element (Microsoft.Speech)

[image]

one-of Element (Microsoft.Speech)
Send Feedback

Specifies a set of alternative phrases that can possibly be matched by a user. Each alternative word or phrase must be enclosed within an item element.

Syntax

XML Copy image Copy Code
<one-of>...</one-of>

Attributes

None.

Remarks

Unlike the Speech Recognition Grammar Specification (SRGS) Version 1.0 specification, the Microsoft Speech Platform SDK 11 does not support the use of the xml:lang attribute on the one-of element. Grammars in the Speech Platform SDK 11 can contain only one language, and this must be declared in the grammar Element (Microsoft.Speech). To support multiple languages for your applications, you can use multiple grammars in parallel, each with a separate single language.

Example

The rule named PhoneRule in the grammar shown below recognizes the following utterances:

  • call

  • call him

  • call her

  • call them

  • phone

  • phone him

  • phone her

  • phone them

The repeat attribute on the second item element indicates that the words in the one-of element can be spoken zero or one time, making them optional.

XML Copy image Copy Code
<grammar root="PhoneRule" version="1.0" xmlns="http://www.w3.org/2001/06/grammar"
 xml:lang="en-US" tag-format="semantics/1.0">

  <rule id="PhoneRule" scope="public">
    <item>
      <one-of>
        <item> call </item>
        <item> phone </item>
      </one-of>
    </item>

    <item repeat="0-1">
      <one-of>
        <item> him </item>
        <item> her </item>
        <item> them </item>
      </one-of>
    </item>
  </rule>

</grammar>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


rule Element (Microsoft.Speech)

[image]

rule Element (Microsoft.Speech)
See Also Send Feedback

The rule element defines a grammar rule. A rule element contains text or XML elements that define what speakers can say, and the order in which they can say it. The rule element associates a valid rule definition with a rule name and sets the scope of the rule definition. A valid rule element must contain at least one piece of recognizable text or one rule reference. A valid grammar must contain at least one rule element.

Syntax

XML Copy image Copy Code
<rule
   id = "string"
   scope = (public | private)
   sapi:dynamic = (true | false) >
</rule>

Attributes

Attribute

Description

id

Required. Specifies the name that identifies the rule. The rule name must be unique within the containing grammar or rule namespace. The same rule name can be used in multiple grammars. The rule name is a case-sensitive character sequence that is a valid XML name, does not contain the characters ".", ":", or "-", and is not the name of a special rule (NULL, VOID, or GARBAGE).

scope

Optional. Specifies whether the rule can be used only within its containing grammar or referenced by another grammar. If specified, this attribute must have one of the following values:

  • private: The rule is visible only within its containing grammar. A private rule can be referenced by an external grammar if the rule is declared as the root rule of its containing grammar.

  • public: The rule can be referenced by an external grammar (in a ruleref element in the grammar making the reference). A public rule can always be activated for recognition. If omitted, the default value is private.

sapi:dynamic

Optional. Specifies whether the rule can be modified dynamically. Values are true or false. If specified, the containing grammar element must have the following attribute-value pair:

xmlns:sapi="http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions"

Remarks

A rule element can contain unmarked text or any of the ruleref, item, one-of, token, or tag elements. A rule element cannot be empty or contain only white space; however, it can contain empty elements, thus making it empty in grammar logic.

A rule can be identified as the root rule of the grammar that contains it by using the root attribute on the grammar element. The root rule is the default rule used by a ruleref element when that reference specifies only a grammar, and not a specific rule name within that grammar.

Examples

The following example demonstrates that the publicRulerule can be referenced by a rule contained in an external grammar.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-US" mode="voice" root="publicRule"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="publicRule" scope="public">
    <item> This content is accessible by an external grammar. </item>
  </rule>

</grammar>

The following example demonstrates private rules. Although the rule named referenceYes is scoped as private, it can be referenced by an external grammar because it is the root rule of its containing grammar. The rule named referenceNo cannot be referenced by an external grammar.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-US" mode="voice" root="referenceYes"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="referenceYes" scope="private">
    <one-of>
      <item> Yes </item>
      <item> Yep </item>
    </one-of>
  </rule>

  <rule id="referenceNo" scope="private">
    <one-of>
      <item> No </item>
      <item> Nope </item>
    </one-of>
  </rule>

</grammar>

The following example demonstrates how to reference rules using ruleref elements. The first ruleref element in the "CustomerInfo.grxml" grammar points to the rule named food in the grammar "RestaurantInfo.grxml". This is a valid rule reference even though the rule named food is scoped as private, because it is declared as the root rule of the "RestaurantInfo.grxml" grammar.

The second ruleref element in "CustomerInfo.grxml" references the public rule named location in "RestaurantInfo.grxml".

XML Copy image Copy Code
<!-- Grammar file "customerInfo.grxml" -->
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-US" mode="voice" root="customers"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="customers">
    <item repeat="0-1"> I would like </item>
    <ruleref uri="RestaurantInfo.grxml"/>
    <item repeat="0-1">in</item>
    <ruleref uri="restaurantInfo.grxml#location"/>
  </rule>

</grammar>
XML Copy image Copy Code
<!-- Grammar file "RestaurantInfo.grxml" -->
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-US" mode="voice" root="food"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="food" scope="private">
    <one-of>
      <item> Italian </item>
      <item> Thai </item>
    </one-of>
  </rule>

  <rule id="location" scope="public">
    <one-of>
      <item> Bellevue </item>
      <item> Redmond </item>
      <item> Seattle </item>
    </one-of>
  </rule>

</grammar>

See Also

Concepts

Grammar Rules (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ruleref Element (Microsoft.Speech)

[image]

ruleref Element (Microsoft.Speech)
See Also Send Feedback

The ruleref element specifies a reference by the containing rule to another rule, either in the same grammar or in an external grammar. The referenced rule defines user input that must be matched for successful recognition of the containing rule. This element is especially useful for reusing using rules and grammars that contain content which does not change frequently, such as a list of cities or a rule for recognizing phone numbers.

Syntax

XML Copy image Copy Code
<ruleref
   uri = "ruleLocation"
   special = (NULL | VOID | GARBAGE)
   type = "media-type"
</ruleref>

Attributes

Attribute

Description

uri

Optional. Specifies the location of the rule to be referenced. A rule can be referenced using one of the following forms:

  • <ruleref uri="#rulename"/>: Specifies a reference to a local rule. Refers to a rule within the containing grammar.

  • <ruleref uri="grammarUri#rulename"/>: Specifies a reference to an external named rule of a grammar.

  • <ruleref uri="grammarUri"/>: Specifies a reference to the external root rule of a grammar.

  • <ruleref uri="grammarUri#rulename" type="media-type"/>: Specifies a reference to an external named rule of a grammar, with an associated media type.

  • <ruleref uri="grammarUri" type="media-type"/>: Specifies a reference to the external root rule of a grammar, with an associated media type.

Either the uri or the special attribute is required, but both cannot be used together.

special

Optional. Specifies a reference to a rule that has specific interpretation and processing by a speech recognizer. A grammar must not redefine these special rule names. The special rule names are as follows:

  • NULL: Defines a rule that is automatically matched, meaning that the rule is matched without the user speaking any word.

  • VOID: Defines a rule that can never be spoken. Inserting VOID into a sequence automatically makes that sequence unspeakable.

  • GARBAGE: Defines a rule that can match any speech up until the next rule match, the content of the next token element, or until the end of spoken input.

Either the special or the uri attribute is required, but both cannot be used together.

type

Optional. Specifies the media type of the grammar containing the reference. Consider using this attribute only as a last choice. For example, using this attribute can be appropriate when a grammar is retrieved through HTTP and both of the following are true:

  • A Web server cannot be configured to indicate the correct media type.

  • The grammar processor is unable to automatically detect the media type.

Remarks

The ruleref element is an empty element that allows authors to reuse rules and grammars. For example, a grammar author can develop a series of grammars that support mathematic operations and numbers. The grammars can be redistributed using either a Web site or a compiled grammar. Other authors can use the distributed grammars by adding a ruleref element to their own grammar referencing the appropriate file or resource location. By reusing existing rules, authors can more quickly build complex grammars.

You can also use ruleref elements to structure semantic properties into a hierarchy. See Grammar Example: Solitaire (Microsoft.Speech) for an example of a grammar that uses ruleref elements to build and organize a grammar.

Examples

The following are examples of typical uses for the ruleref element in grammar authoring.

Rule Reference within a Grammar

The following example demonstrates using a ruleref element to reference the rule named city in the containing grammar "CityList.grxml".

XML Copy image Copy Code
<!-- Grammar file "cityList.grxml" -->
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-US" mode="voice" root="location"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="location">
    <item> Fly me to <\item>
    <ruleref uri="#city"/>
  </rule>

  <rule id="city">
    <one-of>
      <item> Boston </item>
      <item> Madrid </item>
    </one-of>
  </rule>

</grammar>

Rule Reference Outside a Grammar

The following example uses a ruleref element in the grammar file "Locations.grxml" to reference the external grammar file "StateList.grxml". Because the ruleref element does not specify a rule name, the reference points to the root rule in "StateList.grxml", which has the identifier states.

XML Copy image Copy Code
<!-- Grammar file "locations.grxml" -->
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-US" mode="voice" root="getState"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="getState">
    <item> My home state is </item>
    <ruleref uri="c:\Grammars\stateList.grxml"/>
  </rule>

</grammar>

<!-- Grammar file "stateList.grxml" -->
<?xml version="1.0" encoding="utf-8"?>
<grammar root="states" version="1.0" xmlns="http://www.w3.org/2001/06/grammar"
 xml:lang="en-US" tag-format="semantics/1.0">

  <rule id="states" scope="public">
    <one-of>
     <item> Alabama </item>
     <item> Alaska </item>
     <item> Arizona </item>
     <item> Arkansas </item>
     ...
    </one-of>
  </rule>

</grammar>

Rule References to Public and Private External Rules

The following example uses two ruleref elements in the grammar file "FindFood.grxml" to reference two external rules contained in the grammar file "restaurantInfo.grxml". The grammar "restaurantInfo.grxml" does not specify a root rule, so it cannot be loaded by a speech recognition engine. However, the rules in the grammar can be imported by other grammars, using the ruleref element, but only if the value of a rule's scope attribute is public. Note that the uri attribute of the ruleref elements includes the name of the grammar and the name of the rule.

XML Copy image Copy Code
<!-- Grammar file "FindFood.grxml" -->
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-US" mode="voice" root="getRestaurantInfo"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="getRestaurantInfo">
    <item repeat="0-1"> Find </item>
    <ruleref uri="restaurantInfo.grxml#food"/>
    <item repeat="0-1"> food near </item>
    <ruleref uri="restaurantInfo.grxml#location"/>
  </rule>

</grammar>

<!-- Grammar file "restaurantInfo.grxml" -->
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-US" mode="voice"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="food" scope="public">
    <one-of>
      <item> Italian </item>
      <item> Thai </item>
      <item> Fast </item>
    </one-of>
  </rule>

  <rule id="location" scope="public">
    <one-of>
      <item> Bellevue </item>
      <item> Redmond </item>
      <item> Seattle </item>
    </one-of>
  </rule>

</grammar>

Rule References with Semantics

Ruleref elements are often used in conjunction with tag elements to assign semantic meaning to the recognition result from the referenced rule.

The following example presents a grammar for ordering a meal from a menu. Diners can order any item for a first course, a main course, or for dessert.

The example consists of a root rule (menuOrder) that contains rule references to a second rule that holds the menu items (menu). In the tag element following each ruleref element, the example creates a property for the Rule Variable (identified by "out") of the root rule of the grammar. The properties are named "firstCourse", "mainCourse", and "dessert". Each tag element assigns the recognition result from the referenced rule to the created property. The property serves as a semantic key that identifies the recognition result from the rule named menu as a first course, main course, or dessert.

The speech recognition engine will return the recognition result from each rule reference and tag it with the property name. You can use the property name as a semantic key to retrieve the recognition result for each rule reference. For example, here is a typical recognition result for the grammar that follows:

Recognized phrase: I want to start with Ice Cream followed by Ribs and then the Salad

First Course: Ice Cream

Main Course: Ribs

Dessert: Salad

Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar xml:lang="en-US" root="menuOrder"
tag-format="semantics/1.0" version="1.0"
xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="menuOrder">
    <item> I want to start with </item>
    <ruleref uri="#menu" /><tag> out.firstCourse=rules.latest(); </tag>
    <item> followed by </item>
    <ruleref uri="#menu" /><tag> out.mainCourse=rules.latest(); </tag>
    <item> and then the </item>
    <ruleref uri="#menu" /><tag> out.dessert=rules.latest(); </tag>
  </rule>

  <rule id="menu">
    <one-of>
      <item> Salad </item>
      <item> Soup </item>
      <item> Cheese </item>
      <item> Ribs </item>
      <item> Fish </item>
      <item> Pasta </item>
      <item> Ice Cream </item>
      <item> Cake </item>
      <item> Pie </item>
    </one-of>
  </rule>

</grammar>

The preceding example uses the latest() function on the rules object to reference the last ruleref element to be used in the rule that matches the utterance.

The following example is the same as the preceding example, but uses the syntax of tag-format="semantics-ms/1.0". In the syntax of semantics-ms/1.0, the result from the latest referenced rule that matches the utterance can be represented by the shorthand symbol "$$". The Rule Variable in semantics-ms\1.0 is identified by "$".

Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar xml:lang="en-US" root="menuOrder"
tag-format="semantics-ms/1.0" version="1.0"
xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="menuOrder">
    <item> I want to start with </item>
    <ruleref uri="#menu" /><tag> $.firstCourse=$$; </tag>
    <item> followed by </item>
    <ruleref uri="#menu" /><tag> $.mainCourse=$$; </tag>
    <item> and then the </item>
    <ruleref uri="#menu" /><tag> $.dessert=$$; </tag>
  </rule>

  <rule id="menu">
    <one-of>
      <item> Salad </item>
      <item> Soup </item>
      <item> Cheese </item>
      <item> Ribs </item>
      <item> Fish </item>
      <item> Pasta </item>
      <item> Ice Cream </item>
      <item> Cake </item>
      <item> Pie </item>
    </one-of>
  </rule>

</grammar>

For more information about attaching semantics to rule references, see Grammar Rule Reference Referencing (Microsoft.Speech) and Using the tag Element (Microsoft.Speech).

For an example of an event handler that will retrieve semantic results, see SpeechRecognizedEventArgs.

See Also

Concepts

tag Element (Microsoft.Speech)
Grammar Rule Reference Referencing (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


tag Element (Microsoft.Speech)

[image]

tag Element (Microsoft.Speech)
See Also Send Feedback

A tag element contains semantic information, either as a string or as ECMAScript (JavaScript, JScript), which returns additional information when an element or series of elements is recognized. A tag element does not affect the legal word patterns defined by the grammars or the process of recognizing speech or other input given a grammar. For more information, see Using the tag Element (Microsoft.Speech).

Syntax

XML Copy image Copy Code
<tag> string </tag>
OR
<tag> out="value"; </tag>
OR
<tag> $="value"; </tag>
OR
<tag> out.Property="value"; </tag>
OR
<tag> $.Property="value"; </tag>

Attributes

None.

Remarks

A tag element is a direct child of an item element or a rule element. A tag element can contain one of two types of content: string literals or ECMAScript. The content type of the tag elements within a grammar must be declared in the tag-format attribute of the grammar element. Grammars of greater complexity typically use the ECMAScript content type (tag-format="semantics/1.0" or tag-format="semantics-ms/1.0").

Script expressions or string literals in tag elements generate semantic values for the content of an item element or the target of a ruleref element within a rule. See Grammar Rule Name Referencing (Microsoft.Speech) and Grammar Rule Reference Referencing (Microsoft.Speech) for more information.

A tag element can contain an individual script expression or a concatenated series of multiple script expressions. Script expressions contained in tag elements follow the syntax of ECMA-327. Script expressions cannot assign values to reserved words. The content of the tag element is CDATA.

Note Note

Using the string literal syntax when the value for tag-format is semantics/1.0 or semantics-ms/1.0 will generally result in a runtime error. However, using the ECMAScript syntax when the value for tag-format is semantics/1.0-literals will not produce a runtime error, but will erroneously populate Rule Variables with ECMAScript code.

Examples

The following provides examples for using tag elements to assign semantic meaning to item elements and to ruleref elements.

Using Tag Elements with Item Elements

The following example shows a use of string literals in the tag element. The tag element assigns a string value to the Rule Variable of the rule "destAirport". When "Heathrow" is recognized, the string "Destination" is returned as a semantic result.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-US" root="destAirport"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0-literals">

  <rule id="destAirport">
    <item> Heathrow <tag> Destination </tag> </item>
  </rule>

</grammar>

The next example uses script in the tag element to assign a string value to the Rule Variable of the rule "destAirport".

When "Heathrow" is recognized, the string "Destination" is returned as a semantic result.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-US" root="destAirport"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="destAirport">
    <item> Heathrow <tag> out="Destination"; </tag> </item>
  </rule>

</grammar>

The following example is the same as the preceding example, but uses the syntax of tag-format="semantics-ms/1.0".

  • If the value for the tag-format attribute of the grammar element is semantics/1.0, the Rule Variable is named "out".

  • If the value for tag-format is semantics-ms/1.0 the Rule Variable is named "$".

Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-US" root="destAirport"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics-ms/1.0">

  <rule id="destAirport">
    <item> Heathrow <tag> $="Destination"; </tag> </item>
  </rule>

</grammar>

In the following example, the script expression contained in the tag element creates a property named "code" for the Rule Variable of the rule named destAirport and assigns the value "LHR" to the created property. When "Heathrow" is recognized, the string "LHR", which is the airport code for Heathrow, is returned as a semantic result.

Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar version="1.0" xml:lang="en-US" root="destAirport"
 xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="destAirport">
    <item> Heathrow <tag> out.code = "LHR"; </tag> </item>
  </rule>

</grammar>

Using Tag Elements with RuleRef Elements

The examples above show the use of the tag element as a child of the item element to assign a semantic value to the item element's contents. Another common use for the tag element is to assign a semantic meaning to the recognition result from a rule that is the target specified by a ruleref element.

The following example assigns the semantic key "LeavingFrom" to recognition results from the first ruleref element to the rule named flightCities. The example assigns the semantic key "GoingTo" to recognition results from the second rule reference to the rule named flightCities. The example uses the tag element in each item element of the rule named flightCities to assign a semantic value that is the airport code to each item element that contains the name of a city or a city's airport. The speech recognition engine will return the airport code when a city or airport name is recognized, and whether the city is the "LeavingFrom" city or the "GoingTo" city for the flight. Note that the rule flightCities accepts multiple speech inputs for the Seattle and Dallas city/airports, but returns only one semantic result for each. Here is a sample recognition result from the grammar that follows:

Recognized phrase: I want to fly from Boston to Sea-Tac

Leaving from: BOS

Going to: SEA

Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar xml:lang="en-US" root="flightBooker"
tag-format="semantics/1.0" version="1.0"
xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="flightBooker" scope="public">
    <item> I want to fly from </item>
    <ruleref uri="#flightCities" />
    <tag> out.LeavingFrom=rules.latest(); </tag>
    <item> to </item>
    <ruleref uri="#flightCities" />
    <tag> out.GoingTo=rules.latest(); </tag>
  </rule>

  <rule id="flightCities" scope="private">
    <one-of>
      <item> <tag> out="SEA"; </tag>
        <one-of>
          <item> Seattle-Tacoma </item>
          <item> Sea-Tac </item>
          <item> Seattle </item>
        </one-of>
      </item>
      <item> Boston <tag> out="BOS"; </tag> </item>
      <item> Miami <tag> out="MIA"; </tag> </item>
      <item> <tag> out="DFW"; </tag>
        <one-of>
          <item> Dallas </item>
          <item> Fort Worth </item>
          <item> Dallas-Fort Worth </item>
        </one-of>
      </item>
    </one-of>
  </rule>

</grammar>

The preceding example uses the latest() function on the rules object to reference the last ruleref element to be used in the rule that matches the utterance.

The following example is the same as the preceding example, but uses the syntax of tag-format="semantics-ms/1.0". In the syntax of semantics-ms/1.0, the result from the latest referenced rule that matches the utterance can be represented by the shorthand symbol "$$".

Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar xml:lang="en-US" root="flightBooker"
tag-format="semantics-ms/1.0" version="1.0"
xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="flightBooker" scope="public">
    <item> I want to fly from </item>
    <ruleref uri="#flightCities" />
    <tag> $.LeavingFrom=$$; </tag>
    <item> to </item>
    <ruleref uri="#flightCities" />
    <tag> $.GoingTo=$$; </tag>
  </rule>

  <rule id="flightCities" scope="private">
    <one-of>
      <item> <tag> $="SEA"; </tag>
        <one-of>
          <item> Seattle-Tacoma </item>
          <item> Sea-Tac </item>
          <item> Seattle </item>
        </one-of>
      </item>
      <item> Boston <tag> $="BOS"; </tag> </item>
      <item> Miami <tag> $="MIA"; </tag> </item>
      <item> <tag> $="DFW"; </tag>
        <one-of>
          <item> Dallas </item>
          <item> Fort Worth </item>
          <item> Dallas-Fort Worth </item>
        </one-of>
      </item>
    </one-of>
  </rule>

</grammar>
Note Note

Scripts in tag elements are executed only if the item or rule containing it provides a match.

For an example of an event handler that will retrieve semantic results, see SpeechRecognizedEventArgs.

See Also

Concepts

Using the tag Element (Microsoft.Speech)
Referencing Grammar Rule Variables (Microsoft.Speech)
Grammar Rule Name Referencing (Microsoft.Speech)
Grammar Rule Reference Referencing (Microsoft.Speech)
rule Element (Microsoft.Speech)
item Element (Microsoft.Speech)
ruleref Element (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


token Element (Microsoft.Speech)

[image]

token Element (Microsoft.Speech)
See Also Send Feedback

Contains a string that a speech recognizer can use for recognition and optionally specifies the display form of the string and the precise pronunciation that will trigger recognition.

Syntax

XML Copy image Copy Code
<token
  sapi:display = "string"
  sapi:pron = "string">
</token>

Attributes

Attribute | Description
sapi:display | Optional. Specifies the form of the word or phrase contained by the token element that should be displayed in the user interface. The token element contains the lexical form of a word, which is used for recognition unless a custom pronunciation is specified by the sapi:pron attribute. The display form of a word is often the same as its lexical form.
sapi:pron | Optional. Specifies an inline, custom pronunciation that the speech recognition engine can use to recognize the contents of the token element. The value of sapi:pron must use phones from the phonetic alphabet specified in the sapi:alphabet attribute of the grammar element. When using sapi:pron in a token element, the grammar Element (Microsoft.Speech) must include the sapi:alphabet attribute, and must also contain the following declaration: xmlns:sapi="http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions"

Remarks

A token element typically contains a word or short phrase in the language being recognized. For example, although the city name San Francisco consists of two character strings separated by a space, English speakers recognize the name as a single entity. A token element must not be empty.

The token element allows you to specify three forms of a word: the display form, the lexical form, and a custom pronunciation for the word. Possible uses for the display form include cardinal numbers and acronyms. In the following example, the phrases "United States of America" and "fifty" would be used for recognition, but the user interface would display "USA" and "50".

<item> The <token sapi:display="USA"> United States of America </token> has <token sapi:display="50"> fifty </token> states. </item>

Phones are letters or symbols that describe the sounds of speech. The Microsoft Speech Platform SDK 11 supports three phonetic alphabets for speech recognition: the Universal Phone Set (UPS), the Speech API (SAPI) Phone set, and the International Phonetic Alphabet (IPA). The phones specified in sapi:pron must match the phonetic alphabet specified in the sapi:alphabet attribute of the grammar element. If the phones are not space-delimited or the specified string contains an unrecognized phone, the recognition engine does not recognize the specified pronunciation as a valid pronunciation of the word contained by the token element. If sapi:pron is specified, the speech recognition engine does not use the string contained by the token element for recognition, but returns the string as the recognition result if the speech input matches the pronunciation specified in the sapi:pron attribute.

Pronunciations specified in token elements in speech recognition grammar documents take precedence over pronunciations specified in lexicons associated with a grammar or a recognition engine. Also, the pronunciation in a token element applies only to the single occurrence of the word or phrase contained by the token element.

Unlike the Speech Recognition Grammar Specification (SRGS) Version 1.0 specification, the Speech Platform SDK 11 does not support the use of the xml:lang attribute on the token element. Grammars in the Speech Platform SDK 11 can contain only one language, and this must be declared in the grammar Element (Microsoft.Speech). To support multiple languages for your applications, you can use multiple grammars in parallel, each with a separate single language.

Example

The grammar in the following example contains slang words and also has an uncommon word: "whatchamacallit". Adding a custom, inline pronunciation using the sapi:pron attribute can improve the accuracy of recognition for the word "whatchamacallit" as well as for the entire phrase that contains it. The example uses phones from the Microsoft Universal Phone Set (UPS) to define the custom pronunciations.

Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar xml:lang="en-US" root="slang"
tag-format="semantics/1.0" sapi:alphabet="x-microsoft-ups"
version="1.0" xmlns="http://www.w3.org/2001/06/grammar"
xmlns:sapi="http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions">

  <rule id="slang">

    <one-of>
      <item> give me </item>
      <item> gimme </item>
      <item> hand me </item>
      <item> ha'me </item>
    </one-of>

    <one-of>
      <item> the </item>
      <item> duh </item>
    </one-of>

    <one-of>
      <item> thingamajig </item>
      <item> <token sapi:pron="W AE T CH AE M AE K AA L IH T"> whatchamacallit </token>
      </item>
    </one-of>

  </rule>

</grammar>

See Also

Concepts

grammar Element (Microsoft.Speech)
Lexicons and Phonetic Alphabets (Microsoft.Speech)

Other Resources

Using Custom Pronunciations
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Semantic Interpretation Markup (Microsoft.Speech)

[image]

Semantic Interpretation Markup (Microsoft.Speech)
Send Feedback

This section introduces semantic interpretation and describes how to use semantic interpretation markup in grammars that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0 to customize the semantic values that the speech recognizer returns as the result of a successful recognition.

What Is Semantic Interpretation?

Semantic interpretation is the process by which a semantic interpreter generates a semantic result based on an utterance that matches a path through a grammar. Scripts that are contained within tag elements and inserted in the input grammar generate the content of a semantic result. The speech recognizer serializes the products of the scripts and generates the semantic result in the form of a Semantic Markup Language (SML) output. For more information, see SML Output Overview (Microsoft.Speech).

The model and syntax of semantic interpretation that is implemented in the Microsoft recognition engines is based on Semantic Interpretation for Speech Recognition (SISR) Version 1.0.

Why Use Semantics

Using semantics effectively separates the words of spoken input from the business logic of your application. When spoken input matches a rule in your application's grammar, your application does not need to parse the recognized text to determine how to respond, if the rule contains semantics. The semantics of a grammar rule translate all the speech input options that a grammar rule defines into a result that your application expects. For example, a grammar rule for specifying an airport may recognize any of the utterances "Seattle-Tacoma", "Sea-Tac", or "Seattle", and generate the airport code "SEA" as the semantic result. Using semantics allows users of your application the flexibility to provide a variety of spoken inputs and provides your application with an actionable result. See Using Tag Elements with RuleRef Elements for an example.

Semantic Interpretation Principles

The basic principles for the semantic interpretation mechanism in the Microsoft speech recognition engines are:

  • Scripts that associate values with grammar rules generate semantic information.

  • Script expressions contained in the semantic interpretation tag element follow the syntax of ECMA-327. Not all features are supported. For exceptions, see Semantic Results Content (Microsoft.Speech).

  • The parse order of the rules in the grammar determines the order in which expressions are evaluated.

  • The semantic result (in the form of an SML output) consists of the semantic information associated with the root rule.

Semantic Interpretation Markup Reference

The following topics describe the implementation of semantic interpretation in Microsoft speech recognition engines.

  • Support for Semantic Markup

    Describes two models and syntax for authoring semantic scripts in XML-format SRGS grammars.

  • Semantic Results Content (Microsoft.Speech)

    Describes how the semantic interpreter generates semantic results.

  • Using the tag Element (Microsoft.Speech)

    Describes and illustrates the use of the tag element for semantic interpretation scripts and includes examples that show the semantic output that the contents of tag elements generate.

  • Referencing Grammar Rule Variables (Microsoft.Speech)

    Describes and illustrates the two different types of Rule Variable referencing.

  • Grammar Rule Name Referencing (Microsoft.Speech)

    Describes how to reference the Rule Variable of the containing rule element and how to create child and grandchild properties of the Rule Variable.

  • Grammar Rule Reference Referencing (Microsoft.Speech)

    Describes how to reference the Rule Variable of rule elements outside of the containing rule.

  • Complete Example Grammars with SI Markup (Microsoft.Speech)

    Presents two example grammars that contain scripts for semantic interpretation.

  • Grammar Example: Solitaire (Microsoft.Speech)

    Presents a grammar of moderate complexity that contains several rules and uses semantic scripts extensively.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Support for Semantic Markup

[image]

Support for Semantic Markup
See Also Send Feedback

The Microsoft Speech Platform SDK 11 supports two models and syntax for creating semantic content in XML-format grammars that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0:

  • One model is based on the W3C recommended specification Semantic Interpretation for Speech Recognition (SISR) Version 1.0.

  • The other model was developed by Microsoft and uses different syntax than the SISR-based model.

The scripting language supported by both models is ECMA-327, which is implemented in the Microsoft speech recognition engines using the Microsoft JScript interpreter.

To specify the syntax of semantic content in an SRGS XML grammar, use the tag-format attribute.

Specify the Format for Semantic Interpretation Markup

The tag-format attribute of the grammar element identifies the type of semantic interpretation markup in a grammar. For grammars used with Microsoft speech recognition engines, this value can be one of the following:

tag-format value | Description
semantics/1.0 | This value declares that the content within tag elements is ECMAScript as defined in the SISR specification.
semantics-ms/1.0 | This value declares that the content within tag elements is ECMAScript as implemented by Microsoft.
semantics/1.0-literals | This value declares that the content within tag elements is string literals as defined in the SISR specification. A string literal may be a boolean, an integer, a float, or a string. A string CANNOT be enclosed in double quotes.

Syntactical Differences

The SISR model and the Microsoft model for semantic content use different syntax to refer to Rule Variables.

When using tag-format="semantics/1.0" (conforms to the SISR specification):

  • The Rule Variable of the containing rule element is identified by "out".

  • The name of the object that has access to the Rule Variable of rule elements outside the containing rule element is identified by "rules".

  • The result from the latest referenced rule that matches the utterance can be represented by "rules.latest()".

When using tag-format="semantics-ms/1.0" (syntax defined by Microsoft):

  • The Rule Variable of the containing rule element is identified by "$".

  • The Rule Variable of a rule element that is outside of the containing rule element is identified by "$rulename", where "rulename" is the name of the referenced rule.

  • The result from the latest referenced rule that matches the utterance can be represented by the shorthand symbol "$$".

See tag Element (Microsoft.Speech) for examples that use each of the values for tag-format and demonstrate the supported syntaxes.

Note Note

Microsoft speech recognition engines do not support Augmented Backus-Naur Form (ABNF) grammars. Use only XML-format grammars.

See Also

Concepts

Semantic Interpretation Markup (Microsoft.Speech)
Semantic Results Content (Microsoft.Speech)
Referencing Grammar Rule Variables (Microsoft.Speech)
Grammar Rule Name Referencing (Microsoft.Speech)
Grammar Rule Reference Referencing (Microsoft.Speech)
Complete Example Grammars with SI Markup (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Semantic Results Content (Microsoft.Speech)

[image]

Semantic Results Content (Microsoft.Speech)
See Also Send Feedback

This topic describes how the semantic interpreter generates semantic results.

How Semantic Results Are Generated

Every rule element in a grammar has a single Rule Variable that holds a semantic value that can be composed of multiple properties. This Rule Variable can be assigned a value, and can be evaluated.

The semantic values associated with a Rule Variable consist of the recognized text (the text variable) and the recognition confidence score (the score variable). These values are generated when the recognizer matches the user's speech to the words or phrases that are defined by the rule. The semantic value corresponding to the highest level rule in the grammar (the root rule) is serialized and returned in the Semantic Markup Language (SML) output. Because a valid grammar contains no more than one root rule element, the semantic values returned in the SML output consist of the recognized text and recognition confidence score for the complete set of words and phrases in an utterance that match a path through the whole grammar. Semantic results will not be generated for rules in valid grammars that do not contain a root rule, unless the rules are explicitly referenced from a within a grammar that does contain a root rule.

Application developers can use script expressions contained in tag elements to generate semantic values for items that are contained in the rule and associate these item-specific values with the Rule Variable as properties of the Rule Variable. See Grammar Rule Name Referencing (Microsoft.Speech). Developers can also assign the semantic value of subrules (referenced rules) in the grammar to the Rule Variable of the higher level containing rule. See Grammar Rule Reference Referencing (Microsoft.Speech). The values generated by script expressions are not explicitly typed and can be of any type defined in ECMA-327. For more information, see Using the tag Element (Microsoft.Speech).

When an author adds semantic interpretation markup to the grammar, in addition to the score and the recognized text attributes for the root rule, only values generated by script expressions contained in tag elements appear in the SML output. For more information and examples, see SML Output Overview (Microsoft.Speech).

See Also

Concepts

Semantic Interpretation Markup (Microsoft.Speech)
Referencing Grammar Rule Variables (Microsoft.Speech)
Grammar Rule Name Referencing (Microsoft.Speech)
Grammar Rule Reference Referencing (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Using the tag Element (Microsoft.Speech)

[image]

Using the tag Element (Microsoft.Speech)
See Also Send Feedback

Script expressions in tag elements generate semantic values for the content of item elements and the target of ruleref elements (referenced rules) within the containing rule element. These values can be associated with the Rule Variable of the containing rule as properties of that Rule Variable. For more information about the various forms of reference to Rule Variables, see Referencing Grammar Rule Variables (Microsoft.Speech).

Placement of the tag Element

Author-defined scripts for generating semantic values must be contained inside tag elements.

XML Copy image Copy Code
<tag> out.property="desired value"; </tag>

You can also use an alternate syntax, created by Microsoft, to author the script in tag elements. To use this syntax, set tag-format="semantics-ms/1.0" in the grammar element. See Support for Semantic Markup.

Using the syntax of semantics-ms/1.0, the example above can be written as follows:

XML Copy image Copy Code
<tag> $.property="desired value"; </tag>

Place tag elements so that they immediately follow the word or phrase for which a semantic value is needed or immediately follow a ruleref that has a Rule Variable that contains information that the script expression is required to read.

Typically, words or phrases that require a semantic value are contained inside an item element. In this case, the tag element is contained within the item element. In World Wide Web Consortium (W3C) grammars, it is possible to include words or phrases in a grammar that are not explicitly contained in an item element, but that are nevertheless treated the same as words or phrases that are contained in an item element. In both cases, the script expression contained in the tag element is executed when the speech recognizer follows a path through the grammar that includes the words or phrases that the tag element follows.

A tag element can also be placed following a ruleref element. In this case, the script expression contained in the tag element is executed after the speech recognizer follows a path through the grammar that leads through the ruleref element. Use a tag element in this position to process the semantic information contained in the Rule Variable of the rule that the ruleref element references.

Values that are generated by scripts are attached to the Rule Variable of the rule that contains the tag element. The value corresponding to the root rule in the grammar is converted into the Semantic Markup Language (SML) output. Script expressions contained in semantic interpretation tags follow the syntax of ECMA-327.

Examples of tag Element Placement

The following examples illustrate tag element placement within a grammar rule.

In the following grammar, a tag element is placed within an item element to explicitly associate the expressions in the tag element with the content of the item element. The script expressions create a daynum property of the Rule Variable and set it to a numeric value.

XML Copy image Copy Code
<rule id="WeekdaySelection">
  <one-of>
    <item> Monday <tag> out.daynum="1"; </tag></item>
    <item> Wednesday <tag> out.daynum="3"; </tag></item>
    <item> Friday <tag> out.daynum="5"; </tag></item>
  </one-of>
</rule>

In response to the utterance "Monday," the speech recognizer selects a path through the item element containing "Monday." Following this path triggers the execution of the script that is contained by the tag element inside the item element containing "Monday." The script generates a property named daynum of the Rule Variable belonging to the WeekdaySelection rule and associates the value 1 with daynum.

Using the syntax of semantics-ms/1.0, the example above can be written as follows:

XML Copy image Copy Code
<rule id="WeekdaySelection">
  <one-of>
    <item> Monday <tag> $.daynum="1"; </tag></item>
    <item> Wednesday <tag> $.daynum="3"; </tag></item>
    <item> Friday <tag> $.daynum="5"; </tag></item>
  </one-of>
</rule>

In the following grammar, a tag element follows a word that is not explicitly contained within an item element (the word "select"). Words or phrases in the grammar that are not explicitly contained in an item element are treated as if they are contained in an item element. The rule below recognizes the utterances "select Monday," "select Wednesday," and "select Friday" and generates semantic values associated with both the word "select" and with the day name.

XML Copy image Copy Code
<rule id="WeekdaySelection">
  Select <tag> out.specifier="on"; </tag>
  <one-of>
    <item> Monday <tag> out.daynum="Day 1"; </tag></item>
    <item> Wednesday <tag> out.daynum="Day 3"; </tag></item>
    <item> Friday <tag> out.daynum="Day 5"; </tag></item>
  </one-of>
</rule>

The spoken phrase "select Wednesday" generates a specifier and a daynum property of the Rule Variable WeekdaySelection and associates the semantic values on and Day 3 with these properties, respectively.

Using the syntax of semantics-ms/1.0, the example above can be written as follows:

XML Copy image Copy Code
<rule id="WeekdaySelection">
  Select <tag> $.specifier="on"; </tag>
  <one-of>
    <item> Monday <tag> $.daynum="Day 1"; </tag></item>
    <item> Wednesday <tag> $.daynum="Day 3"; </tag></item>
    <item> Friday <tag> $.daynum="Day 5"; </tag></item>
  </one-of>
</rule>

In the following grammar, the tag element immediately follows the ruleref element. This placement associates the script expressions contained in the tag element with the value returned by the ruleref element. This rule recognizes the utterances "Saturday morning," "Saturday evening," "Sunday morning," and "Sunday evening" and generates numeric values representing the path that the recognizer follows through the grammar.

XML Copy image Copy Code
<rule id="AppointmentTime">
  <one-of>
    <item> Saturday <tag> out.daynum="6"; </tag> </item>
    <item> Sunday <tag> out.daynum="7"; </tag> </item>
  </one-of>
  <ruleref uri="#RelativeTime" /> <tag> out.TimeRange=rules.RelativeTime.range; </tag>
</rule>

<rule id="RelativeTime">
  <one-of>
    <item> morning <tag> out.range="1"; </tag> </item>
    <item> evening <tag> out.range="2"; </tag> </item>
 </one-of>
</rule>

Notice the script contained in the tag element following the ruleref to RelativeTime. The script creates a property named TimeRange of the Rule Variable for the AppointmentTime rule and assigns the contents of the range property of the Rule Variable for RelativeTime to TimeRange.

Using the syntax of semantics-ms/1.0, the example above can be written as follows:

XML Copy image Copy Code
<rule id="AppointmentTime">
  <one-of>
    <item> Saturday <tag> $.daynum="6"; </tag> </item>
    <item> Sunday <tag> $.daynum="7"; </tag> </item>
  </one-of>
  <ruleref uri="#RelativeTime" /> <tag> $.TimeRange=$RelativeTime.range; </tag>
</rule>

<rule id="RelativeTime">
  <one-of>
    <item> morning <tag> $.range="1"; </tag> </item>
    <item> evening <tag> $.range="2"; </tag> </item>
 </one-of>
</rule>

The path followed in response to the utterance "Saturday morning" triggers the scripts associated with "Saturday", "morning", and the ruleref to RelativeTime. This process generates the following data structure.

Copy image Copy Code
AppointmentTime => { daynum    =>   6            }
                   { TimeRange => { range => 1 } }

See Also

Concepts

tag Element (Microsoft.Speech)
Referencing Grammar Rule Variables (Microsoft.Speech)
Grammar Rule Name Referencing (Microsoft.Speech)
Grammar Rule Reference Referencing (Microsoft.Speech)
Support for Semantic Markup
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Referencing Grammar Rule Variables (Microsoft.Speech)

[image]

Referencing Grammar Rule Variables (Microsoft.Speech)
See Also Send Feedback

ECMAScript expressions that are contained in tag elements generate semantic values that are associated with the Rule Variable of a rule element. A rule variable is a container for values generated in the evaluation of a rule, including a basic scalar return value for the rule, attributes explicitly set by scripts in the rule, and other attributes automatically filled when the rule matches words, regardless of scripts. There are two forms of reference to Rule Variables:

  • Grammar Rule Name Referencing (Microsoft.Speech). Use script expressions to evaluate or assign semantic values that are associated with the Rule Variable of the containing rule element.

  • Grammar Rule Reference Referencing (Microsoft.Speech). Use script expressions to evaluate semantic values that are associated with the Rule Variable of a separate rule element that is the target of a ruleref element within the containing rule element.

The required form of reference for a script expression depends on whether the expression refers to the Rule Variable of the containing rule element or to the Rule Variable of a rule element that is referenced by a ruleref element. To reference the Rule Variable of the containing rule element, use script assignments of the form out = value; or out.Property = value;. The first assignment statement assigns a value to the Rule Variable. The second assignment statement assigns a value to the property (named Property) on the Rule Variable.

To reference the Rule Variable of a rule element that is outside of the containing rule, use the rules object. Every semantic interpretation script has access to this object, which can be used to access the value of any visible Rule Variable. For example, the semantic interpretation script out = rules.RuleName; provides access to the value of a rule named RuleName.

You can also use an alternate syntax, created by Microsoft, to reference the Rule Variable of a rule element that is outside of the containing rule. To use this syntax, set tag-format="semantics-ms/1.0" in the grammar element. See Support for Semantic Markup.

Illustration of Rule Name Referencing versus Rule Reference Referencing

The following example illustrates the appropriate use of both forms of referencing. In this example, the root rule named Time contains references to two other rules named Ordinal and Month. The Time rule also contains a list in a one-of element with the items "Saturday" and "Sunday". The example includes line numbers to simplify locating code elements that the comments identify.

Rule Name Referencing

Lines 12 and 13 illustrate Rule Name Referencing. In both of these lines, the item element contains a tag element. Script expressions contained in these tag elements assign values to the Ordinal and Weekday properties of the Rule Variable belonging to the rule named Time. The Weekday property is not assigned a value, as such. Instead, it acts as the parent of two other properties (dayNumber and dayAbbrev) that are assigned values.

Note Note

The script expression contained by the tag element on line 7 constructs the Weekday property as an empty object. This causes Weekday to be represented as a separate node in the Semantic Markup Language (SML) output and allows for the possibility of creating grandchild properties. The rest of the script expression on this line initializes the two child properties of Weekday (grandchildren of the Rule Variable for the rule named Time).

XML Copy image Copy Code
1   <?xml version="1.0" encoding="UTF-8" ?>
2   <grammar version="1.0" xml:lang="en-US" mode="voice" root= "Time"
3   xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">
4
5     <rule id="Time" scope="public">
6       <example>the first Saturday in January</example>
7       <tag> out.Weekday=new Object(); out.Weekday.dayNumber=-1; out.Weekday.dayAbbrev="Noneday"; </tag>
8       <item>the</item>
9       <ruleref uri="#Ordinal" />
10       <tag> out.Ordinal=rules.Ordinal; </tag>
11       <one-of>
12      <item>Saturday<tag> out.Weekday.dayNumber=6; out.Weekday.dayAbbrev="Sat"; </tag></item>
13      <item>Sunday<tag> out.Weekday.dayNumber=0; out.Weekday.dayAbbrev="Sun"; </tag></item>
14       </one-of>
15       <item>in</item>
16       <ruleref uri="#Month" /><tag> out.Month=rules.Month; </tag>
17     </rule>
18
19     <rule id="Ordinal">
20       <one-of>
21         <item> first <tag> out = 1; </tag> </item>
22         <item> second <tag> out = 2; </tag> </item>
23         <item> third <tag> out = 3; </tag> </item>
24       </one-of>
25     </rule>
26
27     <rule id="Month">
28       <one-of>
29         <item> January <tag> out = 1; </tag> </item>
30         <item> February <tag> out = 2; </tag> </item>
31         <item> March <tag> out = 3; </tag> </item>
32       </one-of>
33     </rule>
34   </grammar>

Rule Reference Referencing

Lines 10 and 16 illustrate Rule Reference Referencing. On line 10, a tag element that points to the rule named Ordinal immediately follows the ruleref element on line 9. The script expression contained in the tag element on line 10 evaluates the semantic value associated with the Ordinal rule, and assigns this value to the Ordinal property on the Rule Variable. The script expression contained in the tag element on line 16 evaluates the semantic value associated with the rule element named Month, and assigns this value to the Month property on the Rule Variable. Alternatively, the script assignment on line 10 could have been written as out.Ordinal = rules.latest();. This form uses the latest() function to return the last semantic value returned by one of the visible Rule Variables.

Note Note

The script expressions in a tag element can refer only to semantic values associated with the immediately preceding rule and not any subsequently referenced rules. For example, the script expressions in the tag element on line 10 cannot refer to semantic values associated with the rule named Month because the semantic interpreter finishes parsing the script expressions on line 10 before parsing the ruleref to Month on line 16.

See Also

Concepts

Using the tag Element (Microsoft.Speech)
tag Element (Microsoft.Speech)
ruleref Element (Microsoft.Speech)
grammar Element (Microsoft.Speech)
Support for Semantic Markup
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Rule Name Referencing (Microsoft.Speech)

[image]

Grammar Rule Name Referencing (Microsoft.Speech)
See Also Send Feedback

ECMAScript expressions that are contained in tag elements generate semantic values that are associated with the Rule Variable of a rule element. Script expressions that are contained in a tag element can evaluate values and assign values to the Rule Variable of the tag element's containing rule element. This Rule Variable of the containing rule element is called the Grammar Rule Name (GRN) Rule Variable. Scripts evaluate or assign values to the GRN Rule Variable using GRN referencing.

A tag element can contain an individual script expression or a concatenated series of multiple script expressions. Script expressions cannot assign values to reserved words.

Creating Child Properties

Because the GRN Rule Variable is predefined as an object, direct child properties of it can be created without using a new Object() expression. Use out.PropName (where PropName is the name of the property) to identify properties of the GRN Rule Variable.

In the following example, the GRN Rule Variable of the rule named airport is predefined as an empty object. The script expressions contained in the tag elements create two properties (code and location) of the airport Rule Variable and assign values to these properties. The script expressions assign the value LHR to the code property, and the value England to the location property.

XML Copy image Copy Code
<rule id="airport">
  Heathrow
    <tag> out.code= "LHR"; </tag>
    <tag> out.location= "England"; </tag>
</rule>

You can also use an alternate syntax, created by Microsoft, to reference the Rule Variable of a rule element that is outside of the containing rule. To use this syntax, set tag-format="semantics-ms/1.0" in the grammar element. See Support for Semantic Markup.

Using the syntax of semantics-ms/1.0, the example above can be written as follows:

XML Copy image Copy Code
<rule id="airport">
  Heathrow
    <tag> $.code= "LHR"; </tag>
    <tag> $.location= "England"; </tag>
</rule>

Creating Grandchild Properties

ECMAScript is not a strongly typed language, meaning that when a property is initialized, it is not predefined as a specific type. Instead, assigning a value to the property sets the property type to the same type as the assigned value. In the preceding example, because the location property is assigned a string value, the property type is string.

The way that type is set in ECMAScript has implications for creating grandchild properties. Before grandchild properties can be created, script writers must first initialize a child property of the type object to contain the grandchild properties. Initialize an object using a new Object() expression as shown in the following example.

XML Copy image Copy Code
<rule id="airport">
  Heathrow
    <tag> out.location= new Object(); </tag>
    <tag> out.location.country= "England"; </tag>
    <tag> out.location.city= "London"; </tag>
    <tag> out.location.elevation= "80 ft. MSL"; </tag>
</rule>

In this example, the script initializes the location property as an object. The grandchild properties country, city, and elevation are then initialized as direct properties of the child property location and assigned the values England, London, and 80 ft. MSL, respectively.

Using the syntax of semantics-ms/1.0, the example above can be written as follows:

XML Copy image Copy Code
<rule id="airport">
  Heathrow
    <tag> $.location= new Object(); </tag>
    <tag> $.location.country= "England"; </tag>
    <tag> $.location.city= "London"; </tag>
    <tag> $.location.elevation= "80 ft. MSL"; </tag>
</rule>

Order of Assignment

The way that type is set in ECMAScript also has implications for the order in which script writers can assign values to the Rule Variable or its properties. The previous examples illustrate how a script writer can initialize the location property as a string or an object. Although the Rule Variable is predefined to be an object, the Rule Variable can also be changed to a different type through simple assignment. In the following example, the script assigns a string value to the Rule Variable, thus changing the type of the Rule Variable from an object to a string.

XML Copy image Copy Code
<rule id="airport">
  Heathrow
    <tag> out="A major airport near London"; </tag>
</rule>

Using the syntax of semantics-ms/1.0, the example above can be written as follows:

XML Copy image Copy Code
<rule id="airport">
  Heathrow
    <tag> $="A major airport near London"; </tag>
</rule>

If the property type or the Rule Variable is changed, any values that already exist in the property or Rule Variable are lost. In the following example, the script initializes the code and location child properties and assigns the values LHR and England to them, respectively. However, in the next line, these properties and their values are destroyed when the Rule Variable is assigned a string value.

XML Copy image Copy Code
<rule id="airport">
  Heathrow
    <tag> out.code="LHR"; </tag>
    <tag> out.location="England"; </tag>
    <tag> out="A major airport near London"; </tag>
</rule>

In response to the utterance "Heathrow," this rule returns the semantic value "A major airport near London" and not the values LHR and England.

Using the syntax of semantics-ms/1.0, the example above can be written as follows:

XML Copy image Copy Code
<rule id="airport">
  Heathrow
    <tag> $.code="LHR"; </tag>
    <tag> $.location="England"; </tag>
    <tag> $="A major airport near London"; </tag>
</rule>

See Also

Concepts

tag Element (Microsoft.Speech)
Using the tag Element (Microsoft.Speech)
Support for Semantic Markup
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Rule Reference Referencing (Microsoft.Speech)

[image]

Grammar Rule Reference Referencing (Microsoft.Speech)
See Also Send Feedback

Application developers can use ECMAScript script expressions contained in tag elements to evaluate the semantic values associated with the Rule Variable of a rule element outside of the containing rule. The URI attribute of a ruleref element identifies a rule outside of the containing rule. This form of identification is called Grammar Rule Reference (GRR) referencing.

Identifying the GRR Rule Variable and Its Properties

The GRR Rule Variable is identified by rules.rulename, where rulename is the name of the referenced rule. In the following example, the script expression references the Rule Variable of the rule named airport and assigns the semantic value of this Rule Variable to the departfrom property of the Rule Variable of the rule named flight.

XML Copy image Copy Code
<rule id="flight">
  <ruleref uri="#airport" /><tag> out.departfrom=rules.airport; </tag>
</rule>

If the GRR Rule Variable is an object, use rulename.PropName (where PropName is the name of the property) to identify individual properties of the object. In the following example, the script expression references the code property of the GRR Rule Variable belonging to the rule named airport and assigns the value "code" to the departFrom property of the Rule Variable for the rule named flight.

XML Copy image Copy Code
<rule id="flight">
  <ruleref uri="#airport" />
  <tag> out.departFrom=rules.airport.code; </tag>
</rule>

You can also use an alternate syntax, created by Microsoft, to reference the Rule Variable of a rule element that is outside of the containing rule. To use this syntax, set tag-format="semantics-ms/1.0" in the grammar element. See Support for Semantic Markup.

Using the syntax of semantics-ms/1.0, the example above can be written as follows:

XML Copy image Copy Code
<rule id="flight">
  <ruleref uri="#airport" />
  <tag> $.departFrom=$airport.code; </tag>
</rule>

The latest() Function for the Last-Referenced Rule

Developers can also use the latest() function on the rules object in script expressions to reference the last ruleref element to be used in the expansion matching the utterance. This concept is illustrated in the following example. In this example, the preceding example is rewritten using the latest() function notation instead of the GRR Rule Variable name.

XML Copy image Copy Code
<rule id="flight">
  <ruleref uri="#airport" />
  <tag> out.departFrom=rules.latest().code; </tag>
</rule>

In the syntax of semantics-ms/1.0, the last ruleref element to be used in the expansion matching the utterance can be referred to by the shorthand symbol "$$". Using the syntax of semantics-ms/1.0, the example above can be written as follows:

XML Copy image Copy Code
<rule id="flight">
  <ruleref uri="#airport" />
  <tag> $.departFrom=$$.code; </tag>
</rule>

Remarks

  • The GRR Rule Variable can only be evaluated; it cannot be assigned values.

  • The special rule references, defined in the Speech Recognition Grammar Specification (SRGS) Version 1.0, cannot be evaluated in GRR references. These special rule references include NULL, VOID, and GARBAGE.

  • A tag element containing script expressions with GRR references must appear after the ruleref element that the scripts reference.

  • A script expression using GRR referencing generates semantic values only if the path that the speech recognizer follows through the grammar in response to an utterance includes the referenced rule. In the preceding examples, if a path through the airport rule is not followed, no semantic values are generated by the scripts that reference the airport rule.

See Also

Concepts

Using the tag Element (Microsoft.Speech)
tag Element (Microsoft.Speech)
ruleref Element (Microsoft.Speech)
Support for Semantic Markup
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Complete Example Grammars with SI Markup (Microsoft.Speech)

[image]

Complete Example Grammars with SI Markup (Microsoft.Speech)
See Also Send Feedback

This page contains two complete examples of grammars that contain markup for semantic interpretation (SI). Unlike the simplified grammar examples in other parts of the SI Help documents, the first six lines in these examples contain all the attribute-value pairs that are required or recommended by the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0. Also, the grammar in Plan_itinerary.grxml contains rule references to the grammar in Time_information.grxml. It is an accepted convention to use the .grxml file extension for XML-based grammar documents that conform to the SRGS specification. The examples contain line numbers to simplify the identification of specific lines for comment in the notes sections.

Plan_itinerary.grxml

XML Copy image Copy Code
1   <?xml version="1.0" encoding="UTF-8"?>
2   <!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0/EN"
3             "http://www.w3.org/TR/speech-grammar/grammar.dtd">
4
5   <grammar version="1.0" xml:lang="en-US" mode="voice" root="itinerary"
6     xmlns="http://www.w3.org/2001/06/grammar" xml:base="http://www.adventure-works.com/project" tag-format="semantics/1.0">
7
8     <rule id="itinerary">
9       <item> book a flight departing from </item>
10       <ruleref uri="#airports" /><tag> out.departFrom=rules.airports; </tag>
11       <item> on </item>
12       <ruleref uri="time_information.grxml" /><tag> out.departDay=rules.flightDays; </tag>
13       <item> in the </item>
14       <ruleref uri="time_information.grxml#flighttimes" /><tag> out.arriveRelativeTime=rules.flightTimes; </tag>
15       <ruleref special="GARBAGE" />
16       <item> and arriving at </item>
17       <ruleref uri="#airports" /><tag> out.arriveIn=rules.airports; </tag>
18       <item> on </item>
19       <ruleref uri="time_information.grxml" /><tag> out.arriveDay=rules.flightDays; </tag>
20       <item> in the </item>
21       <ruleref uri="time_information.grxml#flightTimes" /><tag> out.departRelativeTime=rules.flightTimes; </tag>
22     </rule>
23
24     <rule id="airports">
25       <one-of>
26         <item> Heathrow <tag> out.code=new Object(); out.code="LHR"; </tag></item>
27         <item> Gatwick <tag> out.code=new Object(); out.code="LGW"; </tag></item>
28         <item> Washington National <tag> out.code= new Object(); out.code._value="DCA"; </tag></item>
29       </one-of>
30     </rule>
31
32   </grammar>

Notes on Plan_itinerary.grxml

Line 5: | A grammar must specify a root rule.
Line 6: | A base URI (xml:base) is recommended, but is not required.
Line 6: | The tag-format attribute must have the value "semantics/1.0" or "semantics-ms/1.0" to activate semantic interpretation.
Line 10: | The airports value for the uri attribute of the ruleref element indicates a reference to a rule element with its id attribute set to airports that is located within the same grammar.
Line 10: | The expression, out.departFrom=rules.airports;, assigns the value of the Rule Variable for the rule named airports to the property named departFrom of the Rule Variable for the rule named itinerary. The value of Rule Variable for the rule named airports is generated by the tag elements in the airports rule.
Line 12: | Because the example grammar file Time_information.grxml (below) specifies flightDays as its root rule, flightDays is automatically a publicly-scoped rule. A ruleref element that specifies only the bare URI of a grammar file without specifying a rule within the grammar file references its root rule by default.
Line 14: | The flightTimes rule in the Time_information.grxml grammar file (below) is referenced in line 13. Although it is not the root rule in the Time_information.grxml grammar file, a value can be read from the flightTimes Rule Variable because the scope of flightTimes is set to public.
Line 15: | The special rule name, GARBAGE, matches any speech until the next rule match, the next token, or the end of spoken input. In this example, the speaker can say anything in between saying a relative time, such as "Afternoon" and "and arriving at."
Line 24: | Because the scope attribute is not explicitly specified for the airports rule, the scope is set to private by default. As a consequence, values generated by this rule can be referenced only by rules contained within the same grammar and not by rules contained in other grammars.

Time_information.grxml

XML Copy image Copy Code
1   <?xml version="1.0" encoding="UTF-8"?>
2   <!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0/EN"
3     "http://www.w3.org/TR/speech-grammar/grammar.dtd">
4
5   <grammar version="1.0" xml:lang="en-US" mode="voice" root="flightdays"
6     xmlns="http://www.w3.org/2001/06/grammar" xml:base="http://www.adventure-works.com/project" tag-format="semantics/1.0">
7
8     <rule id="flightDays" scope=="public">
9       <one-of>
10         <item weight="1"> Monday <tag> out.selectedDay=new Object(); out.selectedDay= "1"; </tag></item>
11         <item weight="4"> Wednesday <tag> out.selectedDay=new Object(); out.selectedDay="3"; </tag></item>
12         <item weight="9"> Friday <tag> out.selectedDay=new Object(); out.selectedDay="5"; </tag></item>
13       </one-of>
14     </rule>
15
16     <rule id="flightTimes" scope="public">
17       <one-of>
18         <item> Morning <tag> out.selectedTime=new Object(); out.selectedTime="AM"; </tag></item>
19         <item> Afternoon <tag> out.selectedTime=new Object(); out.selectedTime="Midday"; </tag></item>
20         <item> Evening <tag> out.selectedTime=new Object(); out.selectedTime="PM"; </tag></item>
21       </one-of>
22     </rule>
23
24     </grammar>

Notes on Time_information.grxml

Line 16:

Because the scope of the flightTimes rule has been set to public, values generated by this rule can be read by rules outside of this grammar.

See Also

Concepts

Semantic Interpretation Markup (Microsoft.Speech)
Using the tag Element (Microsoft.Speech)
tag Element (Microsoft.Speech)
ruleref Element (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Example: Solitaire (Microsoft.Speech)

[image]

Grammar Example: Solitaire (Microsoft.Speech)
Send Feedback

Grammar rules define the words and phrases that a speech recognition engine can use to recognize speech input. Phrases and sub-expressions are commonly represented by separate rules and combined into larger phrases and sentences by higher level rules. For more information, see Grammars Overview (Microsoft.Speech).

In addition to specifying the words and phrases that can be recognized, a grammar rule can specify additional information that the speech recognition engine will return when it recognizes a word or phrase. For example, a grammar rule could assign the semantic value "ORD" (the airport code) to the city name "Chicago". The speech recognition engine can return the airport code ("ORD"), as well as the name of the city ("Chicago"), each time it recognizes "Chicago".

Grammar rules can also define an information structure that organizes the rules and their expected results into a semantic hierarchy. Using script in tag elements, grammar rules can create the nodes of a semantic hierarchy and assign each node an identifying name (a semantic key), which the speech recognition engine will return with the results of recognition. For example, if "Chicago" is in a list of city names that a user can choose as the origin or the destination for a flight, the grammar rule can assign a semantic key that identifies the selection of "Chicago" as an origin or a destination city. See tag Element (Microsoft.Speech) for more information.

In summary, the definition of a grammar rule can specify the words or phrases that can be recognized, additional information to return when a word or phrase is recognized, and the name of the node that generated the recognition result.

Example

The card game solitaire uses semantic objects such as cards, suits, and ranks, and uses semantic actions, such as "play the <some card>", "move <one card> to <another card>", and "put <some card> on <another card>". The following example illustrates an example implementation of a grammar for a game of solitaire that supports the previously mentioned semantic objects and actions. The example also specifies the exact voice command phrases, in English (United States), which must be spoken to play the game.

When a command such as "play the three of diamonds" is spoken, the first ruleref Element (Microsoft.Speech) in the rule named "toplevel" references the rule named "PlayCard". The rule named "PlayCard" in turn references the rule named "Card", which returns information about the card to play. An application can obtain this information from the semantic key named "Card", which is specified in the tag element of the rule named "toplevel", as follows: <tag> out.Card = rules.PlayCard; </tag>. This example makes extensive use of the tag element to return semantic values. For more information, see Using the tag Element (Microsoft.Speech).

When a command such as "move the seven of clubs to the six of diamonds" is spoken, the "MoveCard" rule is referenced by the second ruleref element in the "toplevel" rule. The "MoveCard" rule in turn references the "Card" rule twice. These references return semantic information about the card to move and its destination. An application can obtain this information from the semantic key "MoveCard".

The following illustration depicts the hierarchy of the semantic information returned by the grammar. If the user utterance is "play the two of hearts", the semantic key "Card" can be used to determine which card is to be played. The information is present in the "Rank" and "Suit" sub-keys of the semantic key "Card". These sub-keys will contain, respectively, the semantic values "2" and "Hearts".

If the user utterance is "move the red Queen to the Jack of clubs," the semantic key "MoveCard" can be used to determine the card to be moved, and the card that is the moved card's destination. The keys of the "Rank" and "Color" sub-keys of the "FromCard" key contain, respectively, "Queen" and "Red'. The keys of the "Rank" and "Suit" sub-keys of the "ToCard" key contain, respectively, "Jack" and "Clubs".

XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8" ?>
<grammar version="1.0" xml:lang="en-US" mode="voice" root="toplevel"
xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">
  <rule id="toplevel" scope="public">
    <one-of>
      <item> <ruleref uri="#PlayCard"/> <tag> out.Card = rules.PlayCard; </tag> </item>
      <item> <ruleref uri="#MoveCard"/> <tag> out.MoveCard = rules.MoveCard; </tag> </item>
    </one-of>
  </rule>

  <rule id="PlayCard" scope="public">
    <example> please play the red queen </example>
    <example> play the ace </example>
    <example> play the five of diamonds please </example>

    <item repeat="0-1"> please </item>
    <item>play the</item>
    <ruleref uri="#Card"/>
    <tag> out = rules.Card; </tag>
    <item repeat="0-1"> please </item>
  </rule>

  <rule id="MoveCard">
    <example>move the five of clubs to the six of hearts</example>
    <example>please put the jack of hearts on the ten of clubs</example>

    <item repeat="0-1"> please </item>
    <one-of>
      <item> move the</item>
      <item> put the</item>
    </one-of>
    <ruleref uri="#Card"/>
    <tag> out.FromCard = rules.Card; </tag>
    <item repeat="0-1">
      <one-of>
        <item> on the</item>
        <item> to the</item>
      </one-of>
      <ruleref uri="#Card"/>
      <tag> out.ToCard = rules.latest(); </tag>
    </item>
    <item repeat="0-1"> please </item>
  </rule>

  <rule id="Card">
    <example> red queen </example>
    <example> jack of clubs </example>
    <example> ace </example>
    <example> spade </example>

    <one-of>
      <item>
        <!-- color and rank form -->
        <ruleref uri="#Color"/>
        <tag> out.Color = rules.Color; </tag>
        <ruleref uri="#Rank"/>
        <tag> out.Rank = rules.Rank; </tag>
      </item>

      <item>
        <!-- rank and optional suit form -->
        <ruleref uri="#Rank"/>
        <tag> out.Rank = rules.Rank; </tag>
        <item repeat="0-1">
          of
          <ruleref uri="#Suits"/>
          <tag> out.Suit = rules.Suits; </tag>
        </item>
      </item>

      <item>
        <!-- suit only form -->
        <ruleref uri="#Suit"/>
        <tag> out.Suit = rules.Suit; </tag>
      </item>
    </one-of>
  </rule>

  <rule id="Color">
    <example> red </example>
    <example> black </example>

    <one-of>
      <item> red <tag> out = "Red"; </tag> </item>
      <item> black <tag> out = "Black"; </tag> </item>
     </one-of>
  </rule>

  <rule id="Suit">
    <example> spade </example>
    <example> club </example>

    <one-of>
      <item> club <tag> out = "Club"; </tag> </item>
      <item> heart <tag> out = "Heart"; </tag> </item>
      <item> diamond <tag> out = "Diamond"; </tag> </item>
      <item> spade <tag> out = "Spade"; </tag> </item>
     </one-of>
  </rule>

  <rule id="Suits">
    <example> spades </example>
    <example> clubs  </example>

    <one-of>
      <item> clubs  <tag> out = "Club"; </tag> </item>
      <item> hearts <tag> out = "Heart"; </tag> </item>
      <item> diamonds <tag> out = "Diamond"; </tag> </item>
      <item> spades <tag> out = "Spade"; </tag> </item>
     </one-of>
  </rule>

  <rule id="Rank">
    <example> ace </example>
    <example> five </example>
    <example> king </example>
    <example> jack </example>

    <one-of>
      <item> ace <tag> out = 1; </tag> </item>
      <item> two <tag> out = 2; </tag> </item>
      <item> three <tag> out = 3; </tag> </item>
      <item> four <tag> out = 4; </tag> </item>
      <item> five <tag> out = 5; </tag> </item>
      <item> six <tag> out = 6; </tag> </item>
      <item> seven <tag> out = 7; </tag> </item>
      <item> eight <tag> out = 8; </tag> </item>
      <item> nine <tag> out = 9; </tag> </item>
      <item> ten <tag> out = 10; </tag> </item>
      <item> jack <tag> out = 11; </tag> </item>
      <item> queen <tag> out = 12; </tag> </item>
      <item> king <tag> out = 13; </tag> </item>
      <item> lady <tag> out = 12; </tag> </item>
      <item> emperor <tag> out = 13; </tag> </item>
    </one-of>
  </rule>
</grammar>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Semantic Markup Language Reference (Microsoft.Speech)

[image]

Semantic Markup Language Reference (Microsoft.Speech)
Send Feedback

The following topics in this section describe the structure and content of SML output and the serialization of semantic results into Semantic Markup Language (SML) output. A speech recognition engine generates SML output from grammar files that conform to the Speech Recognition Grammar Specification (SRGS) 1.0. The grammar files accompany the SML output. For more information about the grammars, see SRGS Grammar XML Reference (Microsoft.Speech) and Semantic Interpretation for Speech Recognition (SISR) Version 1.0. The SML output in these topics can be duplicated by the use of the ConstructSmlFromSemantics()()()() method, using the code example shown on that page.

In This Section

  • SML Output Overview (Microsoft.Speech)

    Describes the structure and content of SML output.

  • Serialization of the Root Rule Variable (Microsoft.Speech)

    Describes how the recognizer serializes the value of the root Rule Variable.

  • Serialization of Developer-defined Rule Variable Properties (Microsoft.Speech)

    Describes how the recognizer serializes the value of Rule Variable properties that developers define in semantic interpretation markup.

  • Serialization of Multiple Rule Grammars (Microsoft.Speech)

    Illustrates how the recognizer serializes grammars with multiple rules.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SML Output Overview (Microsoft.Speech)

[image]

SML Output Overview (Microsoft.Speech)
Send Feedback

On recognition, the semantic interpretation mechanism of a speech recognition engine returns a semantic result to the speech application. The semantic result of a recognition is the value of the root Rule Variable (RRV) in the grammar that the speech recognition engine used to perform the recognition.

A semantic result typically contains information that is more useful to the application than only the text of the utterance. For example, a grammar for specifying an airport might recognize the utterance "Heathrow Airport" and generate the airport code "LHR" as the semantic result. Scripts contained within tag elements inserted in the input grammar generate the content of a semantic result. The speech recognizer serializes the script products and generates the semantic result in the form of Semantic Markup Language (SML) output.

SML is a container format for holding the semantic information that semantic interpretation markup in the input grammar generates. SML output is a valid XML document in which the top-level element is named SML. The SML element can have zero, one, or more child elements, depending on whether the input grammar contains markup for semantic interpretation.

SML Element Content and Structure

The following list outlines the attribute-value pairs that the semantic interpreter automatically includes in the start tag of the SML element:

  • text-a string consisting of all recognized utterance tokens.

  • utteranceConfidence-a floating point value between 0.000-1.000.

  • confidence-a floating point value between 0.000-1.000.

The recognizer automatically sets the values of the utteranceConfidence and text attributes. These values identify the confidence score for the full utterance and the recognized text of the utterance. These values cannot be changed by the developer. The recognizer sets the value of utteranceConfidence to 1.000 for results derived from text parsing or if the recognition engine is unable to generate a confidence score for the full utterance.

The recognizer sets the value of the confidence attribute to the value of the utteranceConfidence attribute by default. Using scripts in semantic interpretation markup, developers are able to change the value of this attribute. Developers might want to control the value of this attribute to push a score from a semantically relevant node upwards or to calculate an interpretive score for the semantic result based on criteria other than simple utterance confidence.

Developers can specify the text content of the SML element by assigning to the _value property of the RRV. Developers can also add attributes to the SML element's start tag by creating child properties of the RRV's _attributes property.

The following code block illustrates the general structure of the SML output for the top-level SML element. Strings enclosed in brackets ("[]") describe the values or names that appear where the bracketed strings are located.

XML Copy image Copy Code
<SML text="[utterance_tokens]"
     utteranceConfidence="[full_utterance_confidence_score]"
     confidence="[value_of_RRV_confidence_property]">
   [value_of_RRV]
</SML>

The recognizer serializes input grammars that contain no semantic interpretation markup into SML output that contains only the top-level SML element and its contents. To view an example, see Serialization of the Root Rule Variable (Microsoft.Speech).

Child Element Content and Structure

Using semantic interpretation tags, developers can obtain confidence scores and text content at the rule level. If a developer assigns variables for semantic interpretation to words or phrases in the input grammar, the SML output contains child elements corresponding to each word or phrase associated with the semantic interpretation markup. The inclusion of any semantic interpretation markup in the grammar disables the default behavior of the semantic interpreter. The SML output contains only the elements that are marked for semantic interpretation.

Child elements take the name of the property that produces them. The semantic interpreter automatically includes a confidence attribute in the start tag of child elements. Additional attribute-value pairs can be added to the start tag of child elements using the _attributes property. Use the _value property to set the text content of the child element. The value of a child element can also be an array, in which case each item in the array is enclosed in an item element contained by the child element. For examples, see Serialization of Developer-defined Rule Variable Properties (Microsoft.Speech).

The following example is SML output that illustrates the structure of three different child elements, one of which itself has child elements. The names of the three child elements are Weekday, Ordinal, and Month. The dayNumber and dayAbbrev elements are children of the Weekday element. For each element that is not the child of another element, the confidence of the recognition and the semantic value associated with that element are shown. This example results from speech recognition using the grammar that appears in Referencing Grammar Rule Variables (Microsoft.Speech). The SML code shown here can be generated by using the ConstructSmlFromSemantics()()()() method.

XML Copy image Copy Code
<SML text="the second Saturday in March" utteranceConfidence="0.950" confidence="0.950">
  <Weekday confidence="0.998">
    <dayNumber confidence="0.998">6</dayNumber>
    <dayAbbrev confidence="0.998">Sat</dayAbbrev>
  </Weekday>
  <Ordinal confidence="0.998">2</Ordinal>
  <Month confidence="0.998">3</Month>
</SML>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Serialization of the Root Rule Variable (Microsoft.Speech)

[image]

Serialization of the Root Rule Variable (Microsoft.Speech)
See Also Send Feedback

On recognition, the semantic interpretation mechanism of a speech recognition engine returns a semantic result to the speech application. The semantic result of a recognition is the value of the root Rule Variable (RRV) of the grammar. Like all Rule Variables, the RRV is predefined as an object.

For an input grammar that contains no markup for semantic interpretation, the SML output consists of a top-level node named SML that contains the recognized utterance. The SML opening tag contains three attributes named text, utteranceConfidence, and confidence. The following example illustrates a simple grammar that contains no markup for semantic interpretation.

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" mode="voice" root="destination"
xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="destination">
    Fly me to
    <one-of>
      <item> London </item>
      <item> Paris </item>
      <item> Berlin </item>
    </one-of>
  </rule>
</grammar>

Using this grammar, the utterance "Fly me to Paris" produces the following SML output.

XML Copy image Copy Code
<SML text="Fly me to Paris" utteranceConfidence="0.874" confidence="0.874" >
    Fly me to Paris
</SML>

For more information about the structure of SML output, and the value types and ranges of these attributes in the SML element, see SML Output Overview (Microsoft.Speech).

Simple Assignment to the Root Rule Variable

If a developer directly assigns a simple scalar value to the root Rule Variable (RRV), all the properties of the RRV that the semantic interpreter normally uses for serialization are lost. The semantic interpreter produces an output in which the top-level SML element has no attributes and contains the simple scalar value. In the following grammar, each expression contained in the tag elements assigns a simple string value to the RRV.

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" mode="voice" root="destination"
xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="destination">
    Fly me to
    <one-of>
      <item> London <tag> out="Heathrow"; </tag></item>
      <item> Pairs <tag> out="Orly"; </tag></item>
      <item> Berlin <tag> out="Tegel"; </tag></item>
    </one-of>
  </rule>
</grammar>

Using this grammar, the utterance "Fly me to Paris" produces SML output similar to the following.

XML Copy image Copy Code
<SML> Orly </SML>

Accessing the Root Rule Variable

Use one of the following to access the RRV to set the text content of the top-level SML element.

  • If the value for the tag-format attribute of the grammar element is semantics/1.0, the Rule Variable is named "out".

  • If the value for the tag-format attribute of the grammar element is semantics-ms/1.0 the Rule Variable is named "$".

The following grammar is identical to the previous grammar except for the addition of an expression that assigns a value to the RRV.

XML Copy image Copy Code
<grammar version="1.0" xmlns="http://www.w3.org/2001/06/grammar"
 root="destination" xml:lang="en-US" tag-format="semantics/1.0">

  <rule id="destination">
    <tag> out="Destination city"; </tag>
    Fly me to
    <one-of>
      <item> London </item>
      <item> Paris </item>
      <item> Berlin </item>
    </one-of>
  </rule>
</grammar>

Using this grammar, the utterance "Fly me to Paris" produces SML output similar to the following.

XML Copy image Copy Code
<SML text="Fly me to Paris" utteranceConfidence="0.874" confidence="0.874" >
    Destination city
</SML>

With the script expression written in the syntax of semantics-ms/1.0, the following example will also produce the preceding SML output.

Copy image Copy Code
<grammar version="1.0" xmlns="http://www.w3.org/2001/06/grammar"
 root="destination" xml:lang="en-US" tag-format="semantics/1.0">

  <rule id="destination">
    <tag> $="Destination city"; </tag>
    Fly me to
    <one-of>
      <item> London </item>
      <item> Paris </item>
      <item> Berlin </item>
    </one-of>
  </rule>
</grammar>

All valid utterances for this grammar produce an SML result that has the same text content in the top-level SML element. This result occurs because the script expression assigning the value of the text content follows the start tag of the rule element. For grammars that contain lists in one-of elements, change the value of the text content of the SML element according to the item selected from a list. Follow each item element with a tag element containing a script expression that assigns a different string value to the RRV. The following grammar is identical to the previous grammar except for the addition of script expressions that create SML element text content that is specific to each item.

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" mode="voice" root="destination"
xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">
  <rule id="destination">
    Fly me to
    <one-of>
      <item> London <tag> out="Arriving at Heathrow"; </tag></item>
      <item> Paris <tag> out="Arriving at Orly"; </tag></item>
      <item> Berlin <tag> out="Arriving at Tegel"; </tag></item>
    </one-of>
  </rule>
</grammar>

Using this grammar, the utterance "Fly me to Paris" produces the following SML output.

XML Copy image Copy Code
<SML text="Fly me to Paris" utteranceConfidence="0.886" confidence="0.886" >
    Arriving at Orly
</SML>

Accessing Properties of the Root Rule Variable

Use the _attributes property of the RRV to produce additional XML attributes in the top-level SML element start tag. As can be seen in the first line in the body of the rule, the _attributes property is created as a new object (out._attributes=new Object();). This is necessary because the _attributes property has two child properties, code and time. The following grammar is identical to the previous grammar, except for the addition of expressions that assign values to two child properties of the _attributes property of the RRV. The code has also been reformatted to make it easier to read.

XML Copy image Copy Code
<rule id="destination">
  <tag>out._attributes=new Object();</tag>
  Fly me to
  <one-of>
    <item>London
      <tag>
        out._value="Arriving at Heathrow";
        out._attributes.code="EGLL";
        out._attributes.time="UTC";
      </tag>
    </item>
    <item>Paris
      <tag>
        out._value="Arriving at Orly";
        out._attributes.code="LFPO";
        out._attributes.time="UTC+1";
      </tag>
    </item>
    <item>Berlin
      <tag>
        out._value="Arriving at Tegel";
        out._attributes.code="EDDT";
        out._attributes.time="UTC+1";
      </tag>
    </item>
  </one-of>
</rule>

Using this grammar, the utterance "Fly me to Paris" produces the following SML output.

XML Copy image Copy Code
<SML text="Fly me to Paris" utteranceConfidence="0.840"confidence="0.840" code="LFPO" time="UTC+1" >
    Arriving at Orly
</SML>

See Also

Concepts

Semantic Interpretation Markup (Microsoft.Speech)
Using the tag Element (Microsoft.Speech)
tag Element (Microsoft.Speech)
ruleref Element (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Serialization of Developer-defined Rule Variable Properties (Microsoft.Speech)

[image]

Serialization of Developer-defined Rule Variable Properties (Microsoft.Speech)
See Also Send Feedback

By default, the semantic interpreter returns developer-defined properties of the Rule Variable as daughter nodes, where the element name for the node is the name of the property. If the script expression assigns a simple value to the property, the semantic interpreter returns the daughter node with its assigned value and a confidence value. In the following example, the script assigns the simple string value Orly to the Airport property. The speech recognition engine will return "Orly" when it recognizes the phrase "Paris".

XML Copy image Copy Code
<rule id="destination">
    Fly me to
    <one-of>
      <item> London <tag> out.Airport="Heathrow"; </tag></item>
      <item> Pairs <tag> out.Airport="Orly"; </tag></item>
      <item> Berlin <tag> out.Airport="Tegel"; </tag></item>
    </one-of>
</rule>

Using this grammar, the utterance "Fly me to Paris" produces the following SML output.

XML Copy image Copy Code
<SML text="Fly me to Paris" utteranceConfidence="0.840" confidence="0.840" >
    <Airport confidence="0.840"> Orly </Airport>
</SML>

Initializing Properties as Objects

If a script expression initializes a property of a Rule Variable as an object, the semantic interpreter returns a daughter node with a confidence attribute and the value of the object. If the object is empty, the interpreter returns an empty daughter node. The following grammar is identical to the previous grammar except that instead of assigning a simple scalar value to the Airport property, the expressions create Airport as an empty object.

XML Copy image Copy Code
<rule id="destination">
    Fly me to
    <one-of>
      <item> London<tag> out.Airport=new Object(); </tag></item>
      <item> Paris<tag> out.Airport=new Object(); </tag></item>
      <item> Berlin<tag> out.Airport=new Object(); </tag></item>
    </one-of>
</rule>

Using this grammar, the utterance "Fly me to Paris" produces the following SML output. Notice that there is no semantic value for Airport.

XML Copy image Copy Code
<SML text="Fly me to Paris" utteranceConfidence="0.840" confidence="0.840">
    <Airport confidence="0.840" />
</SML>

Returning Text Content in a Property Node

The text content contained in an SML node can be a simple type value only. To return an SML node that contains both a daughter node and text content in the daughter node, the script expression can assign the value to be returned to out.daughterNode. The following grammar illustrates this concept.

XML Copy image Copy Code
<rule id="destination">
  Fly me to
  <one-of>
    <item> London <tag> out.Airport="We fly to Heathrow airport"; </tag></item>
    <item> Paris <tag> out.Airport="We fly to Orly airport"; </tag></item>
    <item> Berlin <tag> out.Airport="We fly to Tegel airport"; </tag></item>
  </one-of>
</rule>

Using this grammar, the utterance "Fly me to Paris" produces the following SML output.

XML Copy image Copy Code
<SML text="Fly me to Paris" utteranceConfidence="0.840" confidence="0.840" >
    <Airport confidence="0.840"> We fly to Orly airport </Airport>
</SML>

Creating New Attributes for a Property Node

Use the _attributes property to add new developer-defined attributes to the nodes that are created by developer-defined properties. An important point to remember is that because the Airport property has a child property, it must be created with this script expression: out.Airport=new Object();. The following grammar is similar to the previous grammar except for the addition of script expressions that create new attributes in the Airport node of the SML output. Another difference between this grammar and the previous grammar is that the Airport node has text content and child nodes that have text content.

XML Copy image Copy Code
<rule id="destination">
  <tag>out.Airport=new Object();</tag>
  Fly me to
  <one-of>
    <item>London
      <tag>
        out.Airport._value="We fly to Heathrow airport";
        out.Airport._attributes.country="UK";
        out.Airport._attributes.code="EGLL";
        out.Airport._attributes.elevation="80 ft. MSL";
      </tag>
    </item>
    <item>Paris
      <tag>
        out.Airport._value="We fly to Orly airport";
        out.Airport._attributes.country="FR";
        out.Airport._attributes.code="LFPO";
        out.Airport._attributes.elevation="292 ft. MSL";
      </tag>
    </item>
    <item>Berlin
      <tag>
        out.Airport._value="We fly to Tegel airport";
        out.Airport._attributes.country="DEU";
        out.Airport._attributes.code="EDDT";
        out.Airport._attributes.elevation="121 ft. MSL";
      </tag>
    </item>
  </one-of>
</rule>

Using this grammar, the utterance "Fly me to Paris" produces the following SML output.

XML Copy image Copy Code
<SML text="Fly me to Paris" utteranceConfidence="0.949" confidence="0.949" >
  <Airport confidence="0.998" country="FR" code="LFPO" elevation="292 ft. MSL"> We fly to Orly airport </Airport>
</SML>

See Also

Concepts

Semantic Markup Language Reference (Microsoft.Speech)
Using the tag Element (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Serialization of Multiple Rule Grammars (Microsoft.Speech)

[image]

Serialization of Multiple Rule Grammars (Microsoft.Speech)
See Also Send Feedback

The SML output for a grammar containing multiple rules, but with no semantic interpretation markup, is similar to the output for a grammar containing a single rule. However, SML output for unmarked, multiple rule grammars has no confidence attribute. The top-level SML node has only the text and utteranceConfidence attributes. The text content of the SML node is the text of the utterance. The following grammar contains two rules, with the root rule, destination, referencing the second rule, FlightDay.

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" mode="voice" root="destination"
  xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="destination">
    Fly me to
    <one-of>
      <item> London </item>
      <item> Paris </item>
      <item> Berlin </item>
    </one-of>
    <ruleref uri="#FlightDay" />
  </rule>

  <rule id="FlightDay">
    on
    <one-of>
      <item> Monday </item>
      <item> Wednesday </item>
      <item> Friday </item>
    </one-of>
  </rule>
</grammar>

Using this grammar, the utterance "Fly me to Paris on Wednesday" produces the following SML output.

XML Copy image Copy Code
<SML text="Fly me to Paris on Wednesday" utteranceConfidence="0.777">
  Fly me to Paris on Wednesday
</SML>

Assigning to the _value Property

If the Root Rule Variable (RRV) remains an object, assigning a value to the _value property of referenced rules has no effect on the text content of the SML node. For a grammar with multiple rules, the result is that the value of only the RRV's _value property becomes the text content of the SML node. This scenario is illustrated in the following script; the script expressions in the FlightDay rule do not affect the text content of the RRV. The following grammar is identical to the previous grammar except for the addition of expressions in the second rule that assign a value to the _value property.

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" mode = "voice" root="destination"
  xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="destination">
    Fly me to
    <one-of>
      <item> London <tag> out._value="Arriving at Heathrow"; </tag></item>
      <item> Paris <tag> out._value="Arriving at Orly"; </tag></item>
      <item> Berlin <tag> out._value="Arriving at Tegel"; </tag></item>
    </one-of>
    <ruleref uri="#FlightDay" />
  </rule>

  <rule id="FlightDay">
    on
    <one-of>
      <item> Monday <tag> out._value=1; </tag></item>
      <item> Wednesday <tag> out._value=3; </tag></item>
      <item> Friday <tag> out._value=5; </tag></item>
    </one-of>
  </rule>
</grammar>

Using this grammar, the utterance "Fly me to Paris on Wednesday" produces the following SML output.

XML Copy image Copy Code
<SML text="Fly me to Paris on Wednesday" utteranceConfidence="0.839" confidence="0.839" >
    Arriving at Orly
</SML>

Passing Values from Rule to Rule

To pass a value from one rule to another, create a property as an object of the referencing rule and assign the value of the referenced rule's property to the referencing rule's object. The following grammar creates the weekDay property as an object of the root rule named destination. This causes weekDay to be represented as a separate node in the SML output. Although the following script shows weekDay being created as an unitialized object (out.weekDay = new Object();), this step is necessary only if weekDay itself has child properties of its own. The number of a weekday is assigned to the dayNumber property in the FlightDay rule. In the tag element associated with the ruleref element that targets the FlightDay rule, the weekDay property of the root rule is assigned the value of the referenced rule's dayNumber property. The expression rules.latest() represents the Rule Variable of the last-referenced rule, and the expression rules.latest().dayNumber represents the value of the dayNumber property on the Rule Variable of the last-referenced rule. Alternatively, the script expression out.weekDay=rules.FlightDay.dayNumber; produces the same results.

XML Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" mode="voice" root="destination"
  xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="destination">
    <tag> out.weekDay=new Object(); </tag>
    Fly me to
    <one-of>
      <item> London <tag> out._value="Arriving at Heathrow"; </tag></item>
      <item> Paris <tag> out._value="Arriving at Orly"; </tag></item>
      <item> Berlin <tag> out._value="Arriving at Tegel"; </tag></item>
    </one-of>
    <ruleref uri="#FlightDay" /><tag> out.weekDay=rules.latest().dayNumber; </tag>
  </rule>

  <rule id="FlightDay">
    on
    <one-of>
      <item> Monday <tag> out.dayNumber=1; </tag></item>
      <item> Wednesday <tag> out.dayNumber=3; </tag></item>
      <item> Friday <tag> out.dayNumber=5; </tag></item>
    </one-of>
  </rule>
</grammar>

Using this grammar, the utterance "Fly me to Paris on Wednesday" produces the following SML output.

XML Copy image Copy Code
<SML text="Fly me to Paris on Wednesday" utteranceConfidence="0.954" confidence="0.954" >
    Arriving at Orly
    <weekDay confidence="0.998"> 3 </weekDay>
</SML>
Note Note

This SML output illustrates serialization of a developer-defined property (the weekDay property). For more information, see Serialization of Developer-defined Rule Variable Properties (Microsoft.Speech).

See Also

Concepts

Semantic Markup Language Reference (Microsoft.Speech)
Using the tag Element (Microsoft.Speech)
tag Element (Microsoft.Speech)
ruleref Element (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Speech Synthesis (Microsoft.Speech)

[image]

Speech Synthesis (Microsoft.Speech)
Send Feedback

Speech synthesis, a technology also known as Text-to-Speech (TTS), converts textual information into synthetic speech output. Using the speech synthesis functionality in Microsoft Speech Platform SDK 11, you can generate speech from applications running on Windows Server.

Create SSML Content

The text that is converted to synthetic speech is usually called a prompt. You can author the content for prompts programmatically, or use the XML format that conforms to the Speech Synthesis Markup Language (SSML) Version 1.0. The PromptBuilder class contains methods for building prompt content from strings, SSML markup, and audio files. Speech synthesis content in XML format must be added to a PromptBuilder object before it can be spoken by the TTS engine.

Control Speech Output

You can control the characteristics of synthesized speech, for example you can select a speaking voice, change the current speaking voice, and specify voice characteristics such as language, age, and gender. You can also control attributes of speech such as volume, speaking rate, and emphasis.

Note Note

A speech synthesis engine can render speech in only one language; a different engine is required for each language. The Microsoft Speech Platform Runtime 11 and Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech. See InstalledVoice for more information.

In This Section

  • How Speech Synthesis Works (Microsoft.Speech)

  • Speak the Contents of a String (Microsoft.Speech)

  • Construct and Speak a Simple Prompt (Microsoft.Speech)

  • Construct a Complex Prompt (Microsoft.Speech)

  • Use SSML to Control Synthesized Speech (Microsoft.Speech)

  • Control Voice Attributes (Microsoft.Speech)

  • Use Speech Synthesis Events (Microsoft.Speech)

  • Use Bookmarks (Microsoft.Speech)

  • Speech Synthesis Markup Language Reference (Microsoft.Speech)

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


How Speech Synthesis Works (Microsoft.Speech)

[image]

How Speech Synthesis Works (Microsoft.Speech)
Send Feedback

A speech synthesizer takes text as input and produces an audio stream as output. Speech synthesis is also referred to as text-to-speech (TTS).

A synthesizer must perform substantial analysis and processing to accurately convert a string of characters into an audio stream that sounds just as the words would be spoken. The easiest way to imagine how this works is to picture the front end and back end of a two-part system.

Text Analysis

The front end specializes in the analysis of text using natural language rules. It analyzes a string of characters to determine where the words are (which is easy to do in English, but not as easy in languages such as Chinese and Japanese). This front end also figures out grammatical details like functions and parts of speech. For instance, which words are proper nouns, numbers, and so forth; where sentences begin and end; whether a phrase is a question or a statement; and whether a statement is past, present, or future tense.

All of these elements are critical to the selection of appropriate pronunciations and intonations for words, phrases, and sentences. Consider that in English, a question usually ends with a rising pitch, or that the word "read" is pronounced very differently depending on its tense. Clearly, understanding how a word or phrase is being used is a critical aspect of interpreting text into sound. To further complicate matters, the rules are slightly different for each language. So, as you can imagine, the front end must do some very sophisticated analysis.

Sound Generation

The back end has quite a different task. It takes the analysis done by the front end and, through some non-trivial analysis of its own, generates the appropriate sounds for the input text. Older synthesizers (and today's synthesizers with the smallest footprints) generate the individual sounds algorithmically, resulting in a very robotic sound. Modern synthesizers, such as the one used by the Microsoft Speech Platform Runtime 11, use a database of sound segments built from hours and hours of recorded speech. The effectiveness of the back end depends on how good it is at selecting the appropriate sound segments for any given input and smoothly splicing them together.

Ready to Use

The text-to-speech capabilities described above are built into the language packs that you can download free from the Microsoft Download Center, allowing server-based applications to easily use this technology. This eliminates the need to create your own speech engines. You can invoke all of this processing with a single function call. See Speak the Contents of a String (Microsoft.Speech).

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Speak the Contents of a String (Microsoft.Speech)

[image]

Speak the Contents of a String (Microsoft.Speech)
Send Feedback

A simple way to generate synthesized speech is to create a SpeechSynthesizer instance, and then call the synthesizer's Speak(String) method, passing the string to be spoken as an argument.

The following example shows the Main method of a class in a console application.

When Main begins to run, a SpeechSynthesizer instance named s is created, and then the Speak(String) method on s is called. The string literal to be spoken is passed in the call.

C# Copy image Copy Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Speech.Synthesis;

namespace SimpleSpeak
{
  class Program
  {
    static void Main(string[] args)
    {
      SpeechSynthesizer s = new SpeechSynthesizer();
      s.Speak("Hello. My name is Microsoft Server Speech Text to Speech Voice (en-US, Helen).");
    }
  }
}
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Construct and Speak a Simple Prompt (Microsoft.Speech)

[image]

Construct and Speak a Simple Prompt (Microsoft.Speech)
Send Feedback

For more control over how a phrase is spoken, create a prompt using a constructor on the PromptBuilder class. After you create a PromptBuilder instance with its empty prompt, you can append text, audio, Speech Synthesis Markup Language (SSML) markup, a bookmark, a break, or an existing PromptBuilder instance to the one you just created. After all of the prompt elements are in place, the prompt can be played.

Creating a PromptBuilder Instance

You can create a PromptBuilder instance by calling a PromptBuilder constructor. The constructor that takes no arguments, PromptBuilder()()()(), creates a PromptBuilder instance using the current language-culture setting of the computer, for example en-US. You can use the other constructor, PromptBuilder(CultureInfo), to set the culture to use for speaking the prompt. To perform text-to-speech using the language specified in the CultureInfo argument, a speech synthesis engine that supports that language-country code must be installed.

The following example creates a PromptBuilder instance, and then appends the string "Welcome, everyone" to the prompt.

C# Copy image Copy Code
PromptBuilder pb = new PromptBuilder();
pb.AppendText("Welcome, everyone");

Playing a Prompt

After a prompt is created, it can be played by calling the Speak(PromptBuilder) or SpeakAsync(PromptBuilder) methods on the SpeechSynthesizer instance. In the following example, a SpeechSynthesizer instance named synth has previously been created.

C# Copy image Copy Code
PromptBuilder pb = new PromptBuilder();
pb.AppendText("Welcome, everyone");
synth.Speak(pb);
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Construct a Complex Prompt (Microsoft.Speech)

[image]

Construct a Complex Prompt (Microsoft.Speech)
Send Feedback

When you create a PromptBuilder instance, it contains an empty Prompt object. You can append text, audio, Speech Synthesis Markup Language (SSML) markup, a bookmark, a break, or an existing PromptBuilder instance to the one you just created. After all of the prompt elements are in place, the prompt can be played.

Append Text to a Prompt

Text in the form of a string can be appended to a prompt in a number of ways, using any of the four AppendText()()()() overloaded methods, the two AppendTextWithHint()()()() overloaded methods, the AppendTextWithAlias(String, String) method, or the AppendTextWithPronunciation(String, String).

All four of the AppendText()()()() methods can be used to append a string to a prompt, but with three of these methods you can specify the emphasis, rate, or volume at which the prompt is played.

The two AppendTextWithHint()()()() methods can be used to provide a hint as to how the specified string should be spoken, using either a value in the SayAs enumerated type or using SSML markup. For more information, see say-as Element (Microsoft.Speech).

The AppendTextWithAlias(String, String) method can be used to append text that has substitute text. For example, the text that is appended might be "SAPI" and the alias text that will be spoken might be "Speech Application Programming Interface". For more information, see sub Element (Microsoft.Speech).

The AppendTextWithPronunciation(String, String) method can be used to append text and to provide the pronunciation for that text using characters from the International Phonetic Alphabet (IPA).

In the following example, prompts are created in three PromptBuilder instances, pb1, pb2, and pb3. When spoken, the first part of the prompt in pb1 is spoken at low volume, and the second part is spoken at high volume. When spoken, the prompt in pb2 is rendered as the text in the second parameter. When spoken, the prompt in pb3 is rendered as a date in month-day-year order, and the string "19" is rendered as "nineteenth".

C# Copy image Copy Code
PromptBuilder pb1 = new PromptBuilder();
PromptBuilder pb2 = new PromptBuilder();
PromptBuilder pb3 = new PromptBuilder();
pb1.AppendText("Soft", Microsoft.Speech.Synthesis.PromptVolume.ExtraSoft);
pb1.AppendText("Loud", Microsoft.Speech.Synthesis.PromptVolume.ExtraLoud);

pb2.AppendTextWithAlias("SAPI", "Speech Application Programming Interface");

pb3.AppendTextWithHint("2/19/2009", SayAs.MonthDayYear);
pb3.AppendText("February");
pb3.AppendTextWithHint("19", SayAs.NumberOrdinal);

Append Audio to a Prompt

To include audio from a .WAV file in a prompt, use one of the AppendAudio()()()() overloaded methods. With these methods you can specify the location of the audio file as a fully-qualified path or by its Uniform Resource Identifier (URI). Alternatively, you can specify alternate text to be played if the audio file is not available or not playable.

C# Copy image Copy Code
PromptBuilder pb = new PromptBuilder();
pb.AppendText("Now for some music");
pb.AppendAudio(new Uri("http://www.contoso.com/music/song.wav"),
"Please wait while we get the next song.");

Append SSML Markup to a Prompt

Speech Synthesis Markup Language (SSML) markup can be appended to a prompt in a number of ways. The AppendSsml()()()() overloaded methods can be used to append a file containing SSML markup at a specified path or at a specified Uniform Resource Identifier (URI) location. The SSML file must be an XML-format file that conforms to the Speech Synthesis Markup Language (SSML) Version 1.0 specification. For more information, see Use SSML to Control Synthesized Speech (Microsoft.Speech).

The AppendSsmlMarkup(String) method can be used to append the SSML markup specified in this method's string argument to the prompt. The prompt in the following example, when spoken, will render as "Today is January the twenty-ninth, two thousand nine."

C# Copy image Copy Code
PromptBuilder pb1 = new PromptBuilder();
string str1 = "<say-as type=\"date:mdy\">1/29/2009</say-as>";
pb1.AppendText("Today is ");
pb1.AppendSsmlMarkup(str1);
Note Note

The string used as an argument to AppendSsmlMarkup(String) must not include a speak element.

When spoken, the prompt in the next example renders the spelling of the word "chair."

C# Copy image Copy Code
PromptBuilder pb2 = new PromptBuilder();
string str2 = "<say-as interpret-as=\"characters\">chair</say-as>";
pb2.AppendSsmlMarkup(str2);

Append Breaks and Bookmarks to a Prompt

Breaks can be added to a prompt by the use of one of the AppendBreak()()()() overloaded methods. These methods can be used to append a break of default length, append a break with a length specified by a value of the PromptBreak enumeration, or append a break of a specified time duration.

You can insert a bookmark into a prompt using the AppendBookmark(String) method. When a bookmark is reached in a prompt, the SpeechSynthesizer instance raises the BookmarkReached event. For more information about events raised by the SpeechSynthesizer object, see Use Speech Synthesis Events (Microsoft.Speech).

C# Copy image Copy Code
PromptBuilder pb = new PromptBuilder();
pb.AppendText("Call me Ishmael.");
pb.AppendBreak();
pb.AppendBookmark("Start");

Change the Style or Voice of a Prompt

You can change the style of a PromptBuilder prompt by changing the emphasis, rate, or volume. These style changes affect the prominence or stress to apply to the spoken prompt (emphasis), the speaking rate to use (rate), and the loudness of the spoken output (volume). To change the style in a prompt, build up the prompt to the point at which you want to change the style, call StartStyle(PromptStyle) on the PromptBuilder instance, append the part of the prompt whose style you are changing, and then call EndStyle()()()() on the PromptBuilder instance. Changing the rate or volume is performed in a similar manner except that the PromptRate and PromptVolume enumerations are used in place of the PromptEmphasis enumeration.

The following example demonstrates style change in two prompts. In the first prompt, the first two words of the prompt use the default style, and the last two words of the prompt are spoken at reduced emphasis. In the second prompt, the last word of the prompt is spoken with strong emphasis. The variable named synth is a SpeechSynthesizer instance.

C# Copy image Copy Code
PromptBuilder pb = new PromptBuilder();

pb.AppendText("Normal emphasis ");
pb.StartStyle(new PromptStyle(PromptEmphasis.Reduced));
pb.AppendText("reduced emphasis");
pb.EndStyle();
string XMLStr = pb.ToXml();
synth.Speak(pb);
pb.ClearContent();

pb.AppendText("Come into the house");
pb.StartStyle(new PromptStyle(PromptEmphasis.Strong));
pb.AppendText("now");
pb.EndStyle();
XMLStr = pb.ToXml();
synth.Speak(pb);
pb.ClearContent();

Divide Prompts into Sentences and Paragraphs

Long prompts can be rendered more like human speech if they are broken into sentences and paragraphs. The StartParagraph()()()() overloaded methods can be used to start a paragraph in a prompt, and the StartSentence()()()() overloaded methods can be used to start a sentence. To end a sentence, use EndSentence()()()(), and to end a paragraph, use EndParagraph()()()().

C# Copy image Copy Code
PromptBuilder pb = new PromptBuilder();
pb.StartParagraph();
pb.StartSentence();
pb.AppendText("This is the first sentence.");
pb.EndSentence();
pb.StartSentence();
pb.AppendText("This is the second sentence.");
pb.EndSentence();
pb.EndParagraph();
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Use SSML to Control Synthesized Speech (Microsoft.Speech)

[image]

Use SSML to Control Synthesized Speech (Microsoft.Speech)
Send Feedback

You can use the AppendSsmlMarkup(String) method to append a string containing Speech Synthesis Markup Language (SSML) to a prompt. This topic shows simple examples that use a variety of SSML elements in prompts. For more information about SSML elements, see Speech Synthesis Markup Language Reference (Microsoft.Speech).

Note Note

The string used as an argument to AppendSsmlMarkup(String) must not include a speak element.

Add Emphasis to a Prompt

The emphasis element can be used to render speech at a higher stress level. For more information, see emphasis Element (Microsoft.Speech). The following example creates a prompt that, when played, renders the phrase "Normal speech" normally, and then renders the phrase "emphasized speech" in an emphasized fashion.

C# Copy image Copy Code
SpeechSynthesizer synth = new SpeechSynthesizer();
PromptBuilder pb1 = new PromptBuilder();
string str1 = "<emphasis> emphasized speech </emphasis>";
pb1.AppendText("Normal speech ");
pb1.AppendSsmlMarkup(str1);
synth.Speak(pb1);

Append Audio to a Prompt

The audio element can be used to append audio to a prompt. In the following example, the synthesizer speaks "Subsitute text" if it cannot find or play the audio file. For more information, see audio Element (Microsoft.Speech).

C# Copy image Copy Code
SpeechSynthesizer synth = new SpeechSynthesizer();
PromptBuilder pb2 = new PromptBuilder();
string str2 = "<audio src = \"C:\\song.wav\"> Substitute text </audio>";
pb2.AppendText("And now a song: ");
pb2.AppendSsmlMarkup(str2);
synth.Speak(pb2);

Append Substitute Text to a Prompt

The sub element can be used to provide alternate text to be rendered. In the following example, the synthesizer speaks "First in first out". For more information, see sub Element (Microsoft.Speech).

C# Copy image Copy Code
SpeechSynthesizer synth = new SpeechSynthesizer();
PromptBuilder pb3 = new PromptBuilder();
string str3 = "<sub alias=\"First in first out\"> F. I. F. O. </sub>";
pb3.AppendSsmlMarkup(str3);
synth.Speak(pb3);

Append Phonemes to a Prompt

The phoneme element can be used to render speech by its phonetic pronunciation. For more information, see phoneme Element (Microsoft.Speech). The following example creates a prompt that, when played, renders the Spanish word "llama" approximately as it would be spoken in Mexican Spanish.

C# Copy image Copy Code
SpeechSynthesizer synth = new SpeechSynthesizer();
PromptBuilder pb4 = new PromptBuilder();
string str4 = "<phoneme alphabet=\"x-microsoft-ups\" ph=\"J AA M AX\"> llama </phoneme>";
pb4.AppendSsmlMarkup(str4);
synth.Speak(pb4);
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Control Voice Attributes (Microsoft.Speech)

[image]

Control Voice Attributes (Microsoft.Speech)
See Also Send Feedback

A computer may have multiple synthesizer voices installed that represent various combinations of language, age, and gender. You can select the voice to use with methods on the SpeechSynthesizer object. In addition, you can embed commands in prompts using methods on the PromptBuilder object that change the voice that the synthesizer uses while it is processing prompts.

Note Note

A voice is an installed speech synthesis engine, which is also referred to as a text-to-speech engine or a TTS engine. The Microsoft Speech Platform Runtime 11 and Microsoft Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech. See InstalledVoice for more information.

Select a Voice

When you create a new SpeechSynthesizer object, it uses the default system voice. To select one of the other installed voices, use the SelectVoice(String) or SelectVoiceByHints()()()() methods. Using the SelectVoiceByHints()()()() methods, you can specify characteristics of the voice you want to select, such as language-culture, gender, and age.

Use the GetInstalledVoices()()()() method to find out which voices are available for the synthesizer to use. The VoiceInfo class provides detailed information about an installed voice.

Change the Voice

With the StartVoice()()()() overloaded methods on the PromptBuilder class, you can change the voice used in speech synthesis, change the culture of the voice, or change the gender or age of the voice.

To change the voice in use by the synthesizer, call the StartVoice(String) method, providing the name of the voice in the call. For English (U.S.), the name of the default synthesis voice is "Microsoft Anna." When the voice is no longer needed, call the EndVoice()()()() method. After EndVoice()()()() returns, the voice is reset to the voice in use before the call to StartVoice(String).

An application that has registered a handler for the VoiceChange event can determine the details of the voice change by inspecting the handler's VoiceChangeEventArgs argument. For more information, see Use Speech Synthesis Events (Microsoft.Speech).

Change the Culture

To change the culture of the synthesizer voice, call the StartVoice(CultureInfo) method, passing an initialized CultureInfo instance that represents the desired culture. To generate speech using the language specified in the CultureInfo argument, a speech synthesis engine that supports that language-country code must be installed.

Change a Voice's Gender and Age

There are three methods that can be used to change the synthesizer's gender, age, or both.

To change the voice's gender, call the StartVoice(VoiceGender) method, passing a value from the VoiceGender enumeration in the call.

To change the voice's gender and age, call the StartVoice(VoiceGender, VoiceAge) method, passing values from the VoiceGender and VoiceAge enumerations in the first and second parameters. To change only the age, pass the current gender value and the new age value.

To change the voice's gender and age and to specify a preferred voice when more than one voice matches the gender and age parameters, call the StartVoice(VoiceGender, VoiceAge, Int32) method. Pass in the gender and age and an integer that specifies the preferred voice among those that match the gender and age parameters. This parameter represents the variant attribute that is defined in the Speech Synthesis Markup Language 1.0 specification for the voice element.

See Also

Other Resources

Speech Synthesis Markup Language (SSML) Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Use Speech Synthesis Events (Microsoft.Speech)

[image]

Use Speech Synthesis Events (Microsoft.Speech)
Send Feedback

As a SpeechSynthesizer instance emits synthesized speech, it raises events for which applications can register event handlers. See the example at the end of this topic for more information.

Some events report the progress of the speech synthesizer in the speaking of a prompt. In ascending degrees of granularity, these events range from reporting each individual character or word processed, to features encountered in a prompt such as bookmarks, to the beginning and ending of the speaking of an entire prompt.

Other events report on the state of the speech synthesizer and on the changing of its speaking voice. The following table lists events on the SpeechSynthesizer class.

Event | Description
BookmarkReached | Raised when a bookmark in a prompt is reached.
SpeakCompleted | Raised after a prompt is completely spoken.
SpeakProgress | Raised after an individual word of a prompt is spoken.
SpeakStarted | Raised when a prompt is first spoken.
StateChanged | Raised when the state of the SpeechSynthesizer instance changes. The states are Paused, Ready, and Speaking.
VoiceChange | Raised when the voice in use by the SpeechSynthesizer changes.

Each of the events listed in the table is associated with a particular EventArgs class. Many of these associated classes contain properties named Cancelled, Error, and UserState that are inherited from the AsyncCompletedEventArgs class. These properties indicate, respectively, whether the particular asynchronous operation was cancelled, information about an error if one occurred, and an identifier for the asynchronous task that raised the event. In addition to these common properties, some of the event argument classes contain specialized properties, which are described under the following headings.

BookmarkReached

You can insert a bookmark into a prompt using the AppendBookmark(String) method. A synthesizer will raise the BookmarkReached event when it encounters the bookmark. This event is associated with the BookmarkReachedEventArgs class, which has properties that store the position in the audio stream (AudioPosition) and the name of the bookmark (Bookmark). For more information, see Use Bookmarks (Microsoft.Speech).

SpeakCompleted

The synthesizer automatically raises the SpeakCompleted event when it finishes speaking the synthesized prompt. This event is associated with the SpeakCompletedEventArgs class. The Prompt property on this class contains the prompt that caused the SpeakCompleted event to be raised.

SpeakProgress

The synthesizer raises the SpeakProgress event periodically after the synthesized prompt has begun playing. These events are triggered as the speech synthesizer processes individual words in a prompt. This event is associated with the SpeakProgressEventArgs class, which contains the following properties that provide information about the prompt: AudioPosition, CharacterCount, CharacterPosition, Prompt, and Text.

SpeakStarted

The synthesizer automatically raises the SpeakStarted event when the synthesizer begins speaking the prompt it has synthesized. This event is associated with the SpeakStartedEventArgs class. The Prompt property on this class contains the prompt that caused the SpeakStarted event to be raised.

StateChanged

The synthesizer raises the StateChanged event when its state changes. This event is associated with the StateChangedEventArgs class, which has properties that indicate the synthesizer's previous state (PreviousState) and its state after the change (State). The possible states (Paused, Ready, and Speaking) are members of the SynthesizerState enumeration.

VoiceChange

The synthesizer raises the VoiceChange event when the voice used for synthesis (the speaking voice) changes. This event is associated with the VoiceChangeEventArgs class. The only property of this class contains a VoiceInfo object, which provides information about the new voice, including the age, culture, and gender of the speaker. For more information, see Control Voice Attributes (Microsoft.Speech).

Examples

The following example shows a method that creates a SpeechSynthesizer instance named synth. The method then registers event handlers for the SpeakStarted, SpeakProgress, SpeakCompleted, and BookmarkReached events. Following this method are simple event handlers for these events. The variable synth is a SpeechSynthesizer instance that is assumed to be declared at the class level.

C# Copy image Copy Code
private void Form1_Load(object sender, EventArgs e)
{
  synth = new SpeechSynthesizer();
  synth.SpeakStarted += new EventHandler<SpeakStartedEventArgs>(synth_SpeakStarted);
  synth.SpeakProgress += new EventHandler<SpeakProgressEventArgs>(synth_SpeakProgress);
  synth.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(synth_SpeakCompleted);
  synth.BookmarkReached += new EventHandler<BookmarkReachedEventArgs>(synth_BookmarkReached);
}

C# Copy image Copy Code
void synth_SpeakStarted(object sender, SpeakStartedEventArgs e)
{
  AddEventText("Speak started");
}

void synth_SpeakProgress(object sender, SpeakProgressEventArgs e)
{
  AddEventText("Speak progress: " + e.Text);

  if (e.CharacterPosition + e.CharacterCount <= textBox.Text.Length &&
        textBox.Text.Substring(e.CharacterPosition, e.CharacterCount) == e.Text)
  {
    textBox.Select(e.CharacterPosition, e.CharacterCount);
  }
}

void synth_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
{
  AddEventText("Speak completed");

  textBox.SelectAll();
  textBox.Focus();
}

void synth_BookmarkReached(object sender, BookmarkReachedEventArgs e)
{
  AddEventText("Bookmark reached: " + e.Bookmark);
}
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Use Bookmarks (Microsoft.Speech)

[image]

Use Bookmarks (Microsoft.Speech)
Send Feedback

By inserting a bookmark into a prompt you can identify a particular moment of time with a specific position in the prompt. One use for bookmarks is to permit an application to track the time between when a prompt was played and when a customer service representative responded to a customer's call.

To insert a prompt into a PromptBuilder prompt, call AppendBookmark(String), providing the name of the bookmark.

C# Copy image Copy Code
PromptBuilder pb = new PromptBuilder();
pb.AppendText("A customer service representative will be with you shortly.");
pb.AppendBookmark("Bookmark1");
synth.Speak(pb);
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


East Asian Language Support for Office Communications Server 2007 R2

[image]

East Asian Language Support for Office Communications Server 2007 R2
Send Feedback

In Windows XP and Windows 2003, for text-to-speech to function for traditional Chinese, simplified Chinese, Japanese, and Korean, the client computer must have the files for East Asian languages installed. To install these files:

  1. Open the Regional and Language Options control panel.

  2. Select the Languages tab.

  3. Under Supplemental language support, check Install files for East Asian languages.

  4. Click Apply, and follow the instructions for installing the files.

Differences in Word Breaking on Different Operating Systems

Because of platform dependent files, word breaking in Japanese, simplified Chinese, and traditional Chinese might produce different results when conducted on Windows Server 2003 and Windows Server 2008.

Support for English Within East Asian Languages

Neither the traditional Chinese nor the Simplified Chinese text-to-speech engine supports English word reading.

Support for the 32-bit Text-to-Speech Engine on a 64-bit Operating System

To use the 32-bit text-to-speech engine on a 64-bit operating system, run the application in 32-bit mode for both managed and unmanaged processes. For .NET projects, you can configure Visual Studio to build your application with different settings based on the target CPU type.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Speech Synthesis Markup Language Reference (Microsoft.Speech)

[image]

Speech Synthesis Markup Language Reference (Microsoft.Speech)
Send Feedback

Speech Synthesis Markup Language (SSML) is an XML-based markup language that application developers use to control various characteristics of synthetic speech (text-to-speech, or TTS) output including voice, pitch, rate, volume, pronunciation, and other characteristics.

The Microsoft implementation of SSML is based on World Wide Web Consortium Speech Synthesis Markup Language (SSML) Version 1.0.

All SSML elements belong to the ssml namespace. The following elements are implemented in the Microsoft Speech Platform SDK 11.

SSML Element | Description | Usage | Attributes
audio | Supports the insertion of recorded audio files. | Optional | src
break | An empty element used to control the prosodic boundaries between words. | Optional | strength, time
emphasis | Increases the level of stress with which the contained text is spoken. | Optional | level
lexicon | Specifies a lexicon document that contains the pronunciations for the content of the document. | Optional | uri, type
mark | Designates a specific reference point in the text sequence. This element can also be used to mark an output audio stream for asynchronous notification. | Optional | name
p and s | Denote the paragraph and sentence structure of the document. | Optional | xml:lang
phoneme | Indicates the phonetic pronunciation for the contained text. Overrides the pronunciations in the lexicon, if one is specified. | Optional | ph, alphabet
prosody | Controls the pitch, rate, and volume of the speech output. | Optional | pitch, contour, range, rate, duration, volume
say-as | Indicates the type of text contained in the element (such as acronym, number, and date). | Optional | interpret-as, format, detail
speak | The required root element for all SSML documents. | Required | version, xmlns, xml:lang
sub | Specifies a string of text that should be pronounced in place of the text contained in the element. | Optional | alias
voice | Specifies a voice and its attributes, to be used for synthesized speech, often used to change from one voice to another. | Optional | xml:lang, gender, age, variant, name

In This Section

  • audio Element (Microsoft.Speech)

  • break Element (Microsoft.Speech)

  • emphasis Element (Microsoft.Speech)

  • lexicon Element SSML (Microsoft.Speech)

  • mark Element (Microsoft.Speech)

  • p and s Elements (Microsoft.Speech)

  • phoneme Element (Microsoft.Speech)

  • prosody Element (Microsoft.Speech)

  • say-as Element (Microsoft.Speech)

  • speak Element (Microsoft.Speech)

  • sub Element (Microsoft.Speech)

  • voice Element (Microsoft.Speech)

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


audio Element (Microsoft.Speech)

[image]

audio Element (Microsoft.Speech)
Send Feedback

Supports the insertion of recorded audio files.

Syntax

XML Copy image Copy Code
<audio src="string" /> </audio>

Attributes

Attribute | Description
src | Required. Specifies the path and name of the audio file. The value of this attribute can be an absolute, local path for speech applications running in a local environment, but it must be an HTTP. This attribute is case-sensitive only when referencing files residing in file systems that are case-sensitive.

The audio element supports WMA files and .WAV files containing RIFF headers and encoded with the following parameters.

Parameter | Value
Format | PCM, a-law, u-law
Bit-depth | 8 bits, 16 bits
Channels | Mono only
Sampling Rate | All sampling rates supported.

Remarks

Use this element to play a known audio file.

The content of a non-empty audio element should be the plain text or SSML marked-up text to be spoken if the audio file specified in the src attribute is either not available or unplayable. The content of a non-empty element can also include another audio element.

Example

XML Copy image Copy Code
<?xml version="1.0" encoding="ISO-8859-1"?>
<speak version="1.0"
 xmlns="http://www.w3.org/2001/10/synthesis"
 xml:lang="en-US">

<p>
<audio src="http://www.treyresearch.net/audioprompts/opinionprompt.wav"> Thanks for offering your opinion. Please begin speaking after the beep. </audio>

<audio src="http://www.treyresearch.net/audioprompts/beep.wav"> The beep could not
be played, please voice your opinion now. </audio>
</p>

</speak>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


break Element (Microsoft.Speech)

[image]

break Element (Microsoft.Speech)
Send Feedback

An empty element used to control the prosodic boundaries (pauses) between words.

Syntax

XML Copy image Copy Code
<break />
<break strength="string" />
<break time="string" />

Attributes

Attribute | Description
strength | Optional. Specifies the relative duration of a pause using one of the following enumeration values: none, x-weak, weak, medium, strong, or x-strong. The default value is medium.
time | Optional. Specifies the absolute duration of a pause in seconds or milliseconds. Examples of valid values are 2s and 500ms.

Remarks

Use this element to override the automatic behavior of the text-to-speech (TTS) engine for a word or phrase if the automatically synthesized speech for that word or phrase sounds unnatural. The value none in the strength attribute can be used to prevent a prosodic break which the speech synthesis engine would otherwise insert.

The actual millisecond values associated with each of the enumeration values of the strength attribute depends on the individual speech synthesis engine. For break elements in which the strength or time attributes do not specify a value for the duration of the break, the speech synthesis engine automatically determines a duration value based on the linguistic context.

Example

XML Copy image Copy Code
<?xml version="1.0" encoding="ISO-8859-1"?>
<speak version="1.0"
 xmlns="http://www.w3.org/2001/10/synthesis"
 xml:lang="en-US">

<sentence>
The phone number is one eight hundred <break strength="weak" />
five five five <break time="500ms" /> one two three four.
</sentence>

</speak>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emphasis Element (Microsoft.Speech)

[image]

emphasis Element (Microsoft.Speech)
Send Feedback

Increases the level of stress (prominence) with which the contained text is spoken.

Syntax

XML Copy image Copy Code
<emphasis level="string"> </emphasis>

Attributes

Attribute | Description
level | Indicates the strength of emphasis to be applied, using one of the following enumeration values: strong, moderate, none, reduced. The default level is moderate.

Remarks

The rendering of the contents of the emphasis element can vary depending on the speech synthesis engine, in particular among speech synthesis engines of different languages. Emphasis may be implemented using one or more of pitch change, timing changes, loudness, or other acoustic differences. A value of none in the level attribute can be used to prevent the speech synthesis engine from emphasizing words that it might typically emphasize.

Example

XML Copy image Copy Code
<?xml version="1.0" encoding="ISO-8859-1"?>
<speak version="1.0"
 xmlns="http://www.w3.org/2001/10/synthesis"
 xml:lang="en-US">

<sentence>
Please speak <emphasis level="strong"> loudly </emphasis>
</sentence>

</speak>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


lexicon Element SSML (Microsoft.Speech)

[image]

lexicon Element SSML (Microsoft.Speech)
Send Feedback

Specifies an external pronunciation lexicon file.

Syntax

XML Copy image Copy Code
<lexicon
    uri = lexiconURI
    type = mediaType />

Attributes

Attribute | Description
uri | Required. Specifies the location of the pronunciation lexicon, which is a relative URI or an absolute URI.
type | Optional. Specifies the media type of the pronunciation lexicon document. Microsoft.Speech currently supports two values. The value application/vdn.ms-sapi-lex indicates the lexicon format is "Uncompressed Lexicon", which was created by Microsoft. The value application/pls+xml indicates that the lexicon conforms to the Pronunciation Lexicon Specification (PLS) Version 1.0 specification.

Remarks

The lexicon element is an immediate child of the speak element. Multiple lexicon elements can occur in a Speech Synthesis Markup Language (SSML) document. If there are references to multiple lexicons, the order in which they are listed dictates their priority. Speech synthesis (TTS) engines use lexicons of higher priority first when determining which pronunciations to use.

The pronunciation information provided by a lexicon is specific to the single language declared in the xml:lang attribute of the speak element, and is used only for content defined within the enclosing SSML document.

Example

XML Copy image Copy Code
<?xml version="1.0"?>
<!DOCTYPE speak PUBLIC "-//W3C//DTD SYNTHESIS 1.0//EN"
                  "http://www.w3.org/TR/speech-synthesis/synthesis.dtd">
<speak version="1.0"
  xmlns="http://www.w3.org/2001/10/synthesis"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.w3.org/2001/10/synthesis
  http://www.w3.org/TR/speech-synthesis/synthesis.xsd"
  xml:lang="en-US">

  <lexicon uri="http://www.contoso.com/lexicon.lex" type="application/vdn.ms-sapi-lex"/>
  <lexicon uri="http://www.contoso.com/lexicon2.lex" type="application/pls+xml"/>

<!-- Content for the prompt goes here -->

</speak>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


mark Element (Microsoft.Speech)

[image]

mark Element (Microsoft.Speech)
Send Feedback

Designates a specific reference point in the text sequence. This element can also be used to mark an output audio stream for asynchronous notification.

Syntax

XML Copy image Copy Code
<mark name="string" />

Attributes

Attribute | Description
name | Required. Identifies the name of the mark element. The value is a string.

Remarks

Use the empty mark element to insert a marker into an output stream to trigger asynchronous notification.

When the application reaches the mark element, the text-to-speech engine raises an event that includes the value for the name attribute of the element. In Microsoft.Speech, the speech synthesizer raises a BookmarkReached event when it encounters a mark element.

Example

XML Copy image Copy Code
<?xml version="1.0" encoding="ISO-8859-1"?>
<speak version="1.0"
 xmlns="http://www.w3.org/2001/10/synthesis"
 xml:lang="en-US">

<s>
We guarantee that your call will be answered in less
than three minutes. <mark name="beginWait"/>
</s>

</speak>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


p and s Elements (Microsoft.Speech)

[image]

p and s Elements (Microsoft.Speech)
Send Feedback

The p and s elements mark the paragraph and sentence structure of the document.

Syntax

XML Copy image Copy Code
<p xml:lang="string"> </p>
<s xml:lang="string"> </s>

Attributes

Attribute | Description
xml:lang | Optional. Specifies the language to be used for the enclosed text. The value may contain only a lower-case, two-letter language code, (such as "en" for English or "it" for Italian) or may optionally include an upper-case, country/region or other variation in addition to the language code. Examples with a county/region code include "es-US" for Spanish as spoken in the US, or "fr-CA" for French as spoken in Canada. See the Remarks section for additional information.

Remarks

Use of these elements is optional. The speech engine automatically determines the structure of the document in the absence of these elements. A speech synthesis engine may produce changes in prosody when it encounters a p or s element.

The Microsoft Speech Platform SDK 11 accepts all valid language-country codes as values for the xml:lang attribute. For a given language code specified in the xml:lang attribute, a speech synthesis engine that supports that language code must be installed to correctly pronounce words in the specified language.

If the xml:lang attribute specifies only a language code, (such as "en" for English or "es" for Spanish), and not a country/region code, then any installed speech synthesis voice that expresses support for that generic, region-independent language may produce acceptable pronunciations for words in the specified language. See Language Identifier Constants and Strings for a comprehensive list of language codes.

The paragraph and sentence elements may declare different languages in their xml:lang attributes than the language declared in the speak element. The Speech Platform SDK 11 supports multiple languages in SSML documents.

Note Note

The Microsoft Speech Platform Runtime 11 and Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech. See InstalledVoice for more information.

Example

XML Copy image Copy Code
<?xml version="1.0" encoding="ISO-8859-1"?>
<speak version="1.0"
 xmlns="http://www.w3.org/2001/10/synthesis"
 xml:lang="en-US">

  <p>
    <s> Introducing the sentence element. </s>
    <s> It may be used to mark individual sentences. </s>
  </p>

  <p>
    Another simple paragraph.
    Sentence structure in this paragraph is not explicitly marked.
  </p>

</speak>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


phoneme Element (Microsoft.Speech)

[image]

phoneme Element (Microsoft.Speech)
Send Feedback

Specifies the phonetic pronunciation for the contained text using phones from a supported phonetic alphabet.

Syntax

XML Copy image Copy Code
<phoneme alphabet="string" ph="string"> </phoneme>

Attributes

Attribute | Description
alphabet | Optional. Specifies the phonetic alphabet to use when synthesizing the pronunciation of the ph string. The string specifying the alphabet is case-sensitive and must be entered in lowercase letters. The only acceptable values are ipa or x-microsoft-sapi or x-microsoft-ups. The pronunciation alphabet specified applies only to the containing phoneme.
ph | Required. A string containing phones that specify the pronunciation of the word contained by the phoneme element. If the specified string contains unrecognized phones, the text-to-speech (TTS) engine rejects the entire SSML document and produces none of the speech output specified in the document.

Remarks

Phonetic alphabets are composed of phones, which consist of letters, numbers or characters, sometimes in combination. Each phone describes a unique sound of speech. This is in contrast to the Latin alphabet, for which any letter may represent multiple spoken sounds. Consider the different pronunciations of the letter "c" in the words "candy" and "cease", or the different pronunciations of the letter combination "th" in the words "thing" and "those". See Lexicons and Phonetic Alphabets (Microsoft.Speech) for more information.

Even though the TTS engine ignores the content of the phoneme element (it pronounces only the string specified in the ph attribute), place text content in the element so that devices without speech capability can still render something intelligible in place of speech.

Example

XML Copy image Copy Code
<?xml version="1.0" encoding="ISO-8859-1"?>
<speak version="1.0"
 xmlns="http://www.w3.org/2001/10/synthesis"
 xml:lang="en-US">

  <s>
    His name is Mike <phoneme alphabet="x-microsoft-ups" ph="JH AU"> Zhou </phoneme>
  </s>

</speak>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


prosody Element (Microsoft.Speech)

[image]

prosody Element (Microsoft.Speech)
Send Feedback

Specifies the pitch, contour, range, rate, duration, and volume for speaking the contained text.

Syntax

XML Copy image Copy Code
<prosody pitch="value" contour="value" range="value" rate="value" duration="value" volume="value"> </prosody>

Attributes

Attribute

Description

pitch

Optional. Indicates the baseline pitch for the contained text. This value may be expressed in one of three ways:

  • An absolute value, expressed as a number followed by "Hz" (Hertz). For example, 600Hz.

  • A relative value, expressed as a number preceded by "+" or "-" and followed by "Hz" or "st", that specifies an amount to change the pitch. For example +80Hz or -2st. The "st" indicates the change unit is semitone, which is half of a tone (a half step) on the standard diatonic scale.

  • An enumeration value, from among the following: x-low, low, medium, high, x-high, or default.

contour

Optional. Represents changes in pitch for speech content as an array of targets at specified time positions in the speech output. Each target is defined by sets of parameter pairs, for example:

<prosody contour="(0%,+20Hz) (10%,-2st) (40%,+10Hz)">

The first value in each set of parameters specifies the location of the pitch change as a percentage of the duration of the contained text (a number followed by "%"). The second value specifies the amount to raise or lower the pitch, using a relative value or an enumeration value for pitch, see above.

range

Optional. A value that represents the range of pitch for the contained speech content. This value may be expressed using the same absolute values, relative values, or enumeration values used to describe pitch, see above.

rate

Optional. Indicates the speaking rate of the contained text. This value may be expressed in one of two ways:

  • A relative value, expressed as a number that acts as a multiplier of the default. For example, a value of 1 results in no change in the rate. A value of .5 results in a halving of the rate. A value of 3 results in a tripling of the rate.

  • An enumeration value, from among the following: x-slow, slow, medium, fast, x-fast, or default.

duration

Optional. A value in seconds or milliseconds for the period of time that should elapse while the speech synthesis (TTS) engine reads the contents of the element. For example 2s or 1800ms.

volume

Optional. Indicates the volume level of the speaking voice. This value may be expressed in one of three ways:

  • An absolute value, expressed as a number in the range of 0.0 to 100.0, from quietest to loudest. For example, 75. The default is 100.0.

  • A relative value, expressed as a number preceded by "+" or "-" that specifies an amount to change the volume. For example +10 or -5.5.

  • An enumeration value, from among the following: silent, x-soft, soft, medium, loud, x-loud, or default.

Note Note

Standards for well-formed, valid XML require attribute values to be enclosed in double quotation marks. For example, <prosody volume="90"> is a well-formed, valid element, but <prosody volume=90> is not.

Remarks

Because prosodic attribute values can vary over a wide range, the speech recognizer interprets the assigned values as a suggestion of what the actual prosodic values of the selected voice should be. The text-to-speech (TTS) engine limits or substitutes values that are not supported. Examples of unsupported values are a pitch of 1 MHz or a volume of 120.

Example

XML Copy image Copy Code
<?xml version="1.0" encoding="ISO-8859-1"?>
<speak version="1.0"
 xmlns="http://www.w3.org/2001/10/synthesis"
 xml:lang="en-US">

  <s>
    Your order for <prosody pitch="+1st" rate="-10%" volume="90"> 8 books </prosody>
    will be shipped tomorrow.
  </s>

</speak>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


say-as Element (Microsoft.Speech)

[image]

say-as Element (Microsoft.Speech)
Send Feedback

The say-as element indicates the content type (such as number or date) of text contained in the element. This provides guidance to the speech synthesis engine about how to pronounce the contained text.

Syntax

XML Copy image Copy Code
<say-as interpret-as="string" format="digit string" detail="string"> <say-as>

Attributes

Attribute

Description

interpret-as

Required. Indicates the content type of text contained in the element. The SSML 1.0 say-as attribute values specification defines six content types.

format

Optional. Provides additional information about the precise formatting of the contained text for content types that may have ambiguous formats. SSML defines formats for content types that use them.

detail

Optional. Indicates the level of detail to be spoken. For example, this attribute might request that the speech synthesis engine pronounce punctuation marks.

There are no standard values defined for the detail attribute. Support for this attribute depends on the individual speech synthesis engine.

The following table lists the supported content types for the interpret-as attribute, and the supported values for the format attribute, where applicable.

Interpret-as | Format | Interpretation
date | dmy, mdy, ymd, ym, my, md, dm, d, m, y | The contained text is a date in the specified format. In the format designations, d=day, m=month, and y=year. The format for date indicates which date components are represented and their sequence. The following is an example of a say-as element that contains a date: Today is <say-as interpret-as="date" format="mdy">10-19-2003</say-as> The speech synthesizer should pronounce "Today is October nineteenth two thousand three".
cardinal | - | The contained text should be spoken as a cardinal number. The following is an example of a say-as element that contains a cardinal number: There are <say-as interpret-as="cardinal">3</say-as> alternatives. The speech synthesizer should pronounce "There are three alternatives".
ordinal | - | The contained text should be interpreted as an ordinal number. The following is an example of a say-as element that contains an ordinal number: Select the <say-as interpret-as="ordinal">3rd</say-as> option. The speech synthesizer should pronounce "Select the third option".
characters | - | Indicates that each letter in the contained text should be pronounced individually (spelled out). The following is an example of a say-as element that contains a word that should be spoken as individual letters: <say-as interpret-as="characters">test</say-as>. The speech synthesizer should pronounce each letter: "T E S T".
time | hms12, hms24 | The contained text is a time. Time may be expressed using either a 12-hour clock (hms12) or a 24-hour clock (hms24).The format attribute indicates which clock to use. The following is an example of a say-as element that contains a time: The train departs at <say-as interpret-as="time" format="hms12">4:00am</say-as>. The speech synthesizer should speak "The train departs at four A M". Use a colon to separate numbers representing hours, minutes, and seconds. The following time strings are all valid examples: 12:35, 1:14:32, 08:15, and 02:50:45.
telephone | digit string | The contained text is a telephone number. The format attribute may contain digits that represent a country code, for example "1" for the United States or "39" for Italy. The speech synthesis engine may use this information to guide its pronunciation of a phone number. The country code may also be included in the phone number, and if so, takes precedence over the country code in the format attribute if there is a mismatch. The following is an example of a say-as element that contains a telephone number: The number is <say-as interpret-as="telephone" format="1">(888) 555-1212</say-as>. The speech synthesizer should speak "My number is area code eight eight eight five five five one two one two".

Example

The speech synthesis engine should speak the following example as "Your first request was for one room on October nineteenth twenty ten with early arrival at twelve thirty five P M".

XML Copy image Copy Code
<?xml version="1.0" encoding="ISO-8859-1"?>
<speak version="1.0"
 xmlns="http://www.w3.org/2001/10/synthesis"
 xml:lang="en-US">

  <p>
    Your <say-as interpret-as="ordinal"> 1st </say-as> request
    was for <say-as interpret-as="cardinal"> 1 </say-as> room
    on <say-as interpret-as="date" format="mdy"> 10/19/2010 </say-as>,
    with early arrival at <say-as interpret-as="time" format="hms12"> 12:35pm </say-as>.
  </p>

</speak>

For more information, see the SSML 1.0 say-as attribute values and the Speech Synthesis Markup Language (SSML) Version 1.0

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


speak Element (Microsoft.Speech)

[image]

speak Element (Microsoft.Speech)
Send Feedback

The required root element of a Speech Synthesis Markup Language (SSML) document.

Syntax

XML Copy image Copy Code
<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="string"> </speak>

Attributes

Attribute | Description
version | Required. Indicates the version of the World Wide Web Consortium Speech Synthesis Markup Language (SSML) Version 1.0 specification used to interpret the document markup. The current version is 1.0.
xml:lang | Required. Specifies the language of the root document. The value may contain only a lower-case, two-letter language code, (such as en for English or it for Italian) or may optionally include an upper-case, country/region or other variation in addition to the language code. Examples with a county/region code include es-US for Spanish as spoken in the US, or fr-CA for French as spoken in Canada. See the Remarks section for additional information.
xmlns | Required. Specifies the URI to the document that defines the markup vocabulary (the element types and attribute names) of the SSML document. The current URI is http://www.w3.org/2001/10/synthesis.

Remarks

The Microsoft Speech Platform SDK 11 accepts all valid language-country codes as values for the xml:lang attribute. For a given language code specified in the xml:lang attribute, a speech synthesis engine that supports that language code must be installed to correctly pronounce words in the specified language.

If the xml:lang attribute specifies only a language code, (such as "en" for English or "es" for Spanish), and not a country/region code, then any installed speech synthesis voice that expresses support for that generic, region-independent language may produce acceptable pronunciations for words in the specified language. See Language Identifier Constants and Strings for a comprehensive list of language codes.

The p and s elements may declare different languages in their xml:lang attributes than the language declared in the speak element. The Speech Platform SDK 11 supports multiple languages in SSML documents.

Note Note

The Microsoft Speech Platform Runtime 11 and Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech. See InstalledVoice for more information.

The other elements in the SSML document that also take the xml:lang attribute (voice, paragraph, and sentence) may declare different languages than the language declared in the speak element. The Speech Platform SDK 11 supports multiple languages in SSML documents.

Example

The following example creates a prompt that counts to ten; beginning in English, then in French, and finishing in German. Correct pronunciation of all the numbers will only be achieved if language packs for English, French, and German have been installed. As it processes the prompt, the SpeechSynthesizer object automatically selects and uses the default voice (if installed) for each language specified by an xml:lang attribute.

XML Copy image Copy Code
<?xml version="1.0" encoding="ISO-8859-1"?>
<speak version="1.0"
 xmlns="http://www.w3.org/2001/10/synthesis"
 xml:lang="en-US">

  <!-- Count in English -->
  <p> one, two, three </p>

  <!-- Count in French -->
  <p xml:lang="fr-FR"> quatre, cinq, six </p>

  <!-- Count in German -->
  <p xml:lang="de-DE"> sieben, acht, neun, zehn </p>

</speak>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


sub Element (Microsoft.Speech)

[image]

sub Element (Microsoft.Speech)
Send Feedback

Specifies a string of text to speak in place of the text contained in the element.

Syntax

XML Copy image Copy Code
<sub alias="string"> </sub>

Attributes

Attribute | Description
alias | Required. Specifies the substitute text.

Remarks

Before synthesizing a phrase, the text-to-speech (TTS) engine normalizes it. The normalization process converts symbols, numbers, and other non-orthographic entities into text representing the spoken value of these entities. For example, normalization converts "$1.99" into "one dollar and ninety-nine cents."

Use a sub element to create a custom text value for any text element. Because the TTS engine processes sub elements before normalizing the phrase, the substitute text is normalized before being synthesized.

Example

XML Copy image Copy Code
<?xml version="1.0" encoding="ISO-8859-1"?>
<speak version="1.0"
 xmlns ="http://www.w3.org/2001/10/synthesis"
 xml:lang="en-US">

  <!--Instruct the text-to-speech engine to pronounce
  the string "SAPI" as "Speech Application Programming Interface"-->

  <sub alias="Speech Application Programming Interface"> SAPI </sub>

</speak>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


voice Element (Microsoft.Speech)

[image]

voice Element (Microsoft.Speech)
Send Feedback

With the parameters of the voice element, you can change the voice used in speech synthesis and also specify the attributes of the voice such as the culture, the gender, and the age of the voice.

Syntax

XML Copy image Copy Code
<voice name"string" gender="string" age="integer" xml:lang="string" variant="integer"> </voice>

Attributes

Attribute | Description
name | Optional. Specifies the name of the installed voice that will speak the contained text.
gender | Optional. Specifies the preferred gender of the voice that will speak the contained text. The allowed values are: male, female, and neutral.
age | Optional. Specifies the preferred age in years of the voice that will speak the contained text. The allowed values are: 10 (child), 15 (teen), 30 (adult), and 65 (senior).
xml:lang | Optional. Specifies the language that the voice must support. The value may contain only a lower-case, two-letter language code, (such as "en" for English or "it" for Italian) or may optionally include an upper-case, country/region or other variation in addition to the language code. Examples with a county/region code include "es-US" for Spanish as spoken in the US, or "fr-CA" for French as spoken in Canada. See the Remarks section for additional information.
variant | Optional. An integer that specifies a preferred voice when more than one voice matches the values specified in any of the xml:lang, gender, or age parameters.

Remarks

Although each of its attributes is individually optional, a voice element must have at least one attribute specified.

The Microsoft Speech Platform SDK 11 accepts all valid language-country codes as values for the xml:lang attribute. For a given language code specified in the xml:lang attribute, a speech synthesis engine that supports that language code must be installed to correctly pronounce words in the specified language.

If the xml:lang attribute specifies only a language code, (such as "en" for English or "es" for Spanish), and not a country/region code, then any installed speech synthesis voice that expresses support for that generic, region-independent language may produce acceptable pronunciations for words in the specified language. See Language Identifier Constants and Strings for a comprehensive list of language codes.

Note Note

The Microsoft Speech Platform Runtime 11 and Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech. See InstalledVoice for more information.

The voice element may declare a different language in its xml:lang attribute than the language declared in the speak element. The Speech Platform SDK 11 supports multiple languages in SSML documents.

Example

The following example speaks a phrase in English. The example then changes the speaking voice by specifying the French speech synthesis voice for Microsoft Server, and speaks the same phrase in French.

XML Copy image Copy Code
<?xml version="1.0" encoding="ISO-8859-1"?>
<speak version="1.0"
 xmlns:ssml="http://www.w3.org/2001/10/synthesis"
 xml:lang="en-US">

  This is the text that the application will speak.

  <voice name="Microsoft Server Speech Text to Speech Voice (fr-FR, Hortense)">
  Ceci est le texte qui sera prononcé par l'application.
  </voice>

</speak>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Language Support

[image]

Language Support
Send Feedback

The Microsoft Speech Platform SDK 11 provides support for 26 languages for both speech recognition and speech synthesis (TTS or text-to-speech). You must download and install a language pack for each language that you want to program against in your applications. There are separate language packs for speech recognition and speech synthesis. The version of the language packs that you use for development, for example version 11.0, must match the version of the Server Runtime that you installed.

Use the following links to download language packs that match your Speech Platform Runtime version.

  • Microsoft Speech Platform - Server Runtime Languages v11.0

  • Microsoft Speech Platform - Server Runtime Languages v10.2

  • Microsoft Speech Platform - Server Runtime Languages v10.1

  • Microsoft Speech Platform - Server Runtime Languages v10.0 (13 languages only)

Supported Languages

You can download language packs in the following languages for use with the Speech Platform SDK 11.

Language-Country | Language-County Code | Hexadecimal Value
Catalan - Spain | ca-ES | 0x0403
Danish - Denmark | da-DK | 0x0406
German - Germany | de-DE | 0x0C07
English - Australia | en-AU | 0x0C09
English - Canada | en-CA | 0x1009
English - Great Britain | en-GB | 0x0809
English - Indian | en-IN | 0x4009
English - United States | en-US | 0x0409
Spanish - Spain | es-ES | 0x2C0A
Spanish - Mexico | es-MX | 0x080A
Finnish - Finland | fi-FI | 0x040B
French - Canada | fr-CA | 0x0C0C
French - France | fr-FR | 0x040c
Italian - Italy | it-IT | 0x0410
Japanese - Japan | ja-JP | 0x0411
Korean - Korea | ko-KR | 0x0412
Norwegian - Norway | nb-NO | 0x0414
Dutch - Netherlands | nl-NL | 0x0813
Polish - Poland | pl-PL | 0x0415
Portuguese - Brazil | pt-BR | 0x0416
Portuguese - Portugal | pt-PT | 0x0816
Russian - Russia | ru-RU | 0x0419
Swedish - Sweden | sv-SE | 0x081D
Chinese - China | zh-CN | 0x0804
Chinese - Hong Kong | zh-HK | 0x0C04
Chinese - Taiwan | zh-TW | 0x0404

For more information about language codes, see Language Identifier Constants and Strings.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Lexicons and Phonetic Alphabets (Microsoft.Speech)

[image]

Lexicons and Phonetic Alphabets (Microsoft.Speech)
Send Feedback

A pronunciation lexicon contains words and their pronunciations, and defines all or part of the vocabulary for a speech application. Speech engines usually include a default lexicon, which you can supplement with custom lexicons that are specific to one or more of your applications. You can use lexicons to optimize the performance of speech recognition and speech synthesis (text-to-speech).

The pronunciations in a lexicon are specified as phonetic spellings that use combinations of letters, numbers, characters, and symbols to represent the sounds of spoken language. There are multiple phonetic alphabets, each of which uses a different character set to describe the pronunciations of words. The phonetic spellings in a lexicon typically use only one phonetic alphabet.

Follow the links below for introductory and reference information about lexicons and phonetic alphabets.

  • About Lexicons and Phonetic Alphabets (Microsoft.Speech)

  • Pronunciation Lexicon Reference (Microsoft.Speech)

  • Phonetic Alphabet Reference (Microsoft.Speech)

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


About Lexicons and Phonetic Alphabets (Microsoft.Speech)

[image]

About Lexicons and Phonetic Alphabets (Microsoft.Speech)
Send Feedback

Overview

Lexicons contain the mapping between the written representations and the pronunciations of words or short phrases. Speech recognition engines and speech synthesis engines each have an internal lexicon that specifies which words in a language can be recognized or spoken. The lexicon specifies how the engine expects a word to be pronounced using characters from a single phonetic alphabet.

A phonetic alphabet contains combinations of letters, numbers, and characters which are known as "phones". Phones describe the spoken sounds of one or more human languages, and represent the valid set of tokens that can be used to define the pronunciations of words using phonetic spellings. Similar to those used in dictionaries, phonetic spellings in lexicons describe how words should be pronounced for speech recognition or for speech synthesis.

For example, here are two phonetic spellings that a speech engine can use to recognize or speak the word "hello" in US English:

  • H EH . S1 L O

  • hh ax . 1 l ow

The first example uses phones from the Universal Phone Set (UPS). The letters indicate the spoken segments that make up the word. The "S1" is a stress symbol that indicates which syllable should be accented. The second example uses phones from the SAPI phone set. The "1" is a stress symbol that indicates which syllable should be accented. In both examples, the phones are space-delimited, and the "." separates the syllables in the word.

Note Note

Microsoft.Speech supports three phonetic alphabets. See Phonetic Alphabet Reference (Microsoft.Speech) for descriptions and lexicon Element PLS (Microsoft.Speech) for how to specify a phonetic alphabet.

A speech recognition engine listens for pronunciations of words that correspond to phonetic spellings that are specified in its internal lexicon. A speech synthesis engine pronounces words as specified by the phonetic spellings in its internal lexicon. A speech engine can also create pronunciations on-the-fly for words it encounters that are not included its lexicon. A speech engine includes an acoustic model and a language model. The acoustic model describes the sounds of a language, while the language model describes how words are distributed in spoken language. The speech engine's language model and acoustic model enable it to process spoken variations of the pronunciations specified in its lexicon, as well as new words.

Application Lexicons

You can supplement a speech engine's default lexicon by creating an application-specific lexicon to improve the accuracy of speech recognition or to customize the vocabulary and pronunciations of a synthesized voice. This is often not necessary because a speech engine can find and create pronunciations for both common and uncommon words in a language.

However, if your application includes words that feature unusual spelling or atypical pronunciation of familiar spellings, then the speech engine may not create the pronunciation that works best for your application. In these cases, you can specify a custom pronunciation that may improve the recognition accuracy for the specialized vocabulary in your application. For example you can create an application lexicon that does the following:

  • Contains words that are not included in the default lexicon and specifies their pronunciations. For example, you can add proper nouns, such as place names and business names, or words that are specific to specialized areas of business, education, or medicine.

  • Specifies new pronunciations that replace the pronunciations defined for words that are already included in the default lexicon. For example, you can add pronunciations that capture regional variations of languages, dialects, slang, and common mispronunciations. You can specify multiple phonetic spellings (pronunciations) for a word. The speech recognition engine accepts all pronunciations of a word in a lexicon; the speech synthesis engine chooses and speaks only one of the pronunciations for a word in a lexicon. See the prefer attribute of the phoneme Element PLS (Microsoft.Speech).

The words and pronunciations that you create in application-specific lexicons take precedence over the pronunciations in a speech engine's default lexicon. Pronunciations specified inline in speech recognition grammar documents and in speech synthesis prompt documents and take precedence over pronunciations in both application-specific lexicons and default lexicons. See Inline Pronunciations later in this topic.

Multiple lexicons may be active simultaneously for an application. For example, if an application references multiple grammars that each reference a different lexicon, then the application has access to all the words and pronunciations contained in all the referenced lexicons in addition to the speech engine's default lexicon.

In Microsoft.Speech, each grammar document can reference only one lexicon. This is a departure from the Speech Recognition Grammar Specification (SRGS) Version 1.0, see SRGS Grammar XML Reference (Microsoft.Speech).

Authoring Lexicons

You author lexicons as XML documents that follow the format of the Pronunciation Lexicon Specification (PLS) Version 1.0. Lexicon documents must declare the single language-culture of the words in the lexicon and the phonetic alphabet used to construct the pronunciations. See Pronunciation Lexicon Reference (Microsoft.Speech) for a summary reference of the PLS specification and for information that is specific to Microsoft's implementation of PLS.

Here is an example of a short lexicon that contains two spellings of a word and two pronunciations, one of which is designated as preferred. Note the declaration of the phonetic alphabet used to create the pronunciations, given in the alphabet attribute of the lexicon Element PLS (Microsoft.Speech).

XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<lexicon version="1.0"
      xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
        http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
      alphabet="x-microsoft-sapi" xml:lang="en-US">
  <lexeme>
    <grapheme>theater</grapheme>
    <grapheme>theatre</grapheme>
    <phone prefer="true">1 th iy . ax . t ax r</phone>
    <phone>th iy . 1 eh . t ax r</phone>
  </lexeme>
</lexicon>

Specifying Lexicons

After you have authored a lexicon, you must reference it from a speech recognition grammar document or a speech synthesis prompt document to use its words and pronunciations. An application-specific lexicon is only active while the grammar or prompt document that references it is active.

  • To specify which lexicon to use for speech recognition, use the lexicon Element (Microsoft.Speech) in an XML-format grammar that conforms to the Speech Recognition Grammar Specification (SRGS) Version 1.0.

  • To specify which lexicon to use for speech synthesis, use the lexicon Element SSML (Microsoft.Speech) in an XML-format prompt document that conforms to the Speech Synthesis Markup Language (SSML) Version 1.0.

You can also specify lexicons programmatically for speech synthesis, using the AddLexicon(Uri, String) method.

Lexicons are reusable. For example, you can reference a lexicon that contains specialized medical terms from multiple grammars or prompts in an application, or from multiple applications. You can use the same lexicon for both speech recognition and speech synthesis.

Inline Pronunciations

In addition to creating custom pronunciations in lexicon documents, you can also specify custom pronunciations inline in speech recognition grammar documents and in speech synthesis prompt documents. Again, speech engines are quite adept at creating pronunciations for uncommon words, so be sure to test your custom pronunciations to verify that they improve the speech experience for users of your application.

  • Use the sapi:pron attribute of the token Element (Microsoft.Speech) to specify an inline pronunciation in an SRGS grammar document. The sapi:pron attribute was created by Microsoft to provide an extra measure of control over the pronunciation of specific instances of words for recognition, supplementing the SRGS specification (see SRGS Grammar XML Reference (Microsoft.Speech)).

  • Use the ph attribute of the phoneme Element (Microsoft.Speech)to specify an inline pronunciation in an SSML prompt document.

Inline pronunciations apply only for the single instance of the element in which they are specified.

You can also specify inline pronunciations programmatically. For speech recognition, use the Pronunciation property. For speech synthesis, use the AppendTextWithPronunciation(String, String) method.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Pronunciation Lexicon Reference (Microsoft.Speech)

[image]

Pronunciation Lexicon Reference (Microsoft.Speech)
See Also Send Feedback

Pronunciation lexicons contain the mapping between the pronunciations and the written representations of words or short phrases. You can use lexicons to improve the accuracy of speech recognition or to customize the vocabulary and pronunciations of a synthesized voice.

The implementation of lexicons in Microsoft.Speech is based on World Wide Web Consortium (W3C) Pronunciation Lexicon Specification (PLS) Version 1.0, which defines the structure and syntax for XML-based lexicon documents.

The following table lists and describes elements from the PLS specification that are implemented in Microsoft.Speech. Elements are listed in the order in which they occur in a PLS document,

PLS Element | Description | Usage | Attributes
lexicon | The root element in a lexicon document that contains all the other elements. | Required | version, xml:base, xmlns, xml:lang, alphabet
meta | Specifies information about the document. | Optional | name, http-equiv, content
metadata | Contains information about the document in a metadata schema. | Optional | -
lexeme | Must contain one or more grapheme elements, one or more pronunciations (each in a separate phoneme element), and can optionally contain one or more example elements. | Optional | xml:id
grapheme | A child element of the lexeme element, it contains the written representation of a word or phrase in a lexeme element. | Optional | -
phoneme | A child element of the lexeme element, it contains a single phonetic pronunciation of a word or phrase in a lexeme element. | Optional | prefer, alphabet
example | A child element of the lexeme element, it contains an example sentence that illustrates an occurrence of a lexeme. | Optional | -

Remarks

Although the PLS specification does not require that lexicon documents contain lexeme elements, a lexicon is not useful for pronunciation without them.

The meta and metadata elements must occur before the first lexeme element.

Currently, Microsoft does not support the alias element that is defined in the PLS specification.

PLS lexicons used in Microsoft.Speech are not required to contain an XML prolog, for example: <?xml version="1.0" encoding="UTF-8"?>

See Also

Concepts

About Lexicons and Phonetic Alphabets (Microsoft.Speech)
Phonetic Alphabet Reference (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


lexicon Element PLS (Microsoft.Speech)

[image]

lexicon Element PLS (Microsoft.Speech)
Send Feedback

Specifies the highest level container for an XML-format lexicon document.

Syntax

XML Copy image Copy Code
<lexicon
   version = "1.0"
   xmlns = "http://www.w3.org/2001/06/grammar"
   alphabet = "ipa" | "x-microsoft-sapi" | "x-microsoft-ups"
   xml:lang = "(language code-country/region code)"
</lexicon >

Attributes

Attribute | Description
alphabet | Required. Specifies the default pronunciation alphabet to be used within the PLS document. The only acceptable values are ipa or x-microsoft-sapi or x-microsoft-ups. These values are case-sensitive and must be entered in lower case.
version | Required. Specifies the version number of the Pronunciation Lexicon Specification (PLS) Version 1.0 used. The only accepted value is 1.0.
xml:base | Optional. Specifies a lexicon document's base Uniform Resource Identifier (URI). The value for xml:base is used to resolve relative URIs in a lexicon document. Currently, only the contents of the metadata element can potentially use relative URIs.
xml:lang | Required. Declares the single language for the content of the containing lexicon document. The value can contain only a lower-case, two-letter language code, (such as "en" for English or "it" for Italian) or may optionally include an upper-case, country/region or other variation in addition to the language code. Examples with a county-region code include es-US for Spanish as spoken in the US, or fr-CA for French as spoken in Canada.
xmlns | Required. Specifies the XML namespace for W3C pronunciation lexicon. The XML namespace is "http://www.w3.org/2005/01/pronunciation-lexicon".

Remarks

The pronunciation alphabet specified in the alphabet attribute may be overridden for a specific lexeme using the alphabet attribute of the phoneme Element PLS (Microsoft.Speech). You can also specify a phonetic alphabet programmatically for a speech recognition grammar, using the PhoneticAlphabet property.

See Phonetic Alphabet Reference (Microsoft.Speech) for more information about the phonetic alphabets that Microsoft Speech supports.

For a given language code declared in the xml:lang attribute, a speech engine that supports that language code must be installed for the lexicon to be loaded successfully.

If the xml:lang attribute specifies only a language code, and not a country/region code, (such as xml:lang="en"), then any installed speech engine that expresses support for that generic, region-independent language will be able to load the lexicon.

Example

The following example illustrates the use of the alphabet attribute of the phoneme element to specify a pronunciation using a different phonetic alphabet than the one specified by the alphabet attribute in the lexicon element, for a single instance of the word "hello".

Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<lexicon version="1.0"
      xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
        http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
      alphabet="ipa" xml:lang="en-US">

  <lexeme>
    <grapheme> hello </grapheme>
    <phoneme alphabet="x-microsoft-ups"> S1 H EH . L O </phoneme>
  </lexeme>

</lexicon>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


meta Element PLS (Microsoft.Speech)

[image]

meta Element PLS (Microsoft.Speech)
Send Feedback

Specifies metadata about the pronunciation lexicon document. Metadata is information about a document in contrast to the document content.

Syntax

XML Copy image Copy Code
<meta
  name = "seeAlso"
  http-equiv = "string"
  content = "string" />

Attributes

Attribute | Description
name | Optional. Specifies the property name of the metadata. The only value accepted is seeAlso. All meta elements must specify a name attribute or an http-equiv attribute, but not both.
http-equiv | Optional. Binds the meta element to the HTTP response header, specifying information that should be included in that response header. All meta elements must specify a name attribute or an http-equiv attribute, but not both. Use only values that are known by the Web server or defined in the Document Type Definition (DTD).
content | Required. Specifies the value of the metadata property identified by the name attribute.

Remarks

The meta element must occur before all lexeme elements contained with the root lexicon element.

Example

XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<lexicon version="1.0"
      xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
        http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
      alphabet="ipa" xml:lang="en-US">
    <meta http-equiv="Cache-Control" content="no-cache"/>
    <meta name="seeAlso" content="http://example.com/my-pls-metadata.xml"/>

    <!--  Begin adding lexemes here. -->

</lexicon>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


metadata Element PLS (Microsoft.Speech)

[image]

metadata Element PLS (Microsoft.Speech)
Send Feedback

Contains information about the pronunciation lexicon document in a metadata schema.

Syntax

XML Copy image Copy Code
<metadata>...</metadata>

Attributes

None.

Remarks

The metadata element may be located either before or after the meta element, but must occur before all lexeme elements contained within the root lexicon element.

The metadata element is a container in which authors can place information about the document using a metadata schema. Authors can use any metadata schema. However, the Pronunciation Lexicon Specification (PLS) Version 1.0 recommends that authors use the Resource Description Format (RDF) schema in conjunction with the general metadata properties (for example, Title, Creator, Subject, Description, and Copyrights) defined in the Dublin Core Metadata Initiative.

Example

XML Copy image Copy Code
 <?xml version="1.0" encoding="UTF-8"?>
<lexicon version="1.0"
      xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
        http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
      alphabet="ipa" xml:lang="en-US">
  <metadata>
    <rdf:RDF
       xmlns:rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
       xmlns:dc  = "http://purl.org/dc/elements/1.1/">

     <!-- Metadata about the PLS document -->
     <rdf:Description rdf:about=""
       dc:title="Pronunciation lexicon for W3C terms"
       dc:description="Common pronunciations for many W3C acronyms and abbreviations, i.e. I18N or WAI"
       dc:publisher="W3C"
       dc:date="2005-11-29"
       dc:rights="Copyright 2002 W3C"
       dc:format="application/pls+xml">
       <dc:creator>The W3C Voice Browser Working Group</dc:creator>
     </rdf:Description>
    </rdf:RDF>
  </metadata>

  <!--  Begin adding lexemes here. -->

</lexicon>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


lexeme Element (Microsoft.Speech)

[image]

lexeme Element (Microsoft.Speech)
See Also Send Feedback

Contains one or more written representations of a word, one or more pronunciations of the word, and may include an example usage of the word in a sentence.

Syntax

XML Copy image Copy Code
<lexeme
    xml:id = string
<lexeme/>

Attributes

Attribute | Description
xml:id | Optional. Allows the lexeme to be referenced from other documents.

Remarks

The lexeme element contains one or more grapheme elements, one or more pronunciations (each contained in a separate phoneme element), and zero or more example elements. All the pronunciations given within a lexeme apply to each and every grapheme within the lexeme.

The children of the lexeme element may appear in any order, but note that the order in which the pronunciations are listed may determine which pronunciation a speech synthesis engine selects. See phoneme Element PLS (Microsoft.Speech).

Example

This example contains a pronunciation for the grapheme "lead", specified in the phoneme element, and a sample usage of a pronunciation given in the example element. The pronunciation given in the phoneme element uses phones from Microsoft's Universal Phone Set (UPS), which is specified in the alphabet attribute of the lexicon element.

XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<lexicon version="1.0"
      xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
        http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
      alphabet="x-microsoft-ups" xml:lang="en-US">

  <lexeme>
    <grapheme> lead </grapheme>
    <phoneme> S1 L EH D </phoneme>
    <example> My feet were as heavy as lead </example>
  </lexeme>

</lexicon>

See Also

Concepts

Phonetic Alphabet Reference (Microsoft.Speech)
About Lexicons and Phonetic Alphabets (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


grapheme Element (Microsoft.Speech)

[image]

grapheme Element (Microsoft.Speech)
Send Feedback

Contains the written representation of a word or a short phrase.

Syntax

XML Copy image Copy Code
<grapheme> string </grapheme>

Attributes

None.

Remarks

The grapheme element must contain one or more letters, numbers, or characters.

There may be alternative textual representations for the same word or phrase, for example:

  • Regional spelling variations, such as "colour" and "color".

  • Free spelling variations, such as "judgment" and "judgement"

  • Alternate writing systems, for example Japanese uses a mixture of Han ideographs (Kanji), and phonemic spelling systems (Katakana or Hiragana) for representing the orthography of a word or phrase, and such mixture sometimes has several variations as in kana suffixes following kanji stems (Okurigana) for example "okonau" (行なう vs. 行う);

  • Reformed spellings, for example in German some of the words which once were written with "ß" are now written with "ss".

To accommodate the variations described above, the lexeme element may contain more than one grapheme element.

Example

The following example has two grapheme entries to encompass multiple spellings of a word, both of which share the same pronunciation.

Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<lexicon version="1.0"
      xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
        http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
      alphabet="ipa" xml:lang="en-US">
  <!-- English entry showing how alternative spellings are handled -->

  <lexeme>
    <grapheme> colour </grapheme>
    <grapheme> color </grapheme>
    <phoneme> ˈkʌlər </phoneme>
  </lexeme>

</lexicon>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


phoneme Element PLS (Microsoft.Speech)

[image]

phoneme Element PLS (Microsoft.Speech)
See Also Send Feedback

Contains the phonetic spelling that describes how a lexeme is pronounced.

Syntax

XML Copy image Copy Code
<phoneme
   prefer = "true" | "false"
   alphabet = "ipa" | "x-microsoft-sapi" | "x-microsoft-ups"
</phoneme>

Attributes

Attribute

Description

prefer

Optional. The possible values are: true or false. The default value is false.

alphabet

Optional. Specifies the pronunciation alphabet used to construct the contained phonetic spelling. The only acceptable values are ipa or x-microsoft-sapi or x-microsoft-ups. These values are case-sensitive and must be entered in lower case.

The pronunciation alphabet specified applies only to the containing phoneme, overriding the value of the alphabet attribute in the lexicon element.

Remarks

A lexeme element may contain multiple phoneme elements. A speech recognition engine will recognize all pronunciations specified in phoneme elements. A speech syntheses engine can speak only one pronunciation and must make a selection if multiple pronunciations are present, using one of the following strategies:

  • If only one pronunciation has prefer set to true, the speech synthesis engine selects it.

  • If more than one pronunciation has prefer set to true, the speech synthesis engine selects the one listed first in the document.

  • If none of multiple pronunciations has prefer set to true, the speech synthesis engine selects the one listed first in the document.

  • Alternatively, a speech synthesis engine may have an internal mechanism that selects pronunciations according to another strategy.

Examples

In the following example, "read" has two pronunciations. A speech recognition engine will recognize both pronunciations, whereas a speech synthesis engine will only use one. Since none of the pronunciations has prefer set to true, unless the speech synthesis engine mandates a different strategy, it will use the first pronunciation in document order, in this case "S1 R EH D".

Note that the phones in the phoneme element are case-sensitive and must be space-delimited. See Phonetic Alphabet Reference (Microsoft.Speech) for more information. Each phoneme element can contain only one pronunciation.

XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<lexicon version="1.0"
      xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
        http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
      alphabet="x-microsoft-ups" xml:lang="en-US">

  <lexeme>
    <grapheme> read </grapheme>
    <phoneme> S1 R EH D </phoneme>
    <phoneme> S1 R I D </phoneme>
  </lexeme>

</lexicon>

The following example illustrates the use of the alphabet attribute of the phoneme element to specify two pronunciations for a single instance of the word "lead", using a different phonetic alphabet than the one specified in the lexicon element.

Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<lexicon version="1.0"
      xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
        http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
      alphabet="ipa" xml:lang="en-US">
  <lexeme>
    <grapheme>lead</grapheme>
    <phoneme alphabet="x-microsoft-sapi"> 1 l iy d</phoneme>
    <phoneme alphabet="x-microsoft-sapi" prefer="true"> 1 l eh d</phoneme>
  </lexeme>
</lexicon>

In the example above, a speech recognition engine will recognize both pronunciations. A speech synthesis engine can use only one pronunciation, in this case the second pronunciation listed because it has prefer set to true.

See Also

Concepts

Phonetic Alphabet Reference (Microsoft.Speech)
About Lexicons and Phonetic Alphabets (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


example Element PLS (Microsoft.Speech)

[image]

example Element PLS (Microsoft.Speech)
Send Feedback

Contains an example sentence that illustrates an occurrence of a lexeme.

Syntax

XML Copy image Copy Code
<example>string</example>

Attributes

None.

Remarks

One or more example elements may be provided for a single lexeme element. The example element must contain one or more letters, numbers, or characters, and cannot contain other elements.

Example

The example below shows the use of the example element to provide a sample usage for alternate pronunciations of the word "lead". It is acceptable to include comments with example elements, as well as elsewhere within the lexicon element, using the syntax shown in the example.

Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<lexicon version="1.0"
      xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
        http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
      alphabet="ipa" xml:lang="en-US">

  <lexeme>
    <grapheme> lead </grapheme>
    <phoneme> led </phoneme>
    <example> My feet were as heavy as lead. <!-- possible comment --> </example>
  </lexeme>

  <lexeme>
    <grapheme> lead </grapheme>
    <phoneme> liːd </phoneme>
    <example> The guide once again took the lead. </example>
  </lexeme>

</lexicon>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Phonetic Alphabet Reference (Microsoft.Speech)

[image]

Phonetic Alphabet Reference (Microsoft.Speech)
Send Feedback

A phonetic alphabet contains combinations of letters, numbers, and characters which are known as "phones". A phone represents a discrete sound in a spoken language. Phones are used to create phonetic spellings that determine how a word should be pronounced to be recognized or spoken. Microsoft.Speech supports three phonetic alphabets:

  • International Phonetic Alphabet (IPA). A system of phonetic notation based primarily on the Latin alphabet, devised as a standardized representation of the sounds of spoken language. You can use this phonetic alphabet to specify pronunciations for any language.

  • Universal Phone Set (UPS). A machine-readable phonetic alphabet, created by Microsoft, which is based on the International Phonetic Alphabet (IPA). You can use this phonetic alphabet to specify pronunciations for any language except those that use the SAPI phonetic alphabet, see the next item.

  • Speech API (SAPI) Phone Set. The pronunciation alphabet used in Microsoft.Speech for the following languages:

Language-Culture Code | Language Name | Language ID
zh-TW | Chinese (Taiwan) | 404
zh-CN | Chinese (PRC) | 804
en-US | English (United States) | 409
fr-FR | French (Standard) | 40c
de-DE | German (Standard) | 407
jp-JP | Japanese | 411
es-ES | Spanish (Spain, Traditional Sort) | 40a

Phone Tables

Humans create speech sounds by generating airflow with one or more of the lungs, ribs, diaphragm, larynx, tongue, or cheeks and by modifying the airflow in the vocal tract. Typically, some part of the tongue moves relative to some part of the roof of the mouth to restrict the airflow in varying degrees.

From greatest to least stricture, speech sounds may be classified as stop consonants (with occlusion, or blocked airflow), fricative consonants (with partially blocked and therefore strongly turbulent airflow), approximants (with reduced airflow but no turbulence), and vowels (with full unimpeded airflow). Affricates are sequences of stop plus fricative that behave as a single phoneme.

This section contains lists of phones for each of the speech sound classifications. The tables encompass the phonetic alphabets that Microsoft.Speech supports, and include Unicode and ASCII equivalents, where applicable.

  • Consonants (Microsoft.Speech) are speech sounds that are articulated with complete (voiceless) or partial closure of the vocal tract.

  • Vowels (Microsoft.Speech) are speech sounds that are articulated with an open vocal tract.

  • Diacritics (Microsoft.Speech) are used to modify segmental phones (vowels, consonants, clicks, and ejectives) with additional phonetic detail.

  • Suprasegmentals (Microsoft.Speech) describe the features of a language above the level of individual consonants and vowels, such as prosody, tone, length, and stress.

  • Clicks and Ejectives (Microsoft.Speech) are voiceless consonants with specific velaric and glottalic airflow features. An example of a click in US English is tsk! tsk!.

  • Tones (Microsoft.Speech) describe the use of pitch in speech sounds to distinguish lexical or grammatical meaning.

  • Other Phones (Microsoft.Speech) contains rare phones that are not included in the main IPA consonant table.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Consonants (Microsoft.Speech)

[image]

Consonants (Microsoft.Speech)
Send Feedback

This is a listing and cross reference of the consonant phones that are used by the three phonetic alphabets that Microsoft.Speech supports. See Phonetic Alphabet Reference (Microsoft.Speech).

UPS Consonant Labeling Conventions

Consonant symbols are one, two, or three characters in length. Single character labels are used for highly frequent, language-universal consonants. In general the first character signifies place plus voicing, and the second signifies manner. Labeling conventions carry across phonetic classes in the following ways:

Conventions for place of articulation and voicing labeling:

  • Dentals and alveloars use D for voiced and T for voiceless

  • Alveolars use N for nasal and R for approximant

  • Labiodentals use V for voiced and F for voiceless

  • Velars use G for voiced and K for voiceless, NG for nasal

  • Bilabials use B for voiced and P for voiceless stops, M for nasal

  • Laterals use L

  • Uvulars use Q

  • Pharyngeals use H

  • Palatals use X for voiceless and Y for voiced

Conventions for manner of articulation labeling:

  • Single-character labels have manner encapsulated in choice of symbol: for example, M is nasal

  • Trills double up the first symbol

  • Fricatives use H

  • Approximants use X

  • Retroflex uses R

Consonant Tables

There are two tables, each listing a different category of consonant phones:

  • Consonants

  • Affricates

The table columns contain the following information:

  • UPS. The phone label specified in Microsoft's Universal Phone Set (UPS).

  • IPA. The phone label specified in the International Phonetic Alphabet (IPA) phone set.

  • Unicode. The Unicode value from the IPA phone set.

  • SAPI ID. The Speech API (SAPI) phone ID, which in most cases is the Unicode value.

  • IPA Description. This column describes the features of the phone, such as place of articulation, manner of articulation, phonation type, and airstream mechanism. See the Glossary of Phonetic Terms (Microsoft.Speech) for more information about the features of phones.

  • ipaASCII. The equivalent phone in ipaASCII phone set for reference.

  • X-SAMPA. The equivalent phone in X-SAMPA for reference.

  • Example. A word that uses the phone and illustrates its sound.

  • Language. The language of the example word.

Consonant Phones

Consonants are speech sounds that are articulated with complete (voiceless) or partial closure of the vocal tract.

UPS | IPA | Unicode | SAPI ID | IPA Description | ipaASCII | X-SAMPA | Example | Language
P | p | U+0070 | 0070 | {blb,stp,vls} | P | P | put | English
B | b | U+0062 | 0062 | {blb,stp,vcd} | B | B | big | English
M | m | U+006D | 006D | {blb,nas} | M | M | mat | English
BB | ʙ | U+0299 | 0299 | {blb,trl,vcd} | B<trl> | B\ |  |
PH | ɸ | U+0278 | 0278 | {blb,frc,vls} | P | p\ |  |
BH | β | U+03B2 | 03B2 | {blb,frc,vcd} | B | B | kabra | Spanish
MF | ɱ | U+0271 | 0271 | {lbd,nas} | M | F |  |
F | f | U+0066 | 0066 | {lbd,frc,vls} | F | F | fork | English
V | v | U+0076 | 0076 | {lbd,frc,vcd} | V | V | vat | English
VA | ʋ | U+028B | 028B | {lbd,apr,vcd} | R<lbd> | V\ |  |
TH | θ | U+03B8 | 03B8 | {dnt,frc,vls} | T | T | thin | English
DH | ð | U+00F0 | 00F0 | {dnt,frc,vcd} | D | D | then | English
T | t | U+0074 | 0074 | {alv,stp,vls} | T | T | talk | English
D | d | U+0064 | 0064 | {alv,stp,vcd} | D | D | dig | English
N | n | U+006E | 006E | {alv,nas} | N | N | no | English
RR | r | U+0072 | 0072 | {alv,trl,vcd} | R<trl> |  | torre, rojo | Spanish
DX | ɾ | U+027E | 027E | {alv,flp,vcd} | * | 4 | butter | US English
S | s | U+0073 | 0073 | {alv,frc,vls} | S | S | sit | US English
Z | z | U+007A | 007A | {alv,frc,vcd} | z | Z | zap | US English
LSH | ɬ | U+026C | 026C | {alv,lat,frc,vls} |  | K |  |
LH | ɮ | U+026E | 026E | {alv,lat,frc,vcd} | z<lat> | K\ | caballo | Spanish/Zulu
RA | ɹ | U+0279 | 0279 | {alv,apr} | r | r\ | puro | Spanish
L | l | U+006C | 006C | {alv,lat,apr,vcd} | l | L | lid | US English
L vel | ɫ | U+026B | 006C 02E0 | {alv,lat,apr,vcd} vel |  |  |  |
SH | ʃ | U+0283 | 0283 | {pla,frc,vls} | S | S | she | US English
SH pal | ʆ | U+0286 | 0283 02B2 | {pla,frc,vls} pal |  |  |  |
ZH | ʒ | U+0292 | 0292 | {pla,frc,vcd} | Z | Z | pleasure | US English
ZH pal | ʓ | U+0293 | 0292 02B2 | {pla,frc,vcd} pal |  |  |  |
TR | ʈ | U+0288 | 0288 | {rfx,stp,vls} | t. | t` |  |
DR | ɖ | U+0256 | 0256 | {rfx,stp,vcd} | d. | D` |  |
NR | ɳ | U+0273 | 0273 | {rfx,nas,vcd} | n. | N` |  |
DXR | ɽ | U+027D | 027D | {rfx,flp,vcd} | *. | r` |  |
SR | ʂ | U+0282 | 0282 | {rfx,frc,vls} | s. | S` |  |
ZR | ʐ | U+0290 | 0290 | {rfx,frc,vcd} | z. | Z` |  |
R | ɻ | U+027B | 027B | {rfx,apr,vcd} | r. | R | red | US English
LR | ɭ | U+026D | 026D | {rfx,lat,vcd} | l. | l` |  |
RR rho | ɼ | U+027C | 0072 02DE | {rfx,trl} |  |  |  |
CT | c | U+0063 | 0063 | {pal,stp,vls} | c | C |  |
JD | ɟ | U+025F | 025F | {pal,stp,vcd} | J | J\ |  |
NJ | ɲ | U+0272 | 0272 | {pal,nas,vcd} |  | J | oignon | French
C | ç | U+00E7 | 00E7 | {pal,frc,vls} | C | C | sicher | German
CJ | ʝ | U+029D | 029D | {pal,frc,vcd} | C<vcd> | j\ |  |
J | j | U+006A | 006A | {pal,apr,vcd} | j | J | yard | US English
LJ | ʎ | U+028E | 028E | {pal,lat,apr,vcd} | l^ | L | gli | Italian
W | w | U+0077 | 0077 | {lbv,apr,vcd} | w | W | with | US English
K | k | U+006B | 006B | {vel,stp,vls} | k | K | cut | US English
G | g | U+0067 | 0067 | {vel,stp,vcd} | g | G | gut | US English
NG | ŋ | U+014B | 014B | {vel,nas} | N | N | sing | US English
X | x | U+0078 | 0078 | {vel,frc,vls} | x | X | mujer | Spanish
GH | ɣ | U+0263 | 0263 | {vel,frc,vcd} | Q | 7 | luego | Spanish
GA | ɰ | U+0270 | 0270 | {vel,apr,vcd} | j<vel> | M\ |  |
GL | ʟ | U+029F | 029F | {vel,lat,vcd} | L | L\ |  |
QT | q | U+0071 | 0071 | {uvl,stp,vls} | q | Q |  |
QD | ɢ | U+0262 | 0262 | {uvl,stp,vcd} | G | G\ |  |
QN | ɴ | U+0274 | 0274 | {uvl,nas,vcd} | n" | N\ |  |
QQ | ʀ | U+0280 | 0280 | {uvl,trl,vcd} | - | R\ |  |
QH | χ | U+03C7 | 03C7 | {uvl,frc,vls} | X | X |  |
RH | ʁ | U+0281 | 0281 | {uvl,frc,vcd} | g" | R | rond | French
HH | ħ | U+0127 | 0127 | {phr,frc,vls} | H | X\ |  |
HG | ʕ | U+0295 | 0295 | {phr,frc,vcd} | H<vcd> | ?\ |  |
GT | ʔ | U+0294 | 0294 | {glt,stp,vls} | ? | ? |  |
H | h | U+0068 | 0068 | {glt,frc,vls} | h | H | help | US English
WJ | ɥ | U+0265 | 0265 | {lbp,apr,vcd} | j<rnd> | H | huit;juin | French

Affricates

Affricates are consonants that begin as stops but release as a fricative.

The SAPI UPS includes explicit phones for the most frequent affricates in the highest priority languages. The IPA Unicode specification includes some of these phones, though not all of them. The SAPI phone IDs for affricates do not use the IPA Unicode values but instead concatenate the phone IDs of the component phones. Each SAPI phone ID is four characters long. For example JH 006A0361006A is equivalent to D + ZH 006A 0361 006A.

This approach maintains the semantic equivalence of compounds and their constituents. It has been used to generate the phone IDs of all compound phones in the UPS. This allows a speech recognition engine to easily decompose the compound phone into its constituent phones, which may be required if the engine does not model one of these compounds. The table shows the constituent phones (UPS Compound) that were combined to create the resulting explicit phone (UPS).

UPS | UPS Compound | IPA | Unicode | SAPI ID | IPA Description | Example | Language
PF | P + F | p.f |  | 007003610066 | {lbd,aff,vls} | Pfahl | German
TS | T + S | t.s / ʦ | U+02A6 | 007403610073 | {den,aff,vls} | Zahl | German
CH | T + SH | t.ʃ / ʧ | U+02A7 | 007403610283 | {pla,aff,vls} | chin | English
JH | D + ZH | d.ʒ / ʤ | U+02A4 | 006403610292 | {pla,aff,vcd} | joy | English
JJ | J + J | j.j |  | 006A0361006A | {pal,aff,vcd} | hielo | Spanish
DZ | D + Z | d.z / ʣ | U+02A3 | 00640361007A | {den,aff,vcd} | zona | Italian
CC | T + SC | t.ɕ / ʨ | U+02A8 | 007403610255 | {pla,aff,vls} |  | Mandarin
TSR | T + SR | t.ʂ |  | 007403610282 | {rfx,aff,vls} |  | Mandarin
JC | D + ZC | d.ʑ / ʥ | U+02A5 | 006403610291 | {pla,aff,vcd} |  |

Many other affricates or compound consonants exist and may be required by other languages. For example, there are about 20 Italian geminate consonants (doubled consonants). UPS does not include dedicated phones for these, but allows them to be defined using the + symbol, or the length diacritic 'lng' in the case of geminates. For more details, see Parsing Guidelines for SAPI Speech Recognition Phone Converters (Microsoft.Speech).

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Vowels (Microsoft.Speech)

[image]

Vowels (Microsoft.Speech)
Send Feedback

This is a listing and cross reference of the vowel phones that are used by the three phonetic alphabets that Microsoft.Speech supports. See Phonetic Alphabet Reference (Microsoft.Speech).

UPS Labeling Conventions for Vowels

The UPS labeling conventions for vowels were designed to make the phones more intuitive and maintain phonetic similarity across each class. The labels follow these conventions:

  • Cardinal or main vowels use single character labels

  • Non-cardinal vowels and common diphthongs use two characters

  • Maximum label length is three characters

  • Centralized vowel labels use X, as in AX, IX, UX

  • Checked vowel (usually must be followed by a consonant in a stressed syllable) labels use H, as in IH, UH

  • U or O signifies lip rounding, as in AU, AO, EU

The vowel chart below is based on the 1993 IPA vowel chart and displays each IPA vowel followed by its UPS equivalent. The cardinal vowels are marked in red, the checked vowels in blue, and the centralized vowels down the middle in green.

Figure 1. Correspondence Between IPA and UPS Vowels

Vowel Tables

There are four tables, each listing a different category of vowel phones:

  • Monophthong

  • Diphthong

  • German Diphthong

  • Nasal

The table columns contain the following information:

  • UPS. The phone label specified in Microsoft's Universal Phone Set (UPS).

  • IPA. The phone label specified in the International Phonetic Alphabet (IPA) phone set.

  • Unicode. The Unicode value from the IPA phone set.

  • SAPI ID. The Speech API (SAPI) phone ID, which in most cases is the Unicode value.

  • IPA Description. This column describes the features of the phone, such as place of articulation, manner of articulation, phonation type, and airstream mechanism. See the Glossary of Phonetic Terms (Microsoft.Speech) for more information about the features of phones.

  • ipaASCII. The equivalent phone in ipaASCII phone set for reference.

  • X-SAMPA. The equivalent phone in X-SAMPA for reference.

  • Example. A word that uses the phone and illustrates its sound.

  • Language. The language of the example word.

Monophthong Vowel Phones

Monophthong (literally "one sound" or "one tone") vowels are those whose articulation at both beginning and end is relatively fixed, and which does not glide up or down towards a new position of articulation.

UPS | IPA | Unicode | SAPI ID | IPA Description | IpaASCII | X-SAMPA | Example | Language
I | i | U+0069 | 0069 | {hgh,fnt,unr,vwl} | I | i | feel | English
Y | y | U+0079 | 0079 | {hgh,fnt,rnd,vwl} | Y | y | du | French
IX | ɨ | U+0268 | 0268 | {hgh,cnt,unr,vwl} | i" | 1 |  |
YX | ʉ | U+0289 | 0289 | {hgh,cnt,rnd,vwl} | U" | } |  |
UU | ɯ | U+026F | 026F | {hgh,bck,unr,vwl} | u- | M |  |
U | u | U+0075 | 0075 | {hgh,bck,rnd,vwl} | u | u | too | English
IH | ɪ | U+026A | 026A | {smh,fnt,unr,vwl} | I | I | fill | English
YH | ʏ | U+028F | 028F | {smh,fnt,rnd,vwl} | I. | Y | hübsch | German
UH | ʊ | U+028ª | 028ª | {smh,bck,rnd,vwl} | U | U | book | English
E | e | U+0065 | 0065 | {umd,fnt,urd,vwl} | e | e | ses | French
EU | ø | U+00F8 | 00F8 | {umd,fnt,rnd,vwl} | Y | 2 | blöd | German
EX | ɘ | U+0258 | 0258 | {umd,cnt,urd,vwl} | @<umd> | @\ |  |
OX | ɵ | U+0275 | 0275 | {umd,cnt,rnd,vwl} |  | 8 |  |
OU | ɤ | U+0264 | 0264 | {umd,bck,urd,vwl} | o- | 7 |  |
O | o | U+006F | 006F | {umd,bck,rnd,vwl} | o | o | go | English
AX | ə | U+0259 | 0259 | {mid,cnt,unr,vwl} | @ | @ | ago | English
AX rho | ɚ | U+025ª | 0259 02DE | {mid,cnt,rho,vwl} | R |  | forensic | English
EH | ɛ | U+025B | 025B | {lmd,fnt,unr,vwl} | E | E | pet | English
OE | œ | U+0153 | 0153 | {lmd,fnt,rnd,vwl} | W | 9 | plötzlich | German
ER | ɜ | U+025C | 025C | {lmd,cnt,unr,vwl} | V" | 3 | bird | UK English
ER rho | ɝ | U+025D | 025C 02DE | {lmd,cnt,unr,rho,vwl} | @. |  | bird | US English
UR | ɞ | U+025E | 025E | {lmd,cnt,rnd,vwl} | O" | 3\ |  |
AH | ʌ | U+028C | 028C | {lmd,bck,unr,vwl} | V | V | cut | English
AO | ɔ | U+0254 | 0254 | {lmd,bck,rnd,vwl} | O | O | dog | English
AE | æ | U+00E6 | 00E6 | {sml,fnt,unr,vwl} | & | { | cat | English
AEX | ɐ | U+0250 | 0250 | {sml,cnt,unr,vwl} |  | 6 | Besser | German
A | a | U+0061 | 0061 | {low,fnt,unr,vwl} | a | a | valle | Spanish
AOE | ɶ | U+0276 | 0276 | {low,fnt,rnd,vwl} | &. | & |  |
AA | ɑ | U+0251 | 0251 | {low,bck,unr,vwl} | A | A | father | English
Q | ɒ | U+0252 | 0252 | {low,bck,rnd,vwl} | A. | Q | hot | English

Diphthong Vowel Phones

In addition to monophthongs, many languages contain diphthongs or even triphthongs. Diphthong (literally "two sounds" or "two tones") vowels are those that change quality during their pronunciation, or "glide", with a smooth movement of the tongue from one articulation to another, as in the English words eye, boy, and cow.

Diphthongs and triphthongs can be represented in UPS as vowel compounds, using the + symbol. However to make lexicons more readable, UPS also contains phones for common diphthongs. The table below shows both the compounding of two phones using the + symbol and the resultant UPS phone.

UPS Compound | UPS | IPA | SAPI ID | X-SAMPA | Example | Language | Example | Language
E + I | EI | e.ɪ | 006503610069 | eI | late | English | late | English
A + UH | AU | ɑ.ʊ | 00610361028A | aU | foul | English | Haus | German
AO + I | OI | ɔ.ɪ | 025403610069 | OI | toy | English | Kreuz | German
A + I | AI | ɑ.ɪ | 006103610069 | ai | bite | English | Eis | German
I + AX | IYX | i.ə | 006903610259 | i:6 | Tier | German | fear | English
Y + AX | UYX | y.ə | 007903610259 | y:6 | Tür | German |  |
EH + AX | EHX | ɛ.ə | 025B03610259 | E6 | Berg | German | stairs | English
U + AX | UWX | u.ə | 007503610259 | u:6 | Kur | German | lure | English
O + AX | OWX | o.ə | 006F03610259 | o:6 | Ohr | German | boa | English
AO + AX | AOX | ɔ.ə | 025403610259 | O6 | dort | German | four | English

German Diphthong Vowels

The German language has several more centering diphthongs that must be represented as phone compounds and do not have explicit UPS phones assigned to them. The 'lng' diacritic is included for phonetic completeness.

UPS Compound | IPA | X-SAMPA | Example | Language
IH + AX | ɪ.ə | I6 | Wirt | German
YH + AX | ʏ.ə | Y6 | Türke | German
EY lng + AX | e.ə | e:6 | schwer | German
EH lng + AX | ɛ:.ə | E:6 | Bär | German
EU lng + AX | ø.ə | 2:6 | Föhr | German
OE + AX | œ.ə | 96 | Wörter | German
A lng + AX | a.ə | a:6 | Haar | German
A + AX | a.ə | a6 | hart | German
UH + AX | ʊ.ə | U6 | kurz | German

Nasal Vowel Phones

UPS contains phones for four nasal vowels. These are shown in the following table with French examples. The SAPI phone ID for these phones is formed from the phone IDs of the primary vowel and the nasality diacritic. The UPS phone is therefore equivalent to the compound shown in the first column.

Compound | UPS | SAPI ID | X-SAMPA | Example | Language
E nas | EN | 00650303 | e~ | vin | French
A nas | AN | 00610303 | a~ | vent | French
O nas | ON | 006F0303 | o~ | bon | French
OE nas | OEN | 01530303 | 9~ | brun | French
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Diacritics (Microsoft.Speech)

[image]

Diacritics (Microsoft.Speech)
Send Feedback

This is a listing and cross reference of the diacritic phones that are used by the three phonetic alphabets that Microsoft.Speech supports. See Phonetic Alphabet Reference (Microsoft.Speech).

The table columns contain the following information:

  • UPS. The phone label specified in Microsoft's Universal Phone Set (UPS).

  • IPA. The phone label specified in the International Phonetic Alphabet (IPA) phone set.

  • Unicode. The Unicode value from the IPA phone set.

  • SAPI ID. The Speech API (SAPI) phone ID, which in most cases is the Unicode value.

  • IPA Description. This column describes the features of the phone, such as place of articulation, manner of articulation, phonation type, and airstream mechanism. See the Glossary of Phonetic Terms (Microsoft.Speech) for more information about the features of phones.

  • ipaASCII. The equivalent phone in ipaASCII phone set for reference.

  • X-SAMPA. The equivalent phone in X-SAMPA for reference.

Diacritic Phones

Diacritics are used to modify segmental phones (vowels, consonants, clicks, and ejectives) with additional phonetic detail. A diacritic cannot stand-alone. Diacritics must modify the preceding segmental phone. Any number of diacritics can follow a segmental symbol.

UPS | IPA | Unicode | SAPI ID | IPA Description | IPA-ASCII | X-SAMPA
+ | U+0361 | 0361 | tie bar |  |  |
adv | o̟ | U+031F | 031F | Advanced |  | _+
api | t̺ | U+033A | 033A | Apical |  | _a
asp | tʰ | U+02B0 | 02B0 | Aspirated | <h> {asp} | _h
atr | e̘ | U+0318 | 0318 | Advanced tongue root |  | _A
bvd | b̤ | U+0324 | 0324 | Breathy voiced |  | _t
cen | ë | U+0308 | 0308 | Centralized |  | _"
cvd | b̰ | U+0330 | 0330 | Creaky voiced |  | _k
den | t̪ | U+032A | 032A | Dental | [ / {dnt} | _d
ejc | pʼ | U+02BC | 02BC | Ejective | {ejc} | _>
lab | tʷ | U+02B7 | 02B7 | Labialised | <w> {lzd} | _w
lam | t̻ | U+033B | 033B | Laminal |  | _m
lar | dˡ | U+02E1 | 02E1 | Lateral release |  | _l
lla | n̼ | U+033C | 033C | Linguolabial |  | _N
low | e̞ | U+031E | 031E | Lowered |  | _o
lrd | o̜ | U+031C | 031C | Less rounded |  | _c
mcn | e̽ | U+033D | 033D | Mid-centralized |  |
mrd | o̹ | U+0339 | 0339 | More rounded |  | _O
nar | d̚ | U+031A | 031A | No audible release |  | _}
nas | ñ | U+0303 | 0303 | Nasalized | ~ / <nzd> | ~ / _~
nsr | oⁿ | U+207F | 207F | Nasal release |  | _n
nsy | n̯ | U+032F | 032F | Non-syllabic |  | _^
pal | tʲ | U+02B2 | 02B2 | Palatalized | ; / {pzd} | '
phr | nˤ | U+02E4 | 02E4 | Pharyngealized |  | _?\
rai | e̝ | U+031D | 031D | Raised |  | _r
ret | o̱ | U+0331 | 0331 | Retracted |  | _-
rho | ə˞ | U+02DE | 02DE | Rhoticity |  | `
rtr | e̙ | U+0319 | 0319 | Retracted tongue root |  | _q
rtr | e̙ | U+0319 | 0319 | Retracted tongue root |  | _q
syl | n̩ | U+0329 | 0329 | Syllabic | {syl} | = / _=
vcd | s̬ | U+032C | 032C | Voiced |  | _v
vel | tˠ | U+02E0 | 02E0 | Velarized | {vzd} | _G
vls | n̊ | U+030A | 030A | Voiceless |  | _0
vph | l̴ | U+0334 | 0334 | Velarized or pharyngealized | {fzd} | _e
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Suprasegmentals (Microsoft.Speech)

[image]

Suprasegmentals (Microsoft.Speech)
Send Feedback

This is a listing and cross reference of the suprasegmental phones that are used by the three phonetic alphabets that Microsoft.Speech supports. See Phonetic Alphabet Reference (Microsoft.Speech).

The table columns contain the following information:

  • UPS. The phone label specified in Microsoft's Universal Phone Set (UPS).

  • IPA. The phone label specified in the International Phonetic Alphabet (IPA) phone set.

  • Unicode. The Unicode value from the IPA phone set.

  • SAPI ID. The Speech API (SAPI) phone ID, which in most cases is the Unicode value.

  • IPA Description. This column describes the features of the phone. See the Glossary of Phonetic Terms (Microsoft.Speech) for more information about the features of phones.

  • X-SAMPA. The equivalent phone in X-SAMPA for reference.

  • SAPI Equivalent. The equivalent SAPI label, if applicable.

Suprasegmental Phones

Suprasegmentals describe the features of a language above the level of individual consonants and vowels, such as prosody, tone, length, and stress.

The first set of suprasegmental symbols, up to and including "linking", map directly to the IPA suprasegmental set and therefore have the IPA Unicode value as the SAPI phone ID. This set includes length diacritics for long, half-long, and extra-short. Length is often used phonemically, so length markers could also belong in the diacritics table. For this reason they are given the lower case label format of a diacritic.

The remaining suprasegmental symbols are used in UPS to describe intonation contours in text-to-speech markup (SSML prompt documents). These UPS symbols were formed by prefixing the original SAPI labels with an underscore. This makes them more easily identifiable as a class and removes any ambiguity with other IPA symbols. For example the old SAPI symbol '!' sentence terminator is the IPA symbol for an alveolar click.

UPS | IPA | Unicode | SAPI ID | IPA Description | X-SAMPA | SAPI Equivalent
S1 | ˈ | U+02C8 | 02C8 | Primary stress | " | 1
S2 | ˌ | U+02CC | 02CC | Secondary stress | % | 2
. | . | U+002E | 002E | Syllable break |  |
_| | | | U+007C | 007C | Minor (foot) group |  |
_|| | ‖ | U+2016 | 2016 | Major (intonation) group |  |
lng | ː | U+02D0 | 02D0 | Long | : |
hlg | ˑ | U+02D1 | 02D1 | Half-long | :\ |
xsh | ˘ | U+02D8 | 02D8 | Extra-short | _X |
_^ | U+203F | 203F | linking (absence of a break) | -\ |  |
_! |  |  | 0001 | Intonation - exclamation |  | ! Sentence terminator (exclamation mark)
_& |  |  | 0002 | Intonation - continue |  | & Word boundary
_, |  |  | 0003 | intonation - incompletion rise |  | , Sentence terminator (comma)
_s |  |  | 0004 | Silence |  | _ Silence (underscore)
_. |  | U+2198 | 2198 | Intonation - fall |  | . Sentence terminator (period)
_? |  | U+2197 | 2197 | Intonation - question rise |  | ? Sentence terminator (question mark)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Clicks and Ejectives (Microsoft.Speech)

[image]

Clicks and Ejectives (Microsoft.Speech)
Send Feedback

This is a listing and cross reference of the click and ejective phones that are used by the three phonetic alphabets that Microsoft.Speech supports. See Phonetic Alphabet Reference (Microsoft.Speech).

The table columns contain the following information:

  • UPS. The phone label specified in Microsoft's Universal Phone Set (UPS).

  • IPA. The phone label specified in the International Phonetic Alphabet (IPA) phone set.

  • Unicode. The Unicode value from the IPA phone set.

  • SAPI ID. The Speech API (SAPI) phone ID, which in most cases is the Unicode value.

  • IPA Description. This column describes the features of the phone, such as place of articulation, manner of articulation, phonation type, and airstream mechanism. See the Glossary of Phonetic Terms (Microsoft.Speech) for more information about the features of phones.

  • X-SAMPA. The equivalent phone in X-SAMPA for reference.

Click and Ejective Phones

IPA uses a diacritic to describe ejectives, but has specific phones for clicks and implosives. Even though this seems a little inconsistent, the UPS follows IPA directly here in order to maintain consistency between SAPI phone Ids and the IPA Unicode values.

Clicks and ejectives are voiceless consonants, although implosives may be partially voiced.

UPS | IPA | Unicode | SAPI ID | IPA Description | X-SAMPA
PCK | ʘ | U+0298 | 0298 | blb,clk | O\
TCK | ǀ | U+01C0 | 01C0 | dnt,clk | |\
NCK | ! | U+0021 | 0021 | alv,clk | !\
CCK | ǂ | U+01C2 | 01C2 | pla,clk | =\
LCK | ǁ | U+01C1 | 01C1 | alv,lat,clk | |\|\
BIM | ɓ | U+0253 | 0253 | blb,imp,vcd | b_<
DIM | ɗ | U+0257 | 0257 | dnt-alv,imp,vcd | d_<
QIM | ʛ | U+029B | 029B | uvl,imp,vcd |
QIM vls | ʠ | U+02A0 | 029B 030A | uvl,imp,vls |
GIM | ɠ | U+0260 | 0260 | vel,imp,vcd | g_<
JIM | ʄ | U+0284 | 0284 | pal,imp,vcd |
P ejc | pʼ | 0070 02BC | 0070 02BC | blb,ej | b_>
T ejc | tʼ | 0074 02BC | 0074 02BC | dnt-alv, ej | t_>
K ejc | kʼ | 006B 02BC | 006B 02BC | vel ej | g_>
S ejc | sʼ | 0073 02BC | 0073 02BC | alv fric ej | s_>
QT ejc | qʼ | 0071 02BC | 0071 02BC | uvl,ej |
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Tones (Microsoft.Speech)

[image]

Tones (Microsoft.Speech)
Send Feedback

This is a listing and cross reference of the tone phones that are used by the three phonetic alphabets that Microsoft.Speech supports. See Phonetic Alphabet Reference (Microsoft.Speech).

The table columns contain the following information:

  • UPS. The phone label specified in Microsoft's Universal Phone Set (UPS).

  • IPA. The phone label specified in the International Phonetic Alphabet (IPA) phone set.

  • Unicode. The Unicode value from the IPA phone set.

  • SAPI ID. The Speech API (SAPI) phone ID, which in most cases is the Unicode value.

  • IPA Description. This column describes the features of the phone. See the Glossary of Phonetic Terms (Microsoft.Speech) for more information about the features of phones.

  • X-SAMPA. The equivalent phone in X-SAMPA for reference.

Tone Phones

Tone describes the use of pitch in speech sounds to distinguish lexical or grammatical meaning. Lexical tones can follow a vowel or syllabic consonant. They can be made up of simple levels, on a universal scale which has a maximum of five level contrasts, or they can be contours composed of sequences of tones. A sequence of three tones should be sufficient to describe any tone contour.

IPA contains a mixture of lexical tones and contour tones. UPS covers the five lexical tones found in IPA, plus upstep and downstep. All contour tones can be represented in UPS by compound tones.

UPS does not include tonal symbols for the following IPA symbols: Rising, Falling, High Rising, Low Rising and Rising-Falling. These can all be defined in UPS using tone sequences. Global Rise and Global Fall are equivalent to "intonation - fall" and "intonation - question rise" in UPS and are found in Suprasegmentals (Microsoft.Speech).

UPS | IPA | Unicode | SAPI ID | IPA Description | X-SAMPA
T5 | e̋ | U+030B | 030B | Extra high Level | _T
T4 | é | U+0301 | 0301 | High Level | _H
T3 | ē | U+0304 | 0304 | Mid Level | _M
T2 | è | U+0300 | 0300 | Low Level | _L
T1 | ȅ | U+030F | 030F | Extra Low Level | _B
T- | ↓ | U+2193 | 2193 | Downstep | !
T+ | ↑ | U+2191 | 2191 | Upstep | ^
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Other Phones (Microsoft.Speech)

[image]

Other Phones (Microsoft.Speech)
Send Feedback

This is a listing and cross reference of the uncommon phones that are not listed in the other phone tables, but are used by the three phonetic alphabets that Microsoft.Speech supports. See Phonetic Alphabet Reference (Microsoft.Speech).

The table columns contain the following information:

  • UPS. The phone label specified in Microsoft's Universal Phone Set (UPS).

  • IPA. The phone label specified in the International Phonetic Alphabet (IPA) phone set.

  • Unicode. The Unicode value from the IPA phone set.

  • SAPI ID. The Speech API (SAPI) phone ID, which in most cases is the Unicode value.

  • IPA Description. This column describes the features of the phone, such as place of articulation, manner of articulation, phonation type, and airstream mechanism. See the Glossary of Phonetic Terms (Microsoft.Speech) for more information about the features of phones.

  • ipaASCII. The equivalent phone in ipaASCII phone set for reference.

  • X-SAMPA. The equivalent phone in X-SAMPA for reference.

Other Phones

UPS | IPA | Unicode | SAPI Id | IPA Description | IPA-ASCII | X-SAMPA
WH | ʍ | U+028D | 028D | lbv,frc,vls | w<vls> | W
ESH | ʜ | U+029C | 029C | epl,frc,vls |  | H\
EZH | ʢ | U+02A2 | 02A2 | epl,frc,vcd |  | <\
ET | ʡ | U+02A1 | 02A1 | epl,stp |  | >\
SC | ɕ | U+0255 | 0255 | pla,frc,vls |  | s\
ZC | ʑ | U+0291 | 0291 | pla,frc,vcd |  | z\
LT | ɺ | U+027A | 027A | alv,lat,flp | *<lat> | l\
SHX | ɧ | U+0267 | 0267 | simultaneous SH and X |  | x\
HZ | ɦ | U+0266 | 0266 | glt,frc,vcd |  | h\
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Universal Phone Set (UPS) (Microsoft.Speech)

[image]

Universal Phone Set (UPS) (Microsoft.Speech)
Send Feedback

The Speech API (SAPI) Universal Phone Set (UPS) is a machine-readable phone set that is based on the International Phonetic Alphabet (IPA).

UPS Design Principles

The following design principles were used to select SAPI labels and phone IDs for UPS.

  1. UPS covers the IPA 1993 Unicode character set, plus some extra SAPI phones including some suprasegmental labels that are used in speech synthesis markup but are not found in IPA.

    • In most cases there is a one-to-one mapping between UPS and IPA. In these cases, the SAPI Phone ID can simply use the IPA hex Unicode value.

    • In some cases UPS is a superset of IPA. For example, UPS includes some unique phone labels for commonly used sounds such as diphthongs and nasalized vowels, which the IPA treats as compounds. These compounds are represented using the compounding symbol "+". This symbol is treated just like any other phone, and so must be space delimited in a lexicon: the compound of A and B is written A + B, not AB or A+B. The SAPI Phone IDs of such compounds are formed from the sequence of phone IDs making up the compound.

  2. UPS pronunciations consist of a string of UPS phones, each separated by whitespace. SAPI makes no distinction between segmental phones and diacritics, suprasegmentals, and tones, and so these must also be separated by whitespace like any other SAPI phone.

  3. The UPS phone labels are not restricted to use the SAPI phone labels from US English, Spanish, French, German, Japanese, or Chinese; however, where possible, existing SAPI labels were re-used. Two sets of guidelines were used in creating the phone label names:

    • The UPS phone set reflects orthography where possible but is not biased too heavily towards English.

    • Phone labels adhere to labeling conventions that apply across phonetic classes (e.g., lax vowels use the character 'H' as in 'IH', 'UH' and 'AH')

  4. The UPS phone set is case-sensitive. UPS phone labels are all defined using ASCII character strings.

    • Segmental phones (Consonants (Microsoft.Speech), Vowels (Microsoft.Speech), Clicks and Ejectives (Microsoft.Speech)) are represented by upper-case alphabetic symbols. These may vary in length from one to three characters. In general, shorter symbols are used for more frequent phones.

    • Diacritics (Microsoft.Speech) are represented by three-character, lower-case, alphabetic symbols.

    • Suprasegmentals (Microsoft.Speech) and Tones (Microsoft.Speech) may vary in length and contain non-alphabetic characters.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Language Coverage (Microsoft.Speech)

[image]

Language Coverage (Microsoft.Speech)
Send Feedback

The Speech API (SAPI) Phone Converters specify the languages they support in a list of Language Identifiers. You can find this list in the registry key for PhoneConverters by inspecting its Language attribute, at the following location:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\PhoneConverters\Tokens\Universal\Attributes\Language

The Language Identifiers consist of a Locale Identifier that represents the combination of a Primary Language Identifier and a Sublanguage Language Identifier. For a full list of languages and their identifiers, see Language Identifier Constants and Strings on MSDN.

The Universal Phone Set should be used for all Microsoft-supported languages except the seven languages currently supported by SAPI, shown in the following table:

Language-Culture Code | Language Name | Language ID
zh-TW | Chinese (Taiwan) | 404
zh-CN | Chinese (PRC) | 804
en-US | English (United States) | 409
fr-FR | French (Standard) | 40c
de-DE | German (Standard) | 407
jp-JP | Japanese | 411
es-ES | Spanish (Spain, Traditional Sort) | 40a

The following table lists all the currently supported languages and their language identifiers.

LangID | Language | LangID | Language
436 | Afrikaans | 430 | Sutu
41c | Albanian | 441 | Swahili (Kenya)
401 | Arabic (Saudi Arabia) | 41d | Swedish
801 | Arabic (Iraq) | 81d | Swedish (Finland)
c01 | Arabic (Egypt) | 45a | Windows XP: Syriac. (Unicode only)
1001 | Arabic (Libya) | 449 | Windows 2000/XP: Tamil. (Unicode only)
1401 | Arabic (Algeria) | 2409 | English (Caribbean)
1801 | Arabic (Morocco) | 2809 | English (Belize)
1c01 | Arabic (Tunisia) | 2c09 | English (Trinidad)
2001 | Arabic (Oman) | 3009 | Windows 98/Me, Windows 2000/XP: English (Zimbabwe)
2401 | Arabic (Yemen) | 3409 | Windows 98/Me, Windows 2000/XP: English (Philippines)
2801 | Arabic (Syria) | 425 | Estonian
2c01 | Arabic (Jordan) | 438 | Faeroese
3001 | Arabic (Lebanon) | 429 | Farsi
3401 | Arabic (Kuwait) | 40b | Finnish
3801 | Arabic (U.A.E.) | 80c | French (Belgian)
3c01 | Arabic (Bahrain) | c0c | French (Canadian)
4001 | Arabic (Qatar) | 100c | French (Switzerland)
42b | Windows 2000/XP: Armenian. (Unicode only) | 140c | French (Luxembourg)
42c | Azeri (Latin) | 180c | Windows 98/Me, Windows 2000/XP: French (Monaco)
82c | Azeri (Cyrillic) | 456 | Windows XP: Galician
42d | Basque | 437 | Windows 2000/XP: Georgian. (Unicode only)
423 | Belarusian | 807 | German (Switzerland)
402 | Bulgarian | c07 | German (Austria)
455 | Burmese | 1007 | German (Luxembourg)
403 | Catalan | 1407 | German (Liechtenstein)
c04 | Chinese (Hong Kong SAR, PRC) | 408 | Greek
1004 | Chinese (Singapore) | 447 | Windows XP: Gujarati. (Unicode only)
1404 | Windows 98/Me, Windows 2000/XP: Chinese (Macau SAR) | 40d | Hebrew
41a | Croatian | 439 | Windows 2000/XP: Hindi. (Unicode only)
405 | Czech | 40e | Hungarian
406 | Danish | 40f | Icelandic
465 | Windows XP: Divehi. (Unicode only) | 421 | Indonesian
413 | Dutch (Netherlands) | 410 | Italian (Standard)
813 | Dutch (Belgium) | 810 | Italian (Switzerland)
809 | English (United Kingdom) | 44b | Windows XP: Kannada. (Unicode only)
c09 | English (Australian) | 457 | Windows 2000/XP: Konkani. (Unicode only)
1009 | English (Canadian) | 412 | Korean
1409 | English (New Zealand) | 812 | Windows 95, Windows NT 4.0 only: Korean (Johab)
1809 | English (Ireland) | 440 | Windows XP: Kyrgyz.
1c09 | English (South Africa) | 426 | Latvian
2009 | English (Jamaica) | 427 | Lithuanian
418 | Romanian | 827 | Windows 98 only: Lithuanian (Classic)
419 | Russian | 42f | FYRO Macedonian
44f | Windows 2000/XP: Sanskrit. (Unicode only) | 43e | Malay (Malaysian)
c1a | Serbian (Cyrillic) | 83e | Malay (Brunei Darussalam)
81a | Serbian (Latin) | 44e | Windows 2000/XP: Marathi. (Unicode only)
41b | Slovak | 450 | Windows XP: Mongolian
424 | Slovenian | 414 | Norwegian (Bokmal)
80a | Spanish (Mexican) | 814 | Norwegian (Nynorsk)
c0a | Spanish (Spain, Modern Sort) | 415 | Polish
100a | Spanish (Guatemala) | 416 | Portuguese (Brazil)
140a | Spanish (Costa Rica) | 816 | Portuguese (Portugal)
180a | Spanish (Panama) | 446 | Windows XP: Punjabi. (Unicode only)
1c0a | Spanish (Dominican Republic) | 444 | Tatar (Tatarstan)
200a | Spanish (Venezuela) | 44a | Windows XP: Telugu. (Unicode only)
240a | Spanish (Colombia) | 41e | Thai
280a | Spanish (Peru) | 41f | Turkish
2c0a | Spanish (Argentina) | 422 | Ukrainian
300a | Spanish (Ecuador) | 420 | Windows 98/Me, Windows 2000/XP: Urdu (Pakistan)
340a | Spanish (Chile) | 820 | Urdu (India)
380a | Spanish (Uruguay) | 443 | Uzbek (Latin)
3c0a | Spanish (Paraguay) | 843 | Uzbek (Cyrillic)
400a | Spanish (Bolivia) | 42a | Windows 98/Me, Windows NT 4.0 and later: Vietnamese
440a | Spanish (El Salvador) |  |
480a | Spanish (Honduras) |  |
4c0a | Spanish (Nicaragua) |  |
500a | Spanish (Puerto Rico) |  |

The registry key for PhoneConverters also contains a mapping from the UPS label to the SAPI identifier for supported phones, at this location:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\PhoneConverters\Tokens\Universal\Attributes

See UPS to SAPI Phone Map (Microsoft.Speech).

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compound Tying Symbol (Microsoft.Speech)

[image]

Compound Tying Symbol (Microsoft.Speech)
Send Feedback

UPS provides unique phone labels for common compound sounds such as affricates and nasal vowels. However, less frequent compound sounds may also exist in some languages and need to be represented in SAPI lexicons. The Universal Phone Set provides a compounding or tying symbol "+" that can be used to describe composite sounds from any two phones.

The German affricate "PF", diphthong "AI", and nasal vowel "AN" exist as unique phones in UPS. However, they could also be represented as compounds. The following example shows that "PF" and "P + F" are equivalent and are distinct from the phone sequence "P F".

Unique Phone | Compound
PF | P + F
AI | A + I

The nasal vowel "AN" can be described as the "A" vowel with a nasal diacritic. All diacritics must follow a segmental phone, so "A nas" and "A + nas" are equivalent. The former is preferred, though SAPI does not enforce any particular use of "+" or diacritics.

Unique Phone | Compound
AN | A nas
AN | A + nas

Speech Recognition (SR) engines must interpret compound sounds found in SAPI phone strings and map them to their internal phone set. For example, one SR engine may have an acoustic model "pf". In this case, the SAPI phone string "P + F" or "PF" would be mapped to the SR phone "pf". Another engine may not model "pf", instead modeling only "p" and "f". In this case either SAPI phone string (unique or compound) would be split into its component parts "p" and "f" by the SR engine.

Such mappings are provided by the SR engine's Phone Converter object within the engine's Locale Handler. It is up to the engine developer to write this mapping code and to parse any incoming SAPI phone strings. See Parsing Guidelines for SAPI Speech Recognition Phone Converters (Microsoft.Speech) for more information.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Parsing Guidelines for SAPI Speech Recognition Phone Converters (Microsoft.Speech)

[image]

Parsing Guidelines for SAPI Speech Recognition Phone Converters (Microsoft.Speech)
Send Feedback

SAPI does not enforce any parsing conventions on phone strings, nor does it place any restrictions on the phonetic validity of compounds or the correct usage of diacritics.

Application developers need to be aware of guidelines for writing pronunciations and using UPS phones. In addition, engine developers require some guidelines for parsing UPS phone strings.

The Compound Symbol

The compound phone "+" is a Boolean symbol that requires a left and right context. Any two SAPI symbols can be joined by the compound symbol, including sequences of segmental symbols, Tones (Microsoft.Speech), and Diacritics (Microsoft.Speech).

Any number of segmental symbols can be joined by the "+" symbol. Usually, this will be limited to two in the case of affricates and diphthongs. Some sounds, such as triphthongs or geminates, may require three or more.

The following are all valid phone strings, shown with the parsed meaning:

Phone string | Parsed Phone String
A B C | A B C
A + B | AB
A B + C | A BC
A + B + C | ABC

Parsing Affricates, Diphthongs, and Nasal Vowels

When UPS contains a specific phone for a compound sound such as a nasal vowel or affricate, the SAPI phone ID of the phone provides the information required to split it up into its constituent phones, including the "+" marker.

For example, UPS contains phones for the affricate "PF" and the nasal vowel "AN". If the speech recognition (SR) engine does not model such sounds and would prefer to split them up, it is possible by parsing the SAPI phone ID. Each SAPI phone ID is a fixed length of four integers as can be seen below. The phone ID for "PF" breaks down to three individual phones: "P", "+", and "F".

UPS Phone | SAPI Phone ID
PF | 007003610066
P + F | 0070 0361 0066
AN | 00610303
A nas | 0061 0303

Diacritics

A diacritic cannot stand alone. Diacritics must modify the preceding segmental phone. The compound marker is not required to bind diacritics. If the phone preceding a diacritic is a "+" symbol, it should be ignored by the SR engine. Any number of diacritics can follow a segmental symbol. Diacritics may use the three-letter symbol or the symbolic form if there is one. The SR engine should ignore the "+" marker.

Phone | Parsed Phone
A lng | Alng
A vls lng | Avlslng
A vls + lng | Avlslng

Tones

Lexical tones can follow a vowel or syllabic consonant. They can be made up of simple levels or they can be contours composed of sequences of tones. Lexical tones are described using a universal scale which has a maximum of five level contrasts. A sequence of three tones should be sufficient to describe any tone contour. The following are valid strings using tones.

Phone String | Parsed Phone String
M + A T3 T5 | MA35
M + A + T3 + T5 | MA35
M A + T3 + T5 | MA35

The first example defines a syllabic unit "MA" through the use of the compound "+" marker, with a high rising 35 tone contour.

The second example attaches the tone to the vowel only. It is up to the speech recognition engine to map the "M A" to a syllable "MA" depending on its internal acoustic modeling. The use of the compound symbol "+" between tones is redundant here.

Geminate Consonants

Italian geminates are sometimes described as long consonants, and they could be described using the length diacritic or the "+" symbol. The following table shows some alternative phone strings that have equivalent meaning. The examples are in Italian.

Compounds | IPA | Example
TS lng | T lng + S | TS + TS | t:.s | bozza
DZ lng | D lng + Z | DZ + DZ | d:.z | mezzo
CH lng | T lng + SH | CH + CH | t:.ʃ | braccio
JH lng | D lng + ZH | JH + JH | d:.ʒ | oggi
M lng | M + M | M + M | m.m | mamma

The preferred method is to use the length diacritic. To be safe, the engine developer should anticipate that any of these cases could be encountered in Italian SAPI lexicons or grammars.

Diphthongs

Diphthongs are represented by placing a "+" marker between two vowels, for example: "EY + EU".

German contains several examples of centering diphthongs for which there is no single phone label in UPS. See the diphthongs table in Diphthong Vowel Phones to see how diphthongs would be represented using UPS compounds.

Note that due to the length diacritic there are two ways in which the vowel in Bär could be represented. This first example attaches the length correctly to the EH vowel:

Phone String | SAPI Phone ID
EH lng + AEX | 025B 02D0 0361 0250

However it is possible that people could choose to attach the length to the schwa, (the second vowel) such as in the following example.

Phone String | SAPI Phone ID
EH + AEX lng | 025B 0361 0250 02D0

The SR engine should expect to handle this kind of ambiguity when converting SAPI phones to SR engine phones.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Writing a Speech Recognition Phone Converter for SAPI (Microsoft.Speech)

[image]

Writing a Speech Recognition Phone Converter for SAPI (Microsoft.Speech)
Send Feedback

An engine vendor who wishes to build a new speech recognition (SR) engine for a new language, for which there is no specific phone converter supplied, should use the SAPI Universal Phone Set.

The engine vendor then needs to write a language-specific phone converter from SAPI phones to SR engine phones for the new language. This is implemented in the SR engine's locale handler. This phone converter defines the mapping between the SAPI phone set and the internal SR phone set for the particular language, which defines the acoustic models the engine uses. For example, the SR engine may only model broad phonemic distinctions in the language, but the application lexicon may encode a more precise phonetic description (such as by including Diacritics (Microsoft.Speech)). It is up to the engine to decide how to map the SAPI pronunciations.

In addition, there are no restrictions on application developers to use a particular subset of UPS. The phone converter must do additional validity checks to ensure that the SAPI pronunciations use a valid phone subset for the language in question, and also that the phone strings are well formed according to parsing guidelines. For more information, see Parsing Guidelines for SAPI Speech Recognition Phone Converters (Microsoft.Speech).

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


UPS to SAPI Phone Map (Microsoft.Speech)

[image]

UPS to SAPI Phone Map (Microsoft.Speech)
Send Feedback

The registered universal phone converter lists each SAPI UPS phone label with its SAPI phone ID, as shown in the following table.

UPS Label | SAPI ID | UPS Label | SAPI ID | UPS Label | SAPI ID
I | 0069 | EHX | 025B03610259 | DR | 0256
Y | 0079 | UWX | 007503610259 | NR | 0273
IX | 0268 | OWX | 006F03610259 | DXR | 027D
YX | 0289 | AOX | 025403610259 | SR | 0282
UU | 026F | EN | 00650303 | ZR | 0290
U | 0075 | AN | 00610303 | R | 027B
IH | 026A | ON | 006F0303 | LR | 026D
YH | 028F | OEN | 01530303 | CT | 0063
UH | 028A | P | 0070 | JD | 025F
E | 0065 | B | 0062 | NJ | 0272
EU | 00F8 | M | 006D | C | 00E7
EX | 0258 | BB | 0299 | CJ | 029D
OX | 0275 | PH | 0278 | J | 006A
OU | 0264 | BH | 03B2 | LJ | 028E
O | 006F | MF | 0271 | W | 0077
UPS Label | SAPI ID | UPS Label | SAPI ID | UPS Label | SAPI ID
AX | 0259 | F | 0066 | K | 006B
EH | 025B | V | 0076 | G | 0067
OE | 0153 | VA | 028B | NG | 014B
ER | 025C | TH | 03B8 | X | 0078
UR | 025E | DH | 00F0 | GH | 0263
AH | 028C | T | 0074 | GA | 0270
AO | 0254 | D | 0064 | GL | 029F
AE | 00E6 | N | 006E | QT | 0071
AEX | 0250 | RR | 0072 | QD | 0262
A | 0061 | DX | 027E | QN | 0274
AOE | 0276 | S | 0073 | QQ | 0280
AA | 0251 | Z | 007A | QH | 03C7
Q | 0252 | LSH | 026C | RH | 0281
EI | 006503610069 | LH | 026E | HH | 0127
AU | 00610361028A | RA | 0279 | HG | 0295
OI | 025403610069 | L | 006C | GT | 0294
AI | 006103610069 | SH | 0283 | H | 0068
IYX | 006903610259 | ZH | 0292 | WJ | 0265
UYX | 007903610259 | TR | 0288 | PF | 007003610066
UPS Label | SAPI ID | UPS Label | SAPI ID | UPS Label | SAPI ID
TS | 007403610073 | S1 | 02C8 | mrd | 0339
CH | 007403610283 | S2 | 02CC | lrd | 031C
JH | 006403610292 | . | 002E | adv | 031F
JJ | 006A0361006A | _| | 007C | ret | 0331
DZ | 00640361007A | _|| | 2016 | cen | 0308
CC | 074003610255 | lng | 02D0 | mcn | 033D
JC | 006403610291 | hlg | 02D1 | syl | 0329
TSR | 007403610282 | xsh | 02D8 | nsy | 032F
WH | 028D | _^ | 203F | rho | 02DE
ESH | 029C | _! | 0001 | lla | 033C
EZH | 02A2 | _& | 0002 | lab | 02B7
ET | 02A1 | _, | 0003 | pal | 02B2
SC | 0255 | _s | 0004 | vel | 02E0
ZC | 0291 | _. | 2198 | phr | 02E4
LT | 027A | _? | 2197 | vph | 0334
SHX | 0267 | T5 | 030B | rai | 031D
HZ | 0266 | T4 | 0301 | low | 031E
UPS Label | SAPI ID | UPS Label | SAPI ID | UPS Label | SAPI ID
PCK | 0298 | T3 | 0304 | atr | 0318
TCK | 01C0 | T2 | 0300 | rtr | 0319
NCK | 0021 | T1 | 030F | den | 032A
CCK | 01C2 | T- | 2193 | api | 033A
LCK | 01C1 | T+ | 2191 | lam | 033B
BIM | 0253 | vls | 030A | nas | 0303
DIM | 0257 | vcd | 032C | nsr | 207F
QIM | 029B | bvd | 0324 | lar | 02E1
GIM | 0260 | cvd | 0330 | nar | 031A
JIM | 0284 | asp | 02B0 | ejc | 02BC
 |  |  |  | + | 0361
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Glossary of Phonetic Terms (Microsoft.Speech)

[image]

Glossary of Phonetic Terms (Microsoft.Speech)
Send Feedback

Introduction

Phonetic alphabets isolate the discreet speech sounds of languages and represent speech sounds with combinations of letters, numbers, and characters which are known as "phones". In addition, phonetic alphabets use a vocabulary of terms that describe phones and their articulation, including the following characteristics:

  • Manner of articulation. Describes how the tongue, lips, jaw, and other speech organs make contact to produce a sound.

  • Place of articulation. The point of contact, where an obstruction occurs in the vocal tract between an active (moving) articulator (typically some part of the tongue) and a passive (stationary) articulator (typically some part of the roof of the mouth).

  • Phonation type. Indicates whether a sound is voiced or voiceless. A voiced sound is one in which the vocal cords vibrate. A voiced sound is one in which the vocal cords do not vibrate.

  • Airstream mechanism. The method by which airflow is created in the vocal tract.

Glossary

The following table defines terms used to describe speech sounds and their components, contains additional terms used in phonetics, and includes the abbreviations used in the phone tables of the Phonetic Alphabet Reference (Microsoft.Speech).

Term

Abbrev.

Description

Example in en-US

Advanced

adv

An advanced sound is pronounced farther to the front of the vocal tract than some reference point.

Advanced tongue root

atr

Moving the base of the tongue forward, expanding the pharyngeal cavity, by during the pronunciation of a vowel. Often includes lowering the larynx.

Affricate

aff

A consonant sound that begins with stop-like total closure for the vocal tract, followed by a more controlled, fricative-style release (i.e. a stricture causing friction.)

[ch] (chin), [j] (joy)

Allophone

-

Similar spoken sounds that are represented by the same phoneme (think letter of the alphabet). There may be multiple phones (pronunciations) for a single phoneme. For example, the different pronunciations of the letter "t" in the words tub, stub, but, butter, and button are allophones of the phoneme /t/.*

Alveolar

alv

A consonant that is articulated with the tongue against or close to the upper alveolar ridge, which contain the sockets for the upper teeth.

[t](talk), [d] (dig)

Alveolo-palatal

-

A consonant that is articulated with the blade of the tongue behind the alveolar ridge, and the body of the tongue raised toward the palate.

Apical

api

A consonant that is produced by obstructing the air passage with the tip of the tongue.

Approximant

apr

Speech sounds made by moving articulators close to each other but not narrowly enough or with enough articulatory precision to create turbulent airflow.

[j], [w]

Articulator

-

There are five basic active articulators for creating speech: the lip, the flexible front of the tongue, the middle/back of the tongue, the root of the tongue together with the epiglottis, and the larynx.

Aspiration

asp

A strong burst of air that accompanies either the release of some obstruents.

Back

bck

Indicates that the position of the tongue is close to the back of the mouth during the articulation of a vowel. Back vowels are also called dark volewls.

[u]

Bilabial

blb

A consonant articulated with both lips.

Breathy voice

bvd

A sound in which the vocal cords vibrate, but are held further apart so that a larger volume of air escapes between them.

Center

cnt

Indicates that the position of the tongue is positioned halfway between the front and the back of the mouth during the articulation of a vowel.

Centralized

cen

A vowel sound in which the tongue is positioned halfway between a front vowel and a back vowel.

Click

clk

A sound produced by closing the vocal tract at two places of articulation in the mouth, rarifying (uncompressing) the air in the enclosed space by lowering the tongue, and then releasing both closures.

Coronal

-

A consonant that is articulated with the flexible front part of the tongue

Creaky voiced

cvd

A sound in which the airflow through the glottis is very slow and the vocal chords vibrate more slowly than with normal voicing.

Dental

den

A consonant that is articulated with the tongue against the upper teeth, such as /t/, /d/, and /n/.

Denti-alveolar

dnt-alv

A consonant that is articulated with a flat tongue against the alveolar ridge and upper teeth

Dentolabial

A consonant that is articulated with the lower teeth against the upper lip

Diphthong

-

Literally "two sounds" or "two tones", a unitary vowel that changes quality during its pronunciation.

Dorsal

-

A consonant that is articulated with the mid body of the tongue (the dorsum).

Egressive

-

Sounds in which the air stream is created by pushing air out through the mouth or nose. Egresives may be one of the following types:

Pulmonic egressive. The air stream is created by the lungs, ribs, and diaphragm to make sounds.

Lingual egressive. With the velum closed, the speaker forces air out of the mouth using either the tongue or cheeks.

Glottalic egressive sounds are known as ejectives.

Ejective

ejc

Voiceless consonants that are pronounced with simultaneous closure of the glottis.

Flap (or Tap)

flp

A type of consonantal sound, which is produced with a single contraction of the muscles so that one articulator (such as the tongue) is thrown against another.

Fricative

frc

A consonant sound formed with limited closure of the vocal tract, (i.e. a steady stricture causing friction).

Front

fnt

Indicates that the position of the tongue is close to the front of the mouth during the articulation of a vowel.

[i]

Glottal

glt

Sound production involving only the glottis.

Glottis

-

The combination of the vocal folds (vocal chords) and the space in between the folds.

High

hgh

Indicates that the tongue is in a raised vertical position relative to either the roof of the mouth or the aperture of the jaw to pronounce certain vowels. Vowels thus pronounced are also higher in pitch. Also called closed vowels.

[i] and [u]

Implosive

imp

Implosives consonants are stops in which the airstream is controlled by moving the glottis downward in addition to expelling air from the lungs

Interdental

-

A consonant that is produced by placing the blade of the tongue (the top surface just behind the tip of the tongue) against the upper incisors

Labial

lab

A consonant in which one or both lips are the active articulator.

Labial-alveolar

Consonants that have two primary places of articulation, at the lips and the gums.

labial-palatal

lbp

A sound made both by shaping the roundness of the lips and by raising the body of the tongue toward the hard palate. Rare.

Labial-velar

lbv

Consonants that have two primary places of articulation, at the velum and the lips.

Labiodental

lbd

A consonant that is articulated with the lower lip and the upper teeth.

Labio-palatalization

-

Consonants that are articulated with the lips and with the body of the tongue raised against the hard palate.

Laminal

lam

A consonant that is produced by obstructing the air passage with the blade of the tongue, which is the flat, top surface just behind the tip of the tongue.

Lateral

lat

"L"-like consonants pronounced with an occlusion made somewhere along the axis of the tongue, while air from the lungs escapes at one side or both sides of the tongue. The approximant /l/ is the only lateral in English.

[l]

Lateral release

lar

A consonant that is produced by stopping the airflow in the vocal tract and then releasing it to escape at one side or both sides of the tongue.

Less rounded

lrd

A vowel sound made with the lips less rounded.

Linguolabial

lla

A consonant articulated by placing the tongue tip or blade against the upper lip, which is drawn downward to meet the tongue.

Lowered

low

A sound articulated with the tongue or lip lowered (the mouth more open) than some reference point. Also called open vowel.

[a]

Mid

mid

A vowel that is produced with the tongue positioned mid-way between an open (low) vowel and a close (high) vowel.

Mid-centralized

mcn

A vowel closer to the mid-point of the vowel space, both in terms of front-to-back and top-to-bottom, than some point of reference.

Monophthong

-

Literally "one sound" or "one tone", a vowel whose articulation at both beginning and end is relatively fixed.

More rounded

mrd

A vowel sound made with the lips more rounded.

Nasal

nas

A consonant that is produced with a lowered velum in the mouth, allowing air to escape freely through the nose.

[n], [m]

Nasal release

nsr

A consonant that is produced by stopping the airflow in the vocal tract and then releasing it, allowing the air to escape freely through the nose.

No audible release

nar

A consonant that is produced by blocking the oral tract , but there is no audible indication of when that occlusion ends.

Non-syllabic

nsy

Vowel-like sounds that are not the most prominent part of a syllable.

Obstruent

-

A consonant sound formed by obstructing airflow, resulting in partial or total closure of the vocal tract.

Oral

-

A consonant sound that is made by allowing air to escape from the mouth, as opposed to the nose.

[p], [w], [v] or [x].

Orthography

-

The correct method of writing a language, including spelling, hyphenation, capitalization, word breaks and punctuation.

Palatal

pal

A consonant that is articulated with the body of the tongue raised against the hard palate (the middle part of the roof of the mouth).

Pharyngeal

phr

A consonant that is articulated with the root of the tongue against the pharynx.

Pharynx

-

The pharynx lies behind the oral cavity.

Phone

-

A notation (letters, numbers, characters) that represents a discreet sound in a spoken language. Changing a phone in a word will alter its pronunciation. See Phoneme and Allophone.

Phoneme

-

A basic component of written language, typically a letter of an alphabet, (or the combination of multiple letters) that represents a group of similar sounds. Changing a phoneme in a word will alter its spelling. A written word is an assemblage of phonemes. A phoneme may represent multiple phones. See Phone and Allophone.

[c] (cow, certain); [th] (that, thimble, teeth)

Postalveolar

A consonant that is articulated with the tongue near or touching the back of the alveolar ridge, further back in the mouth than the alveolar consonants, which are at the ridge itself, but not as far back as the hard palate

Radical

-

A consonant that is articulated with the root (base) of the tongue in the throat.

Raised

rai

A sound that is articulated with the tongue or lip raised higher than some reference point.

Retracted

ret

A sound that is pronounced farther to the back of the vocal tract than some reference point.

Retracted tongue root

rtr

The neutral position or the the retraction of the base of the tongue in the pharynx during the pronunciation of a vowel.

Retroflex

rfx

A consonant that is articulated with the roof of the oral cavity behind the alveolar ridge, and may even be curled back to touch the palate or uvula

Rhoticity

rho

Rhotic speakers pronounce /r/ in all positions within a word, while non-rhotic speakers pronounce /r/ only if it is followed by a vowel sound.

Rounded

rnd

The pronunciation of a vowel with lips formed in a circular opening.

Semi-high

smh

A vowel pronounced with the tongue positioned between a high (close) vowel and a mid vowel.

Semi-low

sml

A vowel pronounced with the tongue positioned between a low (open) vowel and a mid vowel.

Sibilant

A type of fricative or affricate consonant, made by directing a jet of air through a narrow channel in the vocal tract towards the sharp edge of the teeth.

[s](sin), [ʃʷ̜] (shin)

Sonorant

-

A speech sound that is produced without turbulent airflow in the vocal tract. Vowels are sonorants.

Stop

stp

A consonant sound produced by stopping the airflow in the vocal tract, followed by an explosive release of air. Also called plosive.

Subapical

-

A consonant made by contact with the underside of the tip of the tongue.

Syllable

-

The building blocks of words, syllables are typically made up of a syllable nuclear (most often a vowel) with optional initial and final margins (typically, consonants).

Syllabic

syl

A consonant which either forms a syllable on its own, or is the nucleus of a syllable.

Tone

-

The use of pitch in language to distinguish lexical or grammatical meaning.

Trill

trl

A consonantal sound produced by vibrations between the articulator and the place of articulation.

Unrounded

unr, urd

A vowel pronounced with the lips not rounded, that is, relaxed.

Upper-mid

umd

A vowel pronounced with the tongue between the high (close) and mid vowel positions.

Uvular

uvl

A consonant that is articulated with the back of the tongue against or near the uvula, that is, further back in the mouth than velar consonants.

Velar

vel

A consonant that is articulated with the back part of the tongue (the dorsum) against the soft palate, the back part of the roof of the mouth, known also as the velum).

Velarize

vph

A secondary articulation of consonants by which the back of the tongue is raised toward the velum during the articulation of the consonant.

Velum

-

The back part of the roof of the mouth; the soft palate.

Vocal Tract

-

Consists of the laryngeal cavity, the pharynx, the oral cavity, and the nasal cavity.

Voiced

vcd

A voiced sound is one in which the vocal cords vibrate.

Voiceless

vls

A voiced sound is one in which the vocal cords do not vibrate.

Vowel

vwl

A spoken sound pronounced with an open vocal tract.

Note Note

In transcription, individual phones are placed between slashes: /sh/.

Individual phonemes are placed in square brackets: [ʃ]

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DTMF Recognition

[image]

DTMF Recognition
Send Feedback

Dual-Tone Multi-Frequency (DTMF) tones are generated by pressing the keys on a telephone. With the DtmfRecognitionEngine class, the Microsoft Speech Platform SDK 11 supports the use of speech recognition grammars to analyze DTMF input emitted by telephones. The members of DtmfRecognitionEngine are similar to those of the SpeechRecognitionEngine class. However, the input for recognition consists of a series of DTMF tones instead of an audio stream.

You can create DTMF grammars programmatically using members of the Microsoft.Speech.Recognition.SrgsGrammar namespace, or create static DTMF grammar files using XML that conforms to the Speech Recognition Grammar Specification (SRGS) Version 1.0. Whether programmatic (dynamic) or XML (static), DTMF grammars can be loaded at runtime by the DtmfRecognitionEngine using the LoadGrammar(Grammar) or LoadGrammarAsync(Grammar) methods.

When performing recognition, the DtmfRecognitionEngine raises events that inform your application about key stages in a recognition operation, such as LoadGrammarCompleted, DtmfHypothesized, DtmfRecognized, DtmfRecognitionRejected, and RecognizeCompleted. You can use the EventArgs class associated with each event to create handlers that return information from the event to your application.

You can use the following methods of the DtmfRecognitionEngine class to manage DTMF tones:

  • AddTone()()()()

  • AddTone()()()()

  • FlushToneBuffer()()()()

  • GetTerminationTones()()()()

  • SetTerminationTone(DtmfTone)

  • SetTerminationTones(ICollection<(Of <<'(DtmfTone>)>>))

Additional methods allow you to initiate DTMF recognition (RecognizeAsync()()()()), terminate DTMF recognition (RecognizeAsyncCancel()()()()), and unload grammars from the DtmfRecognitionEngine object (UnloadAllGrammars()()()() and UnloadGrammar(Grammar)).

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Speech Glossary (Microsoft.Speech)

[image]

Speech Glossary (Microsoft.Speech)
See Also Send Feedback

acronym

A letter sequence formed from the initial letters of a name, such as IPA for International Phonetic Alphabet, or variations on the initial letters, such as XML for Extensible Markup Language.

acoustic model (AM)

A component of a speech engine that describes the sounds of a spoken language. A speech engine uses its acoustic model, in conjunction with its language model and lexicon, to determine how to recognize or pronounce words or phrases.

active grammar

A speech grammar or DTMF grammar that is loaded by a speech recognition engine and is currently active for recognition.

a-law

A standard compression algorithm, used in digital communications systems of the European digital hierarchy, to modify and optimize the dynamic range of an analog signal for digitizing.

alignment

The process of matching words in a transcript to words in a .wav file.

alternative

In speech recognition grammars, one of a set of alternate words or phrases, any of which will match all or part of a rule. In XML-format SRGS grammars, a set of alternative elements is contained within a one-of element. Each alternative is contained in an item element.

ambient noise

The background noise in an area or environment, being a composite of sounds from many sources near and far.

amplitude

A measure of the strength of a signal, for example and audio signal, determined by the distance from the baseline to the peak of the waveform.

audio format

A collection of characteristics that describe the composition of an audio signal that is being received for recognition, including bit depth, samples per second, bytes per second, block align, channel count, and encoding.

audio level

The perceived loudness of an audio signal that is being received for recognition. Factors include the loudness of the sound source (speaker), the proximity of the sound source to the recording device, and the gain of the recording device.

babble

Audio input that is neither speech which matches the initial rule of any of the recognizer's loaded and enabled speech recognition grammars, nor silence.

bookmark

A marker that can be placed in a speech synthesis prompt for which the speech synthesizer will raise an event.

.cfg

The file name extension for an XML-format grammar file that has been compiled to a binary format for consumption by a speech recognition engine.

CFG

See context-free grammar (CFG).

close-talk microphone

A standard type of microphone often used in headsets and other devices in which the user speaks directly into the microphone.

codec

An abbreviation for compressor/decompressor. Software or hardware used to compress or decompress digital media, including audio.

confidence score

A value indicating the likelihood that a word or phrase recognized by a speech engine matches the word or phrase actually uttered by the speaker.

context-free grammar (CFG)

A context-free grammar describes how phrases in a language are built from smaller blocks. SRGS grammars are context-free grammars.

conversational understanding

The ability of a system to recognize spontaneous, conversational speech.

contour

In speech synthesis, an attribute that specifies the frequency and location of changes in pitch that the TTS engine should apply when speaking the contents of a prosody element.

culture

In managed code, a class of information about a particular nation or people including their collective name, writing system, calendar used, and conventions for formatting dates and sorting strings.

diacritic

An ancillary glyph added to a letter, for example ç, ö, or ê.

dictation

A mode of speech recognition, made possible by a large grammar with comprehensive coverage of a language, which accepts freely-spoken input.

diphone

A sound consisting of two phonemes: one that leads into the sound and one that finishes the sound. For example, the word "hello" consists of these diphones: [silence-h] [h-eh] [eh-l] [l-oe] [oe-silence].

diphone concatenation

The process by which a text-to-speech engine concatenates short digital-audio segments and performs inter-segment smoothing to produce a continuous sound.

DOCTYPE declaration

A declaration at the beginning of an XML-format document that gives a public or system identifier for the document type definition (DTD) of the document.

DTMF grammar

A grammar that recognizes dual tone multi-frequency (DTMF) inputs. Contrast with a speech grammar.

dual tone multi-frequency (DTMF)

The signaling system used in telephones with touch-tone keypads, in which each digit is associated with two specific frequencies.

Dublin Core Metadata Initiative

An open forum engaged in the development of interoperable online metadata standards that support a broad range of purposes and business models.

duration

In speech synthesis, an attribute that specifies the desired time that the TTS engine should take to read the contents of a prosody element.

dynamic grammar

A grammar that is created during application execution.

ECMAScript

A scripting programming language created to capture the common core language elements of JavaScript and JScript. ECMAScript is used in the tag element of XML-format grammars to define the semantics for words or phrases.

emphasis

In speech synthesis, the stress or spoken prominence given to a word or phrase.

emulation

The process by which text, rather than speech, is provided as input to a speech recognition engine. Emulation is useful to determine whether a word or phrase is in a grammar and to inspect the recognition result for the word or phrase.

Extensible Markup Language (XML)

A markup language that provides a format for describing structured data. XML is a World Wide Web Consortium (W3C) specification, and is a subset of Standard Generalized Markup Language (SGML).

external grammar

A stand-alone grammar file that is linked from another grammar file using a rule reference. Also referred to as an imported grammar.

garbage

In grammars, a special rule that will match any speech up to the next rule match, the next token, or until the end of spoken input.

globally unique identifier (GUID)

A program-generated number that creates a unique identity for an object.

grammar

A structured list of rules that identify words or phrases that the speech recognition engine should attempt to identify in the spoken input. Also known as a grammar file or a grammar document.

grammar compiler

A compiler that transforms an XML-format grammar file into a binary format file with a .cfg file extension for consumption by a speech recognition (SR) engine.

grammar library

A collection of ready-to-use rules and rule sets designed to recognize commonly used types of user voice input such as dates, times, currency units, numbers, and confirmatory responses, as well as dual tone multi-frequency (DTMF) input.

Grammar Rule Name (GRN) referencing

A type of Semantic Markup Language (SML) script referencing in which the script expression evaluates semantic values of, or assigns semantic values to, the Rule Variable (RV) of the rule element that contains the expression.

Grammar Rule Name (GRN) Rule Variable

A predefined object that holds a semantic value that can be composed of multiple properties. Every rule element in a grammar has a single GRN Rule Variable. The GRN Rule Variable is identified by a dollar sign ($).

Grammar Rule Reference (GRR) referencing

A type of Semantic Markup Language (SML) script referencing in which the script expression evaluates semantic values of the Rule Variable (RV) of a rule element outside of the rule element that contains the expression.

Grammar Rule Reference (GRR) Rule Variable

The Rule Variable of the external rule element to which a grammar rule reference is made. The GRR Rule Variable is identified by a double dollar sign ($$).

Grammar Validator

A command-line tool, available in the Microsoft Speech Platform SDK, which you can use with Microsoft.Speech grammars to check for correct syntax, format, and script functionality.

grapheme

A fundamental unit in a written language, for example letters, numbers, punctuation marks.

.grxml

The file name extension for XML-format grammar files.

GUID

See globally unique identifier (GUID).

homonym

A word with the same sound (homophone) or spelling (homograph) as another, but with a different meaning.

homophone

One of a set of words that are pronounced the same way but differ in meaning, and sometimes in spelling, for example night and knight in English.

homograph

One of a set of words of the same written form but of different meaning and usually origin, whether pronounced the same way or not. For example: lead (to conduct) and lead (the metal).

in-process recognizer

A speech recognition engine that is under the control of a single application. Contrast with a shared recognizer.

International Phonetic Alphabet (IPA)

A standardized system of letters and marks, partially based on the letters of the Roman alphabet, used internationally to represent speech sounds.

inverse text normalization (ITN)

In speech recognition, the process of converting the spelled-out textual result of recognized speech into its more commonly-used written form. For example, the recognized text "one dollar and sixteen cents" would be normalized to "$1.16".

.js

The file name extension for JScript files.

language model (LM)

A component of a speech engine that describes how words of a spoken language are constructed into meaningful sequences. A speech engine has a language model that typically encompasses an entire language, such as French. A grammar is a language model that defines only the words and phrases that have meaning for an application. A speech engine uses its language model(s), in conjunction with its acoustic model and lexicon(s), to determine how to recognize or pronounce words and phrases.

language pack

A set of language resources that supports the development and deployment of applications in a particular language.

lexeme

The name of an element in the Pronunciation Lexicon Specification that contains one or more written representations of a word, one or more pronunciations, and one or more examples.

lexicon

A file that contains the mapping between the written representations and the pronunciations of words or short phrases in a language. A speech engine typically has a default lexicon. Applications and users may also create lexicons. A speech engine uses the phonetic spellings in lexicons, in conjunction with its acoustic model and language model, to determine how to recognize or pronounce words or phrases.

managed code

Code executed by the Microsoft .NET Framework common language runtime (CLR).

metadata

Data that is used to describe other data.

morpheme

A morpheme is the smallest meaningful unit in the grammar of a language. The word "unladylike" consists of three morphemes and four syllables: "Un", "lady", and "like". The word "dogs" consists of two morphemes and one syllable: "dog", and "s", a plural marker on nouns.

mu-law

A standard analog signal compression or companding algorithm, used in digital communications systems of the North American and Japanese digital hierarchies, to optimize the dynamic range of an audio analog signal prior to digitizing.

Multipurpose Internet Mail Extensions (MIME)

A protocol widely used on the Internet that extends the Simple Mail Transfer Protocol (SMTP) to permit data (such as video, sound, and binary files) to be transmitted by Internet e-mail without having to be translated into ASCII format first. Used to describe the media type of lexicons.

natural language

A human language, as opposed to a command or programming language traditionally used to communicate with a computer.

natural language understanding

The ability to infer the intended meaning of a natural language utterance based on the words contained in that utterance.

n-best

The recognition results in which the speech recognition engine has the highest levels of confidence. N is the number of results returned.

.NET Framework

An environment for building, deploying, and running Web Services and other applications. It consists of three main parts: the Common Language Runtime, the Framework classes, and ASP.NET.

node

A word, or the phonetic spelling for a word, on a recognition path in a recognition/alternative graph generated by a speech recognition engine.

orthography

Describes the written form of a language. The elements of orthography include spelling, hyphenation, capitalization, word breaks, and punctuation.

out-of-grammar utterance

An utterance containing words or phrases that are not included in a speech recognition grammar.

PCM8

A recording format typically used in desktop applications. In PCM8, the bit depth of each sample is 8 bits. This format results in lower quality audio than with PCM16, but it requires less disk space.

PCM16

A recording format typically used in desktop applications. In PCM16, the bit depth of each sample is 16 bits.

phone

A notation (consisting of letters, numbers, or characters) that represents a discreet sound in a spoken language. Phones are used to create the phonetic spellings that specify how a word should be pronounced, or to specify the pronunciations of a word that should be recognized. Changing a phone in a word will alter its pronunciation.

phoneme

A phoneme is a basic component of written language, typically a letter of an alphabet (or a combination of letters) that represents one or more distinct sounds. For example, the letter "c" is a phoneme that may sound like "s" in "cinder", or like "k" in "catch". A written word is an assemblage of phonemes. Changing a phoneme in a word will alter its spelling.

The term phoneme is also used as the name of an XML element in the SRGS and SSML specifications that contains the phonetic spelling (consisting of phones) for a word or phrase.

phonetic alphabet

A set of symbols that represents the sounds in spoken languages. Also referred to as pronunciation alphabet. There are three phonetic alphabets used by Microsoft.Speech: the International Phonetic Alphabet (IPA), the Universal Phone Set (UPS), and the SAPI Phone Set.

phrase

An ordered list of words that are spoken in the same utterance.

Phrase Generator

A command-line tool, available in the Microsoft Speech Platform SDK, which you can use with Microsoft.Speech grammars to generate a list of all of the phrases that a grammar will recognize.

pitch

A characteristic of a sound that is determined by the frequency of its vibration. A high-pitched sound has a higher frequency; a low-pitched sound has a lower frequency. In speech synthesis, an attribute that specifies the baseline pitch that the TTS engine should apply when speaking the contents of a prosody element.

postamble

Optional ending words or phrase.

preamble

Optional beginning words or phrase.

prompt

A question, directive, greeting, or information spoken by a speech application. The term also refers to the contents of a prompt, which may be unmarked text or text that is formatted with SSML markup.

pronunciation

The way a word or a language is usually spoken.

pronunciation lexicon

See lexicon.

Pronunciation Lexicon Specification (PLS)

The W3C specification that defines the elements, attributes, and syntax for XML-format lexicons used in speech recognition and speech synthesis.

prosody

A collection of phonological features (pitch, range, contour, volume, rate, and duration) that define the characteristics of spoken language.

pulse code modulation (PCM)

The most common method of encoding an analog voice signal into a digital bit stream.

range

In speech synthesis, an attribute that specifies the span of pitch fluctuations that the TTS engine should apply when speaking the contents of a prosody element.

rate

In speech synthesis, an attribute that specifies the tempo that the TTS engine should apply when speaking the contents of a prosody element.

recognition engine

See speech recognition engine.

recognition grammar

See speech recognition grammar.

recognition path

A sequence of words or phonemes that an engine analyzed while attempting to recognize an utterance.

recognition alternate

One of a collection of possible matches for input to a speech recognition engine.

rejection threshold

A confidence value below which a recognition alternate is rejected by the application.

root rule

The rule that is the entry point to a grammar, and that is active when a speech recognition engine loads the grammar.

Root Rule Variable (RRV)

The GRN Rule Variable of the root rule of a grammar. The RRV provides the semantic result of a recognition.

rule

In grammars, a rule defines a pattern or sequence of words or phrases that a speech recognition engine can use to perform recognition.

semantic interpretation (SI)

The process by which a semantic interpreter generates a result based on a spoken word or phrase that matches a grammar rule.

Semantic Interpretation for Speech Recognition (SISR)

The specification which describes how tags may be inserted within SRGS grammars to support basic post-processing or full semantic interpretation.

semantic item

A value returned by a grammar rule when a user's utterance matches the rule.

Semantic Markup Language (SML)

An XML-based markup language that allows the application to identify and parse meaningful parts of speech recognition output.

shared recognizer

The speech recognition engine in Windows that any open application can use to recognize spoken input. Contrast with an in-process recognizer.

silence

In speech recognition, the absence of spoken input or background noise.

In speech synthesis, the space between spoken words; also referred to as the break or pause between words.

speaker

The user who utters the speech to be recognized by an application.

speaker-dependent

The speech recognition engine requires the user to train it to recognize his or her voice.

speaker-independent

The speech recognition engine does not require training.

Speech API (SAPI)

The native-code speech application programming interface (API) for the Windows Desktop. The Microsoft Speech Platform SDK native-code API can be thought of as the server version of SAPI.

speech application

An application that uses the Microsoft.Speech managed-code API to provide speech recognition and/or speech synthesis for user interaction.

speech grammar

A grammar that recognizes speech inputs. Contrast with a DTMF grammar.

speech recognition (SR)

The process of converting spoken language into a text transcription. Also referred to as automated speech recognition (ASR).

speech recognition engine

Software that accepts spoken language as input, determines what words and phrases or semantic information are present, and outputs a text transcription of the result. Also referred to as a speech recognizer.

Speech Recognition Grammar Specification (SRGS)

A specification developed by the World Wide Web Consortium (W3C) that defines syntax for representing grammars for use in speech recognition. SRGS enables developers to specify the words and patterns of words that a speech recognition engine can use to perform recognition.

speech synthesis

The process of producing synthesized speech output from text on computers.

speech synthesis engine

Software that converts plain text or text with XML markup into artificial speech. A speech synthesis engine synthesizes the glottal pulse from human vocal cords and applies various filters to simulate throat length, mouth cavity, lip shape, and tongue position. Also referred to as text-to-speech engine, TTS engine, speech synthesizer, and voice.

Speech Synthesis Markup Language (SSML)

An XML-based markup language used to control various characteristics of synthetic speech output including voice, pitch, rate, volume, pronunciation, and other characteristics.

speech synthesizer

See Speech Synthesis Engine.

SRGS

See Speech Recognition Grammar Specification (SRGS).

SSML

See Speech Synthesis Markup Language (SSML).

tag

The name of the element in a grammar that contains semantic information, either as string literals or as ECMAScript.

text normalization

Performed as part of speech synthesis, the process of converting numbers, abbreviations, acronyms, and other non-word written symbols into words that a speaker would say when reading that symbol out loud.

text-to-speech (TTS)

Technologies for converting textual (ASCII) information into synthetic speech output.

token

A string that a speech recognizer can use to match spoken input.

training

The process of speaking a series of preselected phrases to a speech recognition engine. This provides the engine with information about the voice, speaking habits, and acoustic environment of a specific speaker. Training typically improves the accuracy of speech recognition.

transcription

A textual record of a spoken input. Transcriptions are commonly used to analyze the performance of a speech application and its grammars by matching what was said during speech input with what was recognized.

TTS

See text-to-speech (TTS).

TTS engine

See speech synthesis engine.

tuning

The process of refining a speech application to improve the accuracy of speech recognition or speech synthesis.

u-law

A standard analog signal-compression algorithm, used in digital communications systems of the North American digital hierarchy, to optimize the dynamic range of an analog signal prior to digitizing.

Unicode

A 16-bit character set that replaces ASCII and allows any character from any language to be represented in a text string. The Unicode character set contains a subset for International Phonetic Alphabet (IPA) phonemes.

Uniform Resource Identifier (URI)

A character string used to identify a resource (such as a file) from anywhere on the Internet by type and location. The set of Uniform Resource Identifiers includes Uniform Resource Names (URNs) and Uniform Resource Locators (URLs).

Uniform Resource Locator (URL)

An address for a resource on the Internet, which specifies the protocol used to access the resource, the name of the server on which the resource resides, and (optionally) the path to a resource.

Universal Naming Convention (UNC)

A name used on Windows to access a drive or directory containing files shared across a network.

Universal Phone Set (UPS)

A machine-readable phone set that is based on the International Phonetic Alphabet (IPA).

UTF-8

The 8-bit Unicode Transformation Format that serializes a Unicode scalar value as a sequence of one to four bytes.

UTF-16

The 16-bit Unicode Transformation Format that serializes a Unicode value as a sequence of two bytes, in either big-endian or little-endian format.

utterance

Anything heard by the engine as a finite series of sounds that the engine attempts to recognize as speech.

viseme

The basic visual unit of speech, which essentially corresponds to the position of the mouth and face when pronouncing a phoneme.

vocabulary

The set of words used in the grammars that a speech application uses. Words that are not in the vocabulary, out-of-vocabulary (OOV) words, cannot be recognized by the speech application.

voice

A speech synthesis (TTS) engine that has specific characteristics, such as culture, age, and gender.

voice command

A word or phrase associated with a voice menu. When an engine recognizes a voice command, it notifies the application that owns the voice menu containing the command.

voice grammar

See speech grammar.

voice user interface (VUI)

A voice-controlled application on a computer, Smartphone, game console, or other device or platform that can host applications.

volume

In speech synthesis, an attribute that specifies how loudly to speak the contents of a prosody element.

.wav

The file name extension for waveform audio files.

waveform audio file

A file format for storing audio on computers.

weight

Within a grammar, an attribute assigned to alternatives that biases the likelihood that an alternative will be chosen as a match for speech input.

As a property of a grammar, a rating that determines the degree of influence that a grammar will have on the ranking of recognition alternatives, relative to other active grammars.

wildcard

A component of a grammar that will match any spoken word.

word boundary

The beginning and ending of individual words, marked by the spacing or silence between words in a speech synthesis prompt.

World Wide Web Consortium (W3C)

The organization that sets standards for Web-based technologies, including the syntax for the XML-format technologies used by speech: SRGS, SSML, SISR, SML, and PLS.

.xml

The file name extension for an XML file.

XPath

A language that describes a way to locate and process items in XML documents by using an addressing syntax based on a path through the document's logical structure or hierarchy.

XPath expression

An expression that searches through an XML document and extracts information from the nodes (any part of the document, such as an element or attribute) in that document.

See Also

Concepts

Glossary of Phonetic Terms (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceXML Support (Microsoft.Speech)

[image]

VoiceXML Support (Microsoft.Speech)
See Also Send Feedback

You can use the Microsoft Speech Platform SDK 11 to create .NET applications that process VoiceXML documents. These .NET applications provide access to speech recognition and speech synthesis (TTS) that facilitate communication with callers.

Voice Extensible Markup Language (VoiceXML) is a specification created by the World Wide Web Consortium (W3C) as a standard for creating interactive voice response (IVR) applications. An IVR application written in VoiceXML markup language consists of one or more documents that define automated communication with a caller. VoiceXML applications must be processed by a VoiceXML interpreter, which makes use of resources outside the VoiceXML application to collect information from, and give information to, a caller.

This section provides an overview of the support for VoiceXML in the Microsoft Speech SDK and describes the new classes and their members.

  • Overview of VoiceXML Support (Microsoft.Speech)

  • Usage Scenarios (Microsoft.Speech)

  • Browser Class (Microsoft.Speech)

  • VoiceXML.Common Namespace (Microsoft.Speech)

See Also

Concepts

Legal Information (VoiceXML Support)

Other Resources

Microsoft Online Privacy Notice
Accessibility in Microsoft Products
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Overview of VoiceXML Support (Microsoft.Speech)

[image]

Overview of VoiceXML Support (Microsoft.Speech)
Send Feedback

Support for VoiceXML in the Microsoft Speech Platform SDK consists of the VoiceXML runtime and two .NET Framework namespaces, Microsoft.Speech.VoiceXml and Microsoft.Speech.VoiceXml.Common, which provide access to the VoiceXML runtime.

VoiceXML Runtime

The VoiceXML runtime consists of a VoiceXML interpreter and a layer of interfaces that connect the VoiceXML interpreter to the required speech and system resources, such as speech recognition engines, speech synthesis engines, input and output audio streams, recorder, tone controller, and logging.

Microsoft.Speech.VoiceXml Namespace

The Microsoft.Speech.VoiceXml namespace consists of two classes: Browser and Browser..::..CallProxy.

The generic Browser base class provides platform-independent access to the VoiceXML runtime. The Browser class also makes use of enumerated types, EventArgs classes, and interpretation result classes that are contained in the Microsoft.Speech.VoiceXml.Common namespace.

Browser is an abstract class that serves as a base for derived classes. The Browser class in the Microsoft.Rtc.Collaboration.AudioVideo.VoiceXml namespace derives from Browser and has access to all its public members.

A Browser instance is associated with a VoiceXML page (the start page) that is specified by a URI. A .NET application normally instantiates a Browser instance and connects to audio inputs and outputs, speech engines, a recorder, a tone processer, and then starts processing a VoiceXML page by calling either the Run(Uri, CookieContainer) or the RunAsync(Uri, CookieContainer) method. For more information, see Browser Class (Microsoft.Speech).

The Browser..::..CallProxy class is used by classes that derive from the Browser class to pass information about calls to the VoiceXML interpreter. See Browser..::..CallProxy class for more information.

Microsoft.Speech.VoiceXml.Common Namespace

The Microsoft.Speech.VoiceXml.Common namespace contains several enumerated types for communicating state. It also includes EventArgs classes and properties that are associated with the events in the Browser class. Additional classes are used as containers for the results of VoiceXML interpretation. The Browser class in the Microsoft.Rtc.Collaboration.AudioVideo.VoiceXml namespace also makes use of the members of the Microsoft.Speech.VoiceXml.Common namespace

For more information, see VoiceXML.Common Namespace (Microsoft.Speech).

Creating VoiceXML Applications

The Microsoft Speech SDK does not instruct developers on creating VoiceXML documents. See the Microsoft Speech Technologies Developer Center for information about authoring VoiceXML applications.

Also see the following specifications of the World Wide Web Consortium (W3C):

Voice Extensible Markup Language (VoiceXML) Version 2.0

Voice Extensible Markup Language (VoiceXML) 2.1

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Usage Scenarios (Microsoft.Speech)

[image]

Usage Scenarios (Microsoft.Speech)
Send Feedback

Interactive voice response (IVR) applications can be used in a wide variety of scenarios. The following is an overview of types of businesses that can use IVR applications to improve customer service while reducing the cost of providing customer care.

Customer Support

A large enterprise, government agency, educational institution, or other organization deploys an interactive voice response (IVR) application to reduce the cost of supporting customers or members. The VoiceXML-enabled IVR allows callers to obtain support without human intervention. The IVR application uses the industry standard VoiceXML format, which means that the organization is not locked into a single application vendor.

Sales

A customer places a telephone call to a business such as a travel agency or a video rental service. The business processes calls with an IVR that includes menus that guide the customer to a particular item, and forms that can be used to order products. The VoiceXML-enabled IVR enables cost-effective telephone sales for customers without internet access. Because the IVR is authored using the industry-standard VoiceXML format, the business is not locked in to one application vendor.

Information Services

A customer places a telephone call to a service to obtain a weather forecast, flight information, stock prices, news, or other information. The information service uses a VoiceXML-based IVR application, which responds with the required information, delivering it to the customer in a time-sensitive and cost-effective way.

Call Centers

Call centers use IVR applications to determine the most suitable destination for a call, based on information obtained from the caller. The IVR application can question the caller about the purpose of a call and transfer the caller appropriately. A caller can be given options such as transfer to an automated response line, transfer to a live agent, or request a call back.

Airlines

Airline customers have increasingly limited patience for frustrating customer care experiences and endless wait times. Airlines can put their customers at ease with voice applications that provide up-to-the minute information and relevant options without ever making them hold for an agent. In this scenario, the VoiceXML browser interacts with a speech recognition engine to understand caller requests, plays pre-recorded audio files to recite menu options, and connects to flight databases to provide details like arrival and departure times, cancellations, and rebooking opportunities.

Financial Services

Voice applications let users interact with their financial institutions at any time from any location. In this scenario, the VoiceXML Browser may interact with real-time stock data feeds and specialized ticker symbol grammars, or write customer data to the institution's customer database.

Health Care

Voice applications help connect patients with their providers and insurers by offering answers to common questions, appointment scheduling/reminders, and proactive contacts when changes occur. In this scenario, a VoiceXML application may instruct the Browser to access audio files that play spoken answers to common health questions, to interact with a scheduling system that helps patients book appointments, or to access a test results database.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Browser Class (Microsoft.Speech)

[image]

Browser Class (Microsoft.Speech)
Send Feedback

The platform-independent Browser class is one of two classes in the Microsoft.Speech.VoiceXml namespace; the other class is Browser..::..CallProxy. Browser is an abstract class that is intended only to be a base class from which to derive platform-specific classes. The Browser class cannot be used directly.

Currently, the only class derived from the Browser class is the Browser class in the Microsoft.Rtc.Collaboration.AudioVideo.VoiceXml namespace, which is implemented in the Unified Communications Managed API (UCMA) 3.0 environment. The Browser class in the Microsoft.Rtc.Collaboration.AudioVideo.VoiceXml namespace can make use of any of the public members of the Browser class in the Microsoft.Speech.VoiceXml namespace, in addition to the members of the Microsoft.Speech.VoiceXml.Common namespace.

For a complete listing and description of all the public and protected members of the Browser class, see Browser.

Overview

The Browser provides access to functionality that allows callers to communicate with a VoiceXML application. The Browser processes the elements in a VoiceXML document using the VoiceXML interpreter in the VoiceXML runtime. An active instance of a Browser also provides access to system functionality, including speech synthesis and audio playback to present information to a caller, speech recognition and DTMF tone detection to collect information from a caller, and a recorder to capture and store the audio from a call.

Creating and Controlling the Browser State

You can use the default constructor in the Browser class to create a Browser instance in any derived class.

After a Browser has been instantiated, you can use methods that control the Browser's state. These methods instruct the Browser to begin interpreting a VoiceXML document or to stop interpreting a VoiceXML document. A property on the Browser object gives the current state of the Browser session.

The arguments of the Browser's Run(Uri, CookieContainer) and RunAsync(Uri, CookieContainer) methods reference the URI of the VoiceXML start page to interpret, and a CookieContainer object. The CookieContainer object stores information about the session that can be used by the Web server that serves the VoiceXML documents.

You can run a Browser instance in either synchronous or asynchronous mode.

Note Note

Only use the synchronous Run(Uri, CookieContainer) method for prototyping and experimentation. Do not use it in a production application.

After launching in asynchronous mode, the Browser generates events during a VoiceXML session that inform the hosting .NET application about the status of phone calls and the state of the Browser session.

When initiated, the Run(Uri, CookieContainer) and RunAsync(Uri, CookieContainer) methods detect whether the Browser instance is already running, and perform one of the following actions:

  • If the Browser instance is running, throw an InvalidOperationException.

  • If the Browser instance is not running, set the value of State to Active, and launch a Browser instance.

The hosting .NET application can terminate a Browser session by calling the StopAsync()()()() method. The StopAsync()()()() method allows the Browser to finish processing the current element before ending the session.

The StopAsync()()()() method sets the value of State to Idle, freeing the Browser instance for use in a new session.

When a session is finished, the Browser instance can be reused or disposed.

Setting a Browser's Input and Output

The Browser class includes methods that a hosting.NET application can use to specify audio inputs and outputs for a VoiceXML session. These methods are only useful for authoring a new Browser class that derives from Browser. Developers who will use an existing Browser implementation, such as the Browser in the Microsoft.Rtc.Collaboration.AudioVideo.VoiceXml namespace, cannot make use of methods described below that specify a Browser's inputs and outputs.

Before launching an instantiated Browser instance to run against a VoiceXML document, the hosting .NET application sets the audio inputs and outputs that will be required to process an automated interaction with a caller during a session.

The media properties of the Browser class are implemented as method calls rather than as public property sets. These methods inform the Browser instance about the source of input audio received from the caller (for speech recognition or recording) and the destination for output audio (from speech synthesis or playback) that the caller will hear.

Input can come from an audio stream, the default audio device, the null device (no input), a Waveform audio (.WAV) format file, or a stream that contains Waveform audio-format data. Output can go to an audio stream, the default audio device, the null device (no output), a Waveform audio (.WAV) format file, or a stream that contains Waveform audio-format data.

Note Note

Calling any of the methods that set audio inputs and outputs while a Browser instance is running, that is, when the value of State equals Active, will result in an InvalidOperationException.

Browser Events

A .NET application registers to receive notification of the events raised during asynchronous Browser sessions. Events inform the hosting .NET application about the current state and type of a phone call transfer, the state of a request to disconnect from a VoiceXML document and the result of the request, and the state of a Browser session.

To receive event notification, a .NET application creates an event handler delegate that identifies the event handler, and adds the delegate instance to the event on the Browser instance. In the following example, a delegate that identifies the HandleDisconnecting event handler is added to the Disconnecting event of the VoiceXML Browser (vxb).

C# Copy image Copy Code
vxb.Disconnecting += new EventHandler<DisconnectingEventArgs>(HandleDisconnecting);

See VoiceXML.Common Namespace (Microsoft.Speech) for information about the enumerated types and EventArgs classes that are associated with Browser events.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceXML.Common Namespace (Microsoft.Speech)

[image]

VoiceXML.Common Namespace (Microsoft.Speech)
Send Feedback

This section describes the types that make up the Microsoft.Speech.VoiceXml.Common namespace. The types in this namespace provide information about events thrown during asynchronous Browser sessions and about the results of synchronous and asynchronous Browser sessions.

  • Enumerated Types (Microsoft.Speech)

  • EventArgs Classes (Microsoft.Speech)

  • Interpretation Results Classes (Microsoft.Speech)

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Enumerated Types (Microsoft.Speech)

[image]

Enumerated Types (Microsoft.Speech)
Send Feedback

The enumerated types in the Microsoft.Speech.VoiceXml.Common namespace contain values that describe the state of an asynchronous Browser instance during a VoiceXML session, and the reason that a synchronous or an asynchronous Browser instance exited a VoiceXML session.

DisconnectState Enumeration

The DisconnectState enumeration describes the state of a request to disconnect from a call during an asynchronous Browser session. When the Disconnected event is raised, the State property on the DisconnectedEventArgs instance indicates the DisconnectState.

For more information, see DisconnectState.

ExitReason Enumeration

The ExitReason enumeration specifies the reason that the Browser exited from a VoiceXML document. When the synchronous Run(Uri, CookieContainer) method returns a VoiceXmlResult, its Reason property instance indicates the reason that the Browser exited the VoiceXML page. For asynchronous Browser instances initiated with the RunAsync(Uri, CookieContainer) method, the Result property of the SessionCompletedEventArgs class gets the VoiceXmlResult.

For more information, see ExitReason.

SessionState Enumeration

The SessionState enumeration indicates the state of an asynchronous VoiceXML Browser session.

For more information, see SessionState.

TransferState Enumeration

The TransferState enumeration indicates the state of a VoiceXML phone call transfer request during an asynchronous Browser session.

For more information, see TransferState.

TransferType Enumeration

The TransferType enumeration indicates the type of phone call transfer to be performed during an asynchronous Browser session.

Note Note

Although the TransferType enumeration contains all three types of transfers defined in the VoiceXML 2.1 standard, the current version of the VoiceXML runtime supports only the Blind transfer type.

For more information, see TransferType.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EventArgs Classes (Microsoft.Speech)

[image]

EventArgs Classes (Microsoft.Speech)
Send Feedback

The Microsoft.Speech.VoiceXml.Common namespace includes Event argument classes that carry information about events that are raised by an asynchronous Browser instance during a VoiceXML session. Event handlers use the information from events to inform the subscribing .NET application about a VoiceXML session.

DisconnectedEventArgs

The DisconnectedEventArgs class contains information that can be used when the Disconnected event is raised, which occurs when a call has been disconnected during an asynchronous Browser session.

For more information, see DisconnectedEventArgs.

DisconnectingEventArgs

The DisconnectingEventArgs class contains information that can be used when the Disconnecting event is raised, which occurs just before a call is disconnected during an asynchronous Browser session.

For more information, see DisconnectingEventArgs.

SessionCompletedEventArgs

The SessionCompletedEventArgs class contains information that can be used when the SessionCompleted event is raised, which occurs at the end of an asynchronous Browser session.

For more information, see SessionCompletedEventArgs.

TransferredEventArgs

The TransferredEventArgs class contains information that can be used when the Transferred event is raised, which occurs when the VoiceXML application has completed a phone call transfer to a different recipient during an asynchronous Browser session.

For more information, see TransferredEventArgs.

TransferringEventArgs

The TransferringEventArgs class contains information that can be used when the Transferring event is raised, which occurs when the VoiceXML Browser is about to process a <transfer> element during an asynchronous Browser session.

For more information, see TransferringEventArgs.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Interpretation Results Classes (Microsoft.Speech)

[image]

Interpretation Results Classes (Microsoft.Speech)
Send Feedback

The PageEvent and VoiceXMLResult classes return information about the result of a Browser session.

PageEvent Class

The PageEvent class contains information about an event thrown from within a VoiceXML document that does not have a corresponding catch element (a handler for the event) in the VoiceXML document.

The hosting .NET application will get the PageEvent information from the VoiceXMLResult object. VoiceXMLResult is the type of return for the synchronous Run(Uri, CookieContainer) method, or is obtained by the Result property of the SessionCompletedEventArgs class during asynchronous Browser sessions.

The UnhandledThrowElement property in the VoiceXmlResult contains the PageEvent object, which holds the value of the throw element's event attribute, for example noinput or error.badfetch. PageEvent also contains the message associated with the event from the catch element's special _message variable, which contains the value of the message string from the corresponding throw element, or a platform-dependent value for the pre-defined events raised by the platform.

VoiceXmlResult Class

The VoiceXmlResult is the type of the return value from the synchronous Run(Uri, CookieContainer) method. For asynchronous Browser instances, launched with the RunAsync(Uri, CookieContainer) method, the Result property on the SessionCompletedEventArgs class provides the VoiceXMLResult.

The properties of the VoiceXMLResult object get the following information about a completed Browser session:

  • The Namelist property gets programmable name/value pairs set in the VoiceXML document processing.

  • The Reason property gets the reason that a Browser exited a VoiceXML document.

  • The UnhandledThrowElement gets a PageEvent object.

  • The Cookies property gets a System.Net.CookieContainer object.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Microsoft Grammar Development Tools

[image]

Microsoft Grammar Development Tools
See Also Send Feedback

This section provides documentation for a set of command-line tools that you can use to validate, debug, test, and optimize grammars for voice applications. You can use the Microsoft Grammar Development Tools to find errors, inefficiencies, and redundancies in grammars. The Grammar Development Tools will help you to optimize your grammars, to find the optimum confidence level setting for your speech recognition context, and to test the results of your optimizations.

The following links provide instructions and examples for using the Grammar Development Tools at various stages in the grammar creation process.

Configuration

See the following topic before your first use of the Grammar Development Tools.

  • Setting Up the Grammar Development Tools

Testing/Debugging

The following tools are helpful for maximizing the likelihood that grammars will function as expected, and contain the most useful content for an optimum recognition experience.

  • Grammar Validator Reference Manual

  • Phrase Generator Reference Manual

  • Check Phrase Reference Manual

  • Confusability Reference Manual

Tuning with Utterances

Either before you deploy, or after you receive feedback from a live deployment, you can use the following tools to tune your grammars based on analysis of simulated recognition for batches of utterances.

  • Simulator Reference Manual

  • Simulator Results Analyzer Reference Manual

Deployment

When you are ready to deploy, use the following tools to compile your grammars to a binary format, and to optionally optimize your grammars for peak performance in the environment in which you expect your application to run.

  • Compile Grammar Reference Manual

  • Prepare Grammar Reference Manual

Remarks

You can find the executable files for the Grammar Development Tools in the Tools folder under the directory that contains your installation of the Microsoft Speech Platform SDK 11.

Note Note

You can use the Grammar Development Tools on systems running Windows XP, but only for some providers. Using the "local" provider is not supported on Windows XP. See Speech Recognition Engine Configuration File Settings for more information. However, Windows XP does NOT provide support for any of the other functionality of the Speech Platform SDK 11. See Microsoft Speech Platform SDK 11 Requirements and Installation.

For information about authoring grammars, see and Grammars Overview (Microsoft.Speech) and Create Grammars (Microsoft.Speech).

See Also

Concepts

Legal Information (Speech SDK Tools)

Other Resources

Microsoft Online Privacy Notice
Accessibility in Microsoft Products
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Development Workflows

[image]

Grammar Development Workflows
Send Feedback

Creating grammars is perhaps the most challenging task when building a speech-enabled application. How can you determine whether the grammar that you created provides the user experience that you intend? How can you improve the response of your application to voice input? The Microsoft Grammar Development Tools are designed to provide you with actionable answers to these questions and others throughout the grammar development process.

The processes involved in grammar development may vary depending on your application and its environment. Often, grammar development includes the following phases:

  • Design/Authoring

  • Testing/Debugging

  • Tuning with Utterances

  • Deployment

The following diagram provides an overview of using the Grammar Development Tools in the grammar development process.

Grammar Develpment Tools Workflow

Design/Authoring

Before you begin the process of actually creating grammar files, you will need to envision and define how users will interact with your application by speaking. In this design phase, you will want to answer questions such as the following:

  • Which application contexts are good candidates for voice interaction?

  • What actions or application behavior can a user initiate using her voice?

  • What words can a user say to initiate each action or behavior?

  • How will users know when they can speak to the application and what they can say?

Answers to these questions and others will focus the task of developing grammars that facilitate engaging and rewarding interactions for users of your application.

You will typically use the Grammar Development Tools after design decisions have been made; voice-driven interactions between your application and its users have been identified and designed, and a vocabulary that your application can understand has been defined.

Now that you are in the authoring phase, you can use an XML editor, for example Visual Studio, to author grammar files. You can also create grammars programmatically that comply with the Speech Recognition Grammar Specification (SRGS) Version 1.0 using the Microsoft.Speech.Recognition.SrgsGrammar namespace, and export the resulting grammars to XML-Format files for consumption by the Grammar Development Tools. See Create Grammars Using SrgsGrammar (Microsoft.Speech).

Testing/Debugging

Having authored one or more grammar files, you can use any of several Grammar Development Tools to determine whether a grammar achieves the goals for which it was designed. In this phase, you may have the following questions:

  • Does my grammar have access to all the resources it needs?

  • Does my grammar over-generate or under-generate phrases?

  • Is a specific phrase in the grammar?

  • Does my grammar contain acoustically ambiguous content?

In this phase, you will typically revise a grammar based on output from one or more of the Grammar Development Tools, including the following:

  • Grammar Validator. Verify the syntax and conformance to schema for XML and ECMAScript (JavaScript, JScript) script, verify that referenced rules, grammars, and lexicons can be loaded. It is a good practice to check your grammars with Grammar Validator after each revision, for example updates you make based on the output from one of the other Grammar Development Tools. See Grammar Validator Reference Manual.

  • Phrase Generator. Produce a comprehensive or filtered list of phrases that a grammar will recognize. The result can help you determine whether your grammars over-generate or under-generate phrases. You can use lists of phrases output by Phrase Generator as input to the Confusability tool. See Phrase Generator Reference Manual.

  • Check Phrase. Determine with certainty whether or not any given phrase is in a grammar. See Check Phrase Reference Manual.

  • Confusability. Analyze grammars for words that may be mistaken for each other when spoken. Speech applications may incorrectly recognize a word in a grammar because its sound is similar to another word in the grammar. You can address confusable phrases in your grammars by substituting synonyms, adding custom pronunciations, or making a phrase longer. You can even use Confusability as an authoring tool by checking whether proposed new phrases, if added to the grammar, may be confused with phrases already in the grammar. See Confusability Reference Manual.

Tuning with Utterances

Speech applications may incorrectly accept unintended words or reject words that are part of the application's vocabulary. You are almost ready to deploy, but may still have the following questions:

  • How accurately does a grammar recognize intended input and reject unintended input?

  • Which confidencelevel setting on the speech recognition will provide the most accurate performance?

  • What out-of-grammar phrases should I consider adding to the grammar as synonyms?

If your production schedule allows it, and you have access to utterances that represent the vocabulary of your application, you can test the effectiveness of your application's grammars in recognizing its vocabulary using the following tools:

  • Simulator. Connects to a speech recognition engine and produces raw recognition results for batches of utterances (such as ".wav" files). See Simulator Reference Manual.

  • Simulator Results Analyzer. Computes percentages and totals that illustrate the effectiveness of recognition for the utterances used as input to Simulator. The analysis results not only point out errors in recognition, but also provide guidance for determining the optimum confidencelevel setting for your speech recognition engine. See Simulator Results Analyzer Reference Manual.

  • Speech Recognition Engine Configuration File. Set the confidencelevel of the speech recognition to achieve the best ratio of accepted recognitions to rejected recognitions. See Speech Recognition Engine Configuration File Settings.

If you do not have access to utterances, you can supply Simulator with a list of phrases in an EMMA document and receive emulated recognition results that include whether each phrase is in a grammar, as well as the semantic result for each in-grammar phrase.

Deployment

When you are ready to deploy, you can compile and optimize your grammars for the Microsoft Speech Platform Runtime 11 using the Compile Grammar tool. See Compile Grammar Reference Manual. Optionally, you can further optimize your compiled grammars for the specific speech recognition engine that your application will use in the production environment in which you expect it to run, using the Prepare Grammar tool. See Prepare Grammar Reference Manual. This will help you address the following concerns:

  • How can I minimize the risk of application latency when loading grammars (especially for large grammars)?

  • How can I convert source grammars in Advanced Research Projects Agency (ARPA) format for use with the Speech Platform Runtime 11?

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


What's New in the Grammar Development Tools

[image]

What's New in the Grammar Development Tools
Send Feedback

The Microsoft Speech Platform SDK 11 provides new functionality in the Microsoft Grammar Development Tools to help you validate, debug, test, and optimize grammars for voice applications. Here is a summary of the new functionality:

New Tools

The following tools are new for version 11 of the Grammar Development Tools.

Check Phrase Tool

This new tool takes a phrase and a grammar as input and outputs whether the phrase is in the grammar. Check Phrase emits the custom pronunciations associated with a found phrase.

See Check Phrase Reference Manual.

Confusability Tool

This new tool identifies phrases in a grammar that are phonetically similar. This helps you to detect phrases that could ultimately cause users to have a poor experience. Confusability accepts multiple grammar files as input and performs its analysis on the entire set of specified input files.

  • You can choose whether or not the tool emits confusable results for phrases whose semantics match. By default, warnings and results are only emitted when semantics are different.

  • For advanced analysis, the /SemanticPath option allows you to filter the results to compare only the semantic nodes that you specify.

See Confusability Reference Manual.

Enhanced Functionality for Existing Tools

The following is a summary of enhancements made to Grammar Development Tools since the previous release of Microsoft Speech Platform SDK.

Grammar Validator

  • Validates the syntax for the grammar element's sapi:alphabet attribute and the token element's sapi:pron and sapi:display attributes.

  • Emits a range of warnings when validating a grammar, including the detection of recursion and unreachable rules.

See Grammar Validator Reference Manual.

Phrase Generator

  • Generates a subset of phrases based on weights in the grammar, and you can optionally choose not to expand specified rule references.

See Phrase Generator Reference Manual.

Simulator

  • You can choose whether or not to reuse the engine state in the structure of the input EMMA, rather than from an option at the command line. That is, the recognition engine state is now automatically reused only when utterances are contained within an emma:sequence block. In addition, the /ReuseEngineState command-line option has been removed.

See Simulator Reference Manual.

Simulator Results Analyzer

  • Now provides additional data for tuning your grammars, including out-of-grammar phrase detection and new error-rate categories to give you improved analysis and metrics for simulated recognition.

  • Adds new XML elements (AudioType, RecoResultSemantics, and TranscriptSemantics) to the tool's output to make it easier to analyze results without needing to refer back to the Simulator's output file.

  • The Excel template for generating graphs and tables from the output of Simulator Results Analyzer has been discontinued. See Generating Simulations and Performing Analysis.

See Simulator Results Analyzer Reference Manual.

More New Features and Enhancements

Support for custom pronunciations. There is expanded support for custom pronunciations both inline in grammars and in lexicon files that are linked from grammars. See Custom Pronunciations Support.

Explicit handling of SRGS "special" rule behavior. Improved handling and more descriptive output for grammars that contain the NULL, VOID, and GARBAGE rules have been added across the Grammar Development Tools. See Special Rules Support.

Support for cookie pass-through. You can now define cookies to use for local or web provider types in both the Simulator's recognition configuration file and the EMMA input file. See Simulator Reference Manual and Setting Up the Grammar Development Tools.

New installation option. You can choose the path for the installation of the Speech Platform SDK 11.

Windows XP support for SDK tools. The Grammar Development Tools (with the exception of PrepareGrammar.exe) are now supported on computers running Windows XP, but only for some providers. Using the "local" provider is not supported on Windows XP. See Speech Recognition Engine Configuration File Settings for more information.

Important note Important

All functionality of the SDK outside of the Grammar Development Tools is NOT supported on Windows XP.

Leveraging of phrases based on URL. The set of tools will allow you to reference grammars via URL.

Floating point representation. Scientific notation for floating point numbers (such as 0.1E+1) will not be supported.

In addition, there are other enhancements such as improved error messaging, updated command-line help in the console, updated command-line syntax, improved consistency across the command-line tools, and new samples to help you get started using the Grammar Development Tools.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Setting Up the Grammar Development Tools

[image]

Setting Up the Grammar Development Tools
Send Feedback

With the exception of Simulator Results Analyzer, each of the Microsoft Grammar Development Tools connects to a speech recognition engine to perform its work, even if a given tool does not actually perform speech recognition as part of its functioning. When using one of the Grammar Development Tools, you must provide it with information about which speech recognition engine to use and how to configure the connection to the engine.

You can store settings for connecting to a speech recognition engine in a configuration (RecoConfig) file. The RecoConfig file identifies the environment that hosts one or more speech recognition engines and provides parameters that you can use to select and configure a speech recognition engine. An environment that hosts speech recognition engines is called a provider.

You must either specify a RecoConfig file on the command line when you launch a tool or create a default configuration file named "RecoConfig.xml". The default configuration file must be located either in the current directory (the directory for the command line), or in the directory that contains the tool. Any of the Grammar Development Tools will automatically connect to the recognition provider and speech recognition engine specified in the default RecoConfig file, unless you specify another RecoConfig file on the command line. With the exception of Simulator Results Analyzer, none of the Grammar Development Tools will function without a RecoConfig file.

If you typically use the same speech recognition engine, for example, the local engine on your computer, then you can simply create one RecoConfig file in one of the default locations, and not need to specify it on the command line. You may need to create multiple RecoConfig files under the following circumstances:

  • You alternate among using different recognition providers or speech recognition engines.

  • You need to pass in cookies with requests for recognition.

  • You work in multiple languages.

Based on your anticipated usage, create at least one RecoConfig file before you first use one of the Grammar Development Tools.

In This Section

  • Speech Recognition Engine Configuration File Settings. Information about which settings you can specify.

  • Speech Recognition Engine Configuration File Examples. An example that you can use as a starting point to create your own RecoConfig files.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Speech Recognition Engine Configuration File Settings

[image]

Speech Recognition Engine Configuration File Settings
See Also Send Feedback

With the exception of Simulator Results Analyzer, each of the Microsoft Grammar Development Tools requires a speech recognition engine configuration file at launch. You use a recognizer configuration file, hereafter referred to as "RecoConfig file", to specify which speech recognition engine the Grammar Development Tools will use, and to specify behavioral parameters for the speech recognition engine. The following describes the parameters that you can set in the RecoConfig file.

Configuration Element

The Configuration element is the root element of the RecoConfig file, and contains the following immediate child elements:

Child Element

Description

Provider

Required child element of the Configuration element. Use to specify the environment that hosts one or more speech recognition engines. Takes the type attribute.

Properties

Optional child element of the Configuration element. Takes the attributes that configure the response of the speech recognition engine to grammars that it receives.

CookieJar

Optional child element of the Configuration element. Contains one or more Cookie elements.

The following are examples of scenarios that would require you to use CookieJar:

  • A remote URI fetch is protected by a cookie-based authentication mechanism.

  • A framework requires parameters to be delivered via HTTP cookies instead of URI query parameters.

Cookie request headers with a domain attribute are used to initialize an empty cookie store associated with the current WebReco request. Any remote URI fetch made to load a grammar or audio content must include cookies from that cookie store.

Provider Element

Use the Provider element to designate the environment that hosts a speech recognition engine that is specified in the Properties element. You can also specify a proxy for fetching remote grammars. The Provider element takes the following attributes and child elements:

Attribute or Child Element | Description
type | Required attribute of the Provider element. Specifies the environment that hosts the speech recognition engine specified in the Properties element.
GrammarProxy | Optional child element of the Provider element. Use to make sure the speech recognition can fetch grammars through a proxy. A Provider element can contain only one GrammarProxy element. This attribute may not be available if the value for type is other than local.

Remarks

If the Provider element's type attribute targets an environment that modifies the syntax and schema of the Speech Recognition Grammar Specification (SRGS) Version 1.0 in its implementation of XML-format grammars, this may influence the output of one or more of the Grammar Development Tools. The Grammar Validator tool verifies syntax and schema of submitted grammars according to the derivation of SRGS used by the environment specified by the type attribute.

Properties Element

You can specify parameters for selecting a speech recognition engine and configure the behavior of a selected speech recognition engine by specifying values for the attributes in the Properties element. This is optional. The designated speech recognition engine will use its default values for the attributes of the Properties element unless you specify different values in the RecoConfig file.

Attribute

Description

enginetokenname

Optional attribute of the Properties element. Use this attribute to specify the speech recognition to use. The value must be the exact string that is the token name of the installed speech recognition engine, as found in the registry. This attribute may not be available if the value for the type attribute of the Provider element is other than local.

enginerequiredattributes

Optional attribute of the Properties element. A set of optional name/value pairs used to select a recognition engine, for example, to choose between different recognition vendors, or between recognizers with different abilities. The values are URI-encoded query strings, which may use either ampersands or semicolons for name/value pair separators.

Default: None; use the API endpoint's default recognition engine.

Examples: "Language=409;CommandAndControl", "Vendor=Microsoft".

engineoptionalattributes

Optional attribute of the Properties element. A set of optional name/value pairs used to select a recognition engine, for example, to choose between different recognition vendors, or between recognizers with different abilities. The values are URI-encoded query strings, which may use either ampersands or semicolons for name/value pair separators.

Default: None; use the API endpoint's default recognition engine.

Examples: "Language=409;CommandAndControl", "Vendor=Microsoft".

confidencelevel

Optional attribute of the Properties element. The confidence level for speech recognition. Utterances with a confidence score below the specified value are rejected (a nomatch event is thrown). A value of "0.0" means minimum confidence is needed for recognition, and a value of "1.0" requires maximum confidence.

Range: "0.0"-"1.0".

timeout

Optional attribute of the Properties element. The length of initial silence in an audio stream before a noinput event should be returned, given in seconds or milliseconds.

Examples: "3s", "850ms", "0.7s", ".5s" and "+1.5s".

completetimeout

Optional attribute of the Properties element. The length of silence required following user speech before the speech recognizer finalizes a result (either accepting it or throwing a nomatch event), when the speech is a complete match of all active grammars.

Examples: "3s", "850ms", "0.7s", ".5s" and "+1.5s".

incompletetimeout

Optional attribute of the Properties element. The length of silence required following user speech after which a recognizer finalizes a result, when the speech is an incomplete match of all active grammars. In this case, once the timeout is triggered, the partial result is rejected (with a nomatch event). The incomplete timeout also applies when the speech prior to the silence is a complete match of an active grammar, but where it is possible to speak further and still match the grammar.

Examples: "3s", "850ms", "0.7s", ".5s" and "+1.5s".

sensitivity

Optional attribute of the Properties element. The sensitivity level of the speech recognition engine. A value of "1.0" means that it is highly sensitive to quiet input. A value of "0.0" means it is least sensitive to noise.

Range: "0.0"-"1.0".

speedvsaccuracy

Optional attribute of the Properties element. The desired balance between speed and accuracy for recognizer input. A value of "0.0" means fastest recognition. A value of "1.0" means best accuracy.

Range: "0.0"-"1.0".

maxnbest

Optional attribute of the Properties element. Maximum number of recognition results returned (the maximum size of the n-best list).

Example: "4".

requesttimeout

Optional attribute of the Properties element. The maximum amount of time that the speech recognition engine will spend to service a request.

Examples: "3s", "850ms", "0.7s", ".5s" and "+1.5s".

Note that the apparent requesttimeout intervals may be extended by network latency.

engineproperty

Optional attribute of the Properties element that specifies configuration parameters or other data for configuring the speech recognition engine. There is no standard format for this parameter, although a recommended encoding for the common case of name/value pairs is a URI encoded query string.

Default: None; equivalent to providing an empty string as a value.Example: None; differs per recognizer implementation.

logstring

Optional attribute of the Properties element containing an arbitrary text string that describes the state of the caller's application at the time it requested recognition. This is used purely for logging, for example, to tag a request as a "locality" recognition rather than a "listing" recognition. API callers may also wish to store other speech-specific parameters such as recognition turn in this string.

Default: None; no application-specific string is logged.Example: "locality".

Remarks

If multiple engines are installed that meet the criteria for engineoptionalattributes and enginerequiredattributes, then the engine chosen will be implementation-specific and is not guaranteed to be deterministic even when the same engines are installed.

  • A best attempt will be made to satisfy all specified engineoptionalattributes, but no error will be returned if no engine is found that satisfies them.

  • If no engine is installed which has ALL the enginerequiredattributes, then an error will be returned.

If the speech recognition engine specified in the Properties element cannot be found, the requesting tool will generate an error that includes the names of available speech recognition engines in the environment.

The values for engineproperty are passed through to the local recognizer. This property is particularly useful if you need to specify a setting that is not explicitly supported by the Grammar Development Tools. Some engine property names are reserved, such as "simulationmode" which may accept a value of "emulate", "simulateonce", or "grammarconfusion".

Any recognition result with a confidence score less than the confidencelevel value will not be classified as CA/In or FA/Out by the Simulator Results Analyzer. See Simulator Results Analyzer Interpreting the Results for more information.

To properly assess the confidence threshold setting for your application via the output of Simulator Results Analyzer, set confidencelevel="0". This will ensure that all recognitions are returned, regardless of confidence score. Specify the configuration file in the /RecoConfig option on the command line when you launch the Simulator tool.

For ARPA-format source grammars only, the Compile Grammar tool will look for a language declaration in the engineoptionalattributes attribute to set the language of the compiled grammar file. If no language is declared, then the language of the compiled file will be US English. A language declaration in the engineoptionalattributes attribute must be in the following form:

enginerequiredattributes="Language=[LanguageCode]"

The language code must be specified in three digit hexadecimal format, without the leading "0x". Here is an example that specifies the French language as spoken in France.

enginerequiredattributes="Language=40C"

The Microsoft Speech Platform SDK 11 accepts all valid language-country codes as values in the enginerequiredattributes attribute. For a given language code specified in the enginerequiredattributes attribute, a speech recognition engine that supports that language code must be installed for the grammar to be loaded successfully. See Locale ID (LCID) Chart for a list of language codes.

CookieJar Element

Child Element

Description

Cookie

Optional child element of the CookieJar element. The Cookie element takes the following attributes:

  • name Required. The name of the cookie, which you can specify and which may vary from cookie to cookie.

  • value. Required. Information associated with the cookie.

  • domain. Optional. The domain in which the cookie is valid, beginning with a dot (.).

  • path. Optional. The subset of URLs to which the cookie applies.

  • secure. Optional. Indicates that a cookie should only be transmitted over a secure channel.

See Also

Concepts

Speech Recognition Engine Configuration File Examples
Compile Grammar Input and Output File Format
Simulator Results Analyzer Interpreting the Results
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Speech Recognition Engine Configuration File Examples

[image]

Speech Recognition Engine Configuration File Examples
Send Feedback

With the exception of Simulator Results Analyzer, each of the Microsoft Grammar Development Tools requires a speech recognition engine configuration file at launch. You use a configuration file, hereafter referred to as "RecoConfig file", to specify which speech recognition engine the Grammar Development Tools will use and to configure the behavior of the speech recognition engine. You can create RecoConfig files that target a speech recognition engine in the environment in which you expect your application to run.

Example RecoConfig File Using a Local Speech Recognition Engine

The following is an example of a RecoConfig file for connecting to a Microsoft speech recognition engine using the language US-English on a local computer. The purpose of this file is to demonstrate how to configure a locally installed Microsoft speech recognizer for use with the Grammar Development Tools. In this example, the RecoConfig file specifies several optional properties that can be set on the recognizer.

XML Copy image Copy Code
<Configuration>

  <!-- Indicates that the recognizer is installed locally -->
  <Provider type="local" />

  <!-- Only the 'enginerequiredattributes' values are required; all others are optional -->
  <Properties
      completetimeout="0.25s" incompletetimeout="3s"
      maxnbest="4" requesttimeout="15s" enginerequiredattributes="Language=409;Vendor=Microsoft"
      engineoptionalattributes="CommandAndControl">
  </Properties>

</Configuration>

Remarks

The "Language=409" value indicates US-English. Change this value to target a different language, (for example use 411 for Japanese), or create separate RecoConfig files for each language that you want to target.

Note Note

To configure a local speech engine, you must first install both the Microsoft Speech Platform Runtime 11 and a runtime language (that is, a language pack or specific language engine).

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Validator Reference Manual

[image]

Grammar Validator Reference Manual
Send Feedback

Grammar Validator is a command-line tool that statically analyzes a grammar and reports errors and warnings for incorrect syntax in the grammar XML and in the semantic script. Also, it verifies that rule references to external files are functioning. You can use this tool to analyze and debug a grammar in the absence of access to speech recognition services.

The Grammar Validator Reference Manual contains the following topics.

  • Grammar Validator Usage Scenarios

  • Grammar Validator Command-Line Syntax

  • Grammar Validator Error Messages and Format

  • Grammar Validator Input and Output File Format

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Validator Usage Scenarios

[image]

Grammar Validator Usage Scenarios
Send Feedback

Grammar Validator checks your XML-format grammars for correct syntax and conformance to schema. There are two primary usage scenarios for Grammar Validator.

  1. You have constructed a grammar for all or a portion of your application. Before you proceed with further testing and tuning, you want to make sure that your XML and script are free of errors in syntax that would prevent the grammar from functioning.

  2. At a later stage in the grammar development cycle, you change the XML or the script in the grammar, perhaps based on the output from one of the grammar development tools. You want to make sure that the change did not break anything.

Grammar Validator will help you to answer the following questions during the authoring and editing phases of grammar development:

  • Will my grammar compile?

  • Are the grammar XML and the JavaScript syntactically correct?

  • Are external rule references available to load? You can use the tool to verify this before you deploy.

  • Did the change in the grammar inadvertently break anything? You don't have to upload the grammar, call into the system, and debug 'dead air' just to find out that it contains a typo.

Note Note

Grammar Validator verifies the syntax and schema of input grammar files according to the rules of the recognition provider that you specify. You must specify a recognition provider using a speech recognition engine configuration file. See Setting Up the Grammar Development Tools.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Validator Command-Line Syntax

[image]

Grammar Validator Command-Line Syntax
Send Feedback

The command-line syntax for Grammar Validator has the following format.

GrammarValidator /In <name of the file to validate> /RecoConfig <configuration file name>

The following table describes the command-line option names and values for Grammar Validator.

Option name | Description
/In | Required. The name of the grammar file to be validated.
/RecoConfig | Optional. The name of the configuration file to use for the speech recognition engine. If not specified, the tool will look for a default configuration file named "RecoConfig.xml" in the current working directory and in the directory that contains GrammarValidator.exe. The tool will generate an error if you do not supply it with a configuration file.
/? | Optional. Displays a list of acceptable option/value pairs.
Note Note

  • Command-line options are not case-sensitive.

  • Command-line options can be preceded by a forward slash (0x002F), a dash (0x002d), an en dash (0x2013), an em dash (0x2014), or a horizontal bar (0x2015).

  • You can enter option/value pairs in any sequence.

Remarks

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" either in the current directory (the directory for the command line) or in the directory that contains GrammarValidator.exe. Use the configuration file to specify a speech recognition engine to use, to configure the parameters for connecting to it, and to configure its behavior. For more information, see Setting Up the Grammar Development Tools.

Example

The following example shows a typical entry at the command prompt for GrammarValidator.exe, when there is a default configuration file named "RecoConfig.xml" in the current directory or in the directory that contains the executable for the tool.

GrammarValidator -In C:\Grammars\MyGrammar.grxml

The following is an example command-line entry that specifies a configuration file that is not the default file in the current directory or in the directory that contains GrammarValidator.exe:

GrammarValidator -In C:\Grammars\MyGrammar.grxml -RecoConfig C:\Grammars\SpecialRecoConfig.xml

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Validator Input and Output File Format

[image]

Grammar Validator Input and Output File Format
Send Feedback

Grammar Validator takes as input a grammar (for example a file with a ".grxml" extension) and outputs a set of error and warning messages relevant to the contents of the grammar.

Note Note

The ".grxml" file extension is an accepted convention for XML-based grammar documents that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0; however, the extension is not required.

Input File Format

Input files for Grammar Validator must meet the following requirements.

  • The input grammar must conform to the SRGS specification.

  • All ruleref elements must be properly formatted in conformance with the SRGS specification.

A ruleref element contains a link to one of the following:

  • A rule element within the grammar file

  • A rule element in an external grammar file

  • An external grammar file

Grammar Validator processes all external grammars and rules that the input file references.

Grammar rules specify the user input that the speech recognition engine will recognize while the grammar is active. For more information see rule Element (Microsoft.Speech) and ruleref Element (Microsoft.Speech).

Output File Format

Grammar Validator writes its output to the console; it does not create a file. The tool first writes the error messages generated by the input file. For more information, see Grammar Validator Error Messages and Format.

Tool Execution Summary

When the tool finishes validating the input grammar file, it generates an execution summary that contains the numbers of errors and warnings it found during validation, as shown in the following example.

Processing Complete: 5 Error(s). 7 Warning(s).

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Validator Error Messages and Format

[image]

Grammar Validator Error Messages and Format
Send Feedback

Grammar Validator outputs a set of error and warning messages relevant to the contents of an input grammar. The tool generates errors for conditions that prevent the grammar from being loaded and used by the Microsoft Speech Platform Runtime 11. Grammar Validator generates warnings for conditions that might cause undesired runtime behavior when the grammar is used. Warnings do not prevent the grammar from being used, but indicate conditions that the grammar author might want to evaluate.

Error messages for errors detected within input files contain the following information:

  • File name (if applicable)

  • Line number within the file of the error (if applicable)

  • Message type: Error, Warning, or Info

  • Error code (if applicable)

  • Error description

The following examples demonstrate the types of error and warning messages produced by Grammar Validator. See the next section, Error Types, for further discussion of each error type.

C:\grammars\mygrammar.grxml(57): Error: A rule name was duplicated.

C:\grammars\mygrammar.grxml(83): Warning: Ambiguous Normalization

C:\grammars\mygrammar.grxml: Error: Problem opening file

C:\grammars\mygrammar.grxml(113): Error: Can't have 'continue' out of loop

Execution continues until all available errors and warnings are identified. If errors are encountered the tool returns EXIT_FAILURE (1). Upon successful completion, with no errors, the tool returns EXIT_SUCCESS (0).

Error Types

Grammar Validator reports the following types of errors.

  • Tool-specific errors

  • Speech API (SAPI) errors

  • JScript syntax errors

Tool-Specific Errors

Grammar Validator will throw an error if it encounters any of the following conditions:

  • The grammar file specified by the /In option cannot be found, or cannot be opened.

  • The grammar file specified by the /In option is not properly formed and cannot be compiled.

  • The grammar file specified by the /In option includes the name of a rule, for example: /In MyGrammar.grxml#MyRule.

  • The file specified by the /RecoConfig option cannot be found, or cannot be opened.

  • There is no file specified by the /RecoConfig option and there is no file named "RecoConfig.xml" in the current directory or in the directory that contains GrammarValidator.exe.

Remarks

Grammar Validator will attempt to load external grammars or rules specified by the uri attribute of a ruleref element to validate their contents. If an externally referenced grammar or rule cannot be loaded (for example, it is behind a firewall or the URI cannot be found), then the tool will emit a warning. If an internally referenced grammar or rule cannot be loaded, then the tool will emit an error.

If a referenced grammar defines a root rule and does not have any publicly scoped rules, then a warning will be emitted. Note that the scope for rule elements is private by default in a grammar. Rules must be declared public explicitly, using the optional attribute setting scope="public".

Additional warnings include:

  • A rule that cannot be reached.

  • Recursion with no outlet (for example, Rule 1 references Rule 2 which references Rule 1).

  • A GRXML-format grammar file in which the encoding element is NOT specified. This is important if characters (for example, "á") are found in the grammar that are not UTF-8 format.

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" in the current directory (the directory for the command line), or in the directory that contains GrammarValidator.exe. The tool will generate an error if you do not supply it with a configuration file.

SAPI Errors

Grammar Validator produces a subset of SAPI errors that describe incorrect logic or syntax found in a grammar document. The following table lists and describes the SAPI errors produced by Grammar Validator.

Error Name

Hexadecimal

Description

SPERR_UNDEFINED_FORWARD_RULE_REF

0x8004501c

A rule reference in a grammar was made to a named rule that was never defined.

SPERR_EMPTY_RULE

0x8004501d

A non-dynamic grammar rule that has no body.

SPERR_GRAMMAR_COMPILER_INTERNAL_ERROR

0x8004501e

The grammar compiler failed due to an internal state error.

SPERR_RULE_NOT_DYNAMIC

0x8004501f

An attempt was made to modify a non-dynamic rule.

SPERR_DUPLICATE_RULE_NAME

0x80045020

A rule name was duplicated.

SPERR_DUPLICATE_RESOURCE_NAME

0x80045021

A resource name was duplicated for a given rule.

SPERR_TOO_MANY_GRAMMARS

0x80045022

Too many grammars have been loaded.

SPERR_CIRCULAR_REFERENCE

0x80045023

Circular reference in import rules of grammars.

SPERR_INVALID_IMPORT

0x80045024

A rule reference to an imported grammar that could not be resolved.

SPERR_ALL_WORDS_OPTIONAL

0x80045027

A grammar rule was defined with a null path through the rule. That is, it is possible to satisfy the rule conditions with no words.

Note Note

This is an old error code, which will not be raised in newer versions of SAPI.

SPERR_RULE_NAME_ID_CONFLICT

0x80045029

A rule exists with matching IDs (names) but different names (IDs).

SPERR_NO_RULES

0x8004502a

A grammar contains no top-level, dynamic, or exported rules. There is no possible way to activate or otherwise use any rule in this grammar.

SPERR_CIRCULAR_RULE_REF

0x8004502b

Rule 'A' refers to a second rule 'B' which, in turn, refers to rule 'A'.

SP_NO_PARSE_FOUND

0x0004502c

Parse path cannot be parsed given the currently active rules.

SPERR_NO_PARSE_FOUND

0x8004502d

Parse path cannot be parsed given the currently active rules.

SPERR_INVALID_FORMAT_STRING

0x80045033

The XML format string for this RULEREF is invalid, e.g. not a GUID or REFCLSID.

SPERR_NO_TERMINATING_RULE_PATH

0x80045036

No Terminating Rule Path.

JScript Syntax Errors

Grammar Validator reports the errors produced as a result of incorrect EcmaScript in tag elements. These errors are shown in the following table.

Error number | Description
1002 | Syntax error
1003 | Expected ':'
1004 | Expected ';'
1005 | Expected '('
1006 | Expected ')'
1007 | Expected ']'
1008 | Expected '{'
1009 | Expected '}'
1010 | Expected identifier
1011 | Expected '='
1012 | Expected '/'
1014 | Invalid character
1015 | Unterminated string constant
1016 | Unterminated comment
1018 | 'return' statement outside of function
1019 | Can't have 'break' outside of loop
1020 | Can't have 'continue' outside of loop
1023 | Expected hexadecimal digit
1024 | Expected 'while'
1025 | Label redefined
1026 | Label not found
1027 | 'default' can only appear once in a 'switch' statement
1028 | Expected identifier, string or number
1029 | Expected '@end'
1030 | Conditional compilation is turned off
1031 | Expected constant
1032 | Expected '@'
1033 | Expected 'catch'
1035 | Throw must be followed by an expression on the same source line
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Phrase Generator Reference Manual

[image]

Phrase Generator Reference Manual
Send Feedback

Phrase Generator is a command-line tool that outputs an exhaustive list, or a filtered list, of the phrases contained in an XML-format grammar.

The Phrase Generator Reference Manual consists of the following topics.

  • Phrase Generator Usage Scenarios

  • Phrase Generator Command-Line Syntax

  • Phrase Generator Input and Output File Format

  • Phrase Generator Error Messages and Format

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Phrase Generator Usage Scenarios

[image]

Phrase Generator Usage Scenarios
Send Feedback

Phrase Generator outputs a list of phrases from a grammar based on parameters that you specify.

You can use Phrase Generator to identify whether your grammar generates phrases that are not expected by your voice application ("over-generation"), whether your grammar does not generate phrases that your voice application does expect ("under-generation"), and whether your grammar generates nonsense phrases. In addition, you can generate a random sampling of phrases (based on rule weights) from a grammar to obtain a test set, or simply for 'sanity checking' the grammar.

The following are some typical scenarios for using Phrase Generator:

  1. You have authored a grammar and used Grammar Validator to verify that it is syntactically correct. Before you invest in testing with utterances, you want to make sure that your grammar recognizes all you intend, but no more. You need to know the following:

    • Does my grammar over-generate phrases thereby increasing the risk of a false recognition?

    • Does my grammar under-generate phrases, increasing the risk of unintended recognition rejections?

    • Will my grammar recognize nonsense phrases? Can I 'sanity check' the phrases to judge whether they are linguistically correct?

  2. Based on the output from another of the grammar tools, you have changed the grammar. Now you need to know:

    • How many more phrases are actually being recognized after I make a change?

  3. You want to test your application with actual voice input.

    • What phrases should testers use to speak to the application so I can verify that it works correctly?

  4. You want to help the speech recognizer to avoid confusing some phrases with others.

    • How can I generate lists of phrases to input to the Confusability tool?

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Phrase Generator Command-Line Syntax

[image]

Phrase Generator Command-Line Syntax
Send Feedback

The command-line syntax for Phrase Generator has the following format.

PhraseGenerator /In <input file name> /Out <output file name> /RecoConfig <configuration file name> /Rule <ID of the rule for which phrases will be generated> /MaxPhrases <number of phrases to generate> /Method <sampling method> /Seed <integer> /DoNotExpand <list of internal rules not to expand> /DoNotExpandExternal

The following table describes the command-line option names and values for Phrase Generator.

Option Name

Description

/In

Required. A string that contains the file name and extension of an XML-based grammar file, for example "MyGrammar.grxml".

The grammar specified by the /In option must be available on the same computer as PhraseGenerator.exe or on a connected local network.

Phrase Generator follows references to rules in external documents and generates phrases for externally referenced rules. External documents containing rules referenced from the input document must be on the same computer as PhraseGenerator.exe or on a local area network to which the computer is connected. References to rules in documents on web servers are not supported.

/Out

Required. A string that contains the file name and extension of the output utterance file, for example MyGrammarOutput.utt.

/RecoConfig

Optional. The name of the configuration file to use for the speech recognition engine. If not specified, the tool will look for a default configuration file named "RecoConfig.xml" in the current working directory and in the directory that contains PhraseGenerator.exe. The tool will generate an error if you do not supply it with a configuration file.

/Rule

Optional. A string that contains the id of the rule to process, for example "MyRule". Phrases are generated for the specified rule and all rules referenced by this rule. If this option is not specified, the phrase generator generates phrases from the root rule of the document specified by the /In option, and all the rules referenced by the root rule.

The id value specified in the /Rule option must be contained in the grammar document that is specified in the /In option.

/MaxPhrases

Optional. Must be specified if the value of the /Method option is SampleByWeight. A string that specifies the maximum number phrases to generate, for example "1000". There is no upper limit to the number of phrases that you can specify in this option. If /MaxPhrases is not specified, Phrase Generator writes the phrases for the root rule and all rules it references, or for the rule specified in the /Rule option and all the rules it references. If the value for /Method is Exhaustive and /MaxPhrases is not specified, Phrase Generator will write up to 100,000 phrases, which is the default value for /MaxPhrases.

/Method

Optional. Indicates the method to be used for extracting phrases. The value can be one of Exhaustive or SampleByWeight. The default value is Exhaustive.

/Seed

Optional. An integer value that is used to generate sample phrases. Only relevant if the /Method value is SampleByWeight which uses the value to generate the results. Reusing the same value will produce the same set of results, unless the input file has changed. If a /Seed value is NOT specified, then the tool will generate its own value and write it both to the console and to the output file when applicable to generation.

/DoNotExpand

Optional. A list of rule names in the input grammar file that should not be expanded in the generated output. In the output, skipped rules appear in square brackets. By default, Phrase Generator attempts to expand all rules, both internal and external to the grammar.

/DoNotExpandExternal

Optional. A Boolean option that does not take a value. If specified, any rule that is external to the input file grammar will not be expanded. In the output, skipped external rules appear in square brackets. By default, this is not enabled.

/?

Optional. Displays a list of acceptable option/value pairs.

Note Note

  • Command-line options are not case-sensitive.

  • Command-line options can be preceded by a forward slash (0x002F), a dash (0x002d), an en dash (0x2013), an em dash (0x2014), or a horizontal bar (0x2015).

  • You can enter option/value pairs in any sequence.

Caution note Caution

If an existing file has the same name as the file name specified by the /Out option, it will be overwritten. The tool does not warn that a file will be overwritten.

Remarks

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" either in the current directory (the directory for the command line) or in the directory that contains PhraseGenerator.exe. Use the configuration file to specify a speech recognition engine to use, to configure the parameters for connecting to it, and to configure its behavior. For more information, see Setting Up the Grammar Development Tools.

If an item element in a grammar file specifies a repeat count of "1-", meaning it can be repeated any number of times, then the tool will continue to generate phrases up to the value specified in /MaxPhrases. If /MaxPhrases is not specified, the tool will generate 100,000 phrases, which is the default setting for /MaxPhrases. In the following example, phrases for the rule "#digit" will be generated until the limit specified in /MaxPhrases or its default limit is reached:

<item repeat="1-">
<ruleref uri="#digit"/>
</item>

Note Note

Depending on system and memory constraints, the tool may be unable to process grammars that contain in excess of 100,000 phrases.

Examples

The following are several usage examples of the Phrase Generator.

Generate all phrases for the grammar's root rule and all rules it references, and output the phrases to the file "MyUtterances.utt":

PhraseGenerator /In MyGrammar.grxml /Out MyUtterances.utt

Generate all phrases for the grammar's root rule and all internal rules it references, and output the phrases to the file "MyUtterances.utt". All external rules will be skipped and will appear in brackets in the output file:

PhraseGenerator /In MyGrammar.grxml /Out MyUtterances.utt /DoNotExpandExternal

Generate 100 random phrases using rule weights for <Rule id="MyRule"> and all rules it references and let the tool generate the value for /Seed:

PhraseGenerator -In MyGrammar.grxml -Out MyUtterances.utt -Rule MyRule -MaxPhrases 100 -Method SampleByWeight

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Phrase Generator Input and Output File Format

[image]

Phrase Generator Input and Output File Format
Send Feedback

Phrase Generator accepts XML-based grammar files as input and generates a list of phrases in an XML file with the ".utt" (utterance) extension. You can generate phrases for either:

  • The root rule of the input file and all the rules referenced by the root rule.

  • A rule that you specify that is not a root rule, and all the rules that it references.

Input File Format

Use grammar documents in XML format that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0 as input for Phrase Generator, for example MyGrammar.grxml. It is an accepted convention to use the ".grxml" file extension for XML-based grammar documents that conform to the SRGS specification.

Required Attributes

A valid XML-format grammar document consists of a legal header followed by a body consisting of a set of legal rule definitions. A legal header in a grammar document must include the xml declaration element and may include an optional DOCTYPE declaration element. These are followed in the header by the root grammar element. Grammar files used as input to the PhraseGenerator command must contain the following required attributes in the root grammar element or the tool will generate an error:

Attribute | Description | Example
version | Attribute of the grammar element. The version of the specification implemented by the grammar. | version="1.0" A grammar that complies with the Speech Recognition Grammar Specification (SRGS) Version 1.0 must declare the version to be "1.0".
xmlns | Attribute of the grammar element. The URI of the namespace for the grammar. | xmlns="http://www.w3.org/2001/06/grammar"
xml:lang | Attribute of the grammar element. The primary language contained by the document and optionally a country or other variation. | xml:lang="en-US" The xml:lang attribute is required if <grammar mode="voice"> or if the mode attribute is omitted, from the grammar element, in which case the value defaults to "voice". The xml:lang attribute is not required if <grammar mode="dtmf">.
Note Note

Grammar files in the Augmented Backus-Naur Form (ABNF) format are not supported.

Example

The following is an example of a valid input grammar document that contains only the minimum required elements and attributes in the document's header, and a simple rule in the body of the document.

XML Copy image Copy Code
<?xml version="1.0"?>
<grammar version="1.0"
xmlns="http://www.w3.org/2001/06/grammar"
xml:lang="en-US">

   <rule id="main">
      <one-of>
         <item> hello </item>
         <item> world </item>
      </one-of>
   </rule>

</grammar>

The document header ends and the body of the grammar document begins with the first Rule element. Grammar files used as input for Phrase Generator can contain optional elements and attributes in the document header, see SRGS Grammar XML Reference (Microsoft.Speech). For more information about elements and attributes in SRGS grammars, see Speech Recognition Grammar Specification Version 1.0.

Note Note

Depending on system and memory constraints, the tool may be unable to process grammars that contain in excess of 100,000 phrases.

Output File Format

PhraseGenerator.exe outputs a list of phrases into an XML document. Phrases are listed in the order processed, though their order may not correspond to the order in which rules are listed in the input file, or in externally referenced grammar documents. The output utterance file contains the following XML elements:

Element | Description
Scenario | The header element for the utterance document, which takes the attribute xml:space. The value for xml:space is always preserve, which preserves white space in the output phrases.
Seed | Contains an integer value that is used to generate phrases when the SampleByWeight method is used. If specified by the user as an option value, it appears in the output file. If not specified by the user, a random value will be assigned by the tool in the output.
Utterance | The parent element for each phrase.
TranscriptText | The semantic content of the phrase, for example "Hello world".
Weight | For any method of generation, a floating point value from 0 to 1 that corresponds to the phrase weight (combining any and all rule weights) of the phrase generated. Notation always follows the W3C xsd:decimal type, specifying "." as the decimal separator regardless of locale.

Example 1

This example shows the output that Phrase Generator produces from a grammar file (PearsGrapes.grxml) that contains a reference to a rule in another grammar file (ApplesOranges.grxml). Phrase generator outputs phrases from rules in both grammar files. The contents of the output utterance file is shown below the contents of the input grammar files.

Below are the contents of the input grammar file PearsGrapes.grxml. This grammar file contains the root rule "main", which references the rule "Fruit" within the grammar and the rule "OtherFruit" in the separate grammar ApplesOranges.grxml.

XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd">

<grammar version="1.0"
   xmlns="http://www.w3.org/2001/06/grammar"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.w3.org/2001/06/grammar
   http://www.w3.org/TR/speech-grammar/grammar.xsd"
   xml:lang="en-US" mode="voice" root="main">

   <!-- rule declarations -->
   <rule id="main" scope="public">
      <one-of>
         <item><ruleref uri="#Fruit"/></item>
         <item><ruleref uri="ApplesOranges.grxml#OtherFruit"/></item>
      </one-of>
         <item> are my favorite fruit </item>
   </rule>

   <rule id="Fruit" scope="public">
      <example> Pears </example>
      <example> Grapes </example>
      <one-of>
         <item> Pears </item>
         <item> Grapes </item>
      </one-of>
   </rule>
</grammar>

Below are the contents of the grammar file ApplesOranges.grxml. Note that this grammar file does not have a root rule and that its rule "OtherFruit" is referenced explicitly from PearsGrapes.grxml.

XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE grammar PUBLIC "-//W3C//DTD GRAMMAR 1.0//EN" "http://www.w3.org/TR/speech-grammar/grammar.dtd">

<grammar version="1.0"
   xmlns="http://www.w3.org/2001/06/grammar"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.w3.org/2001/06/grammar
   http://www.w3.org/TR/speech-grammar/grammar.xsd"
   xml:lang="en-US" mode="voice">

   <rule id="OtherFruit" scope="public">
      <example> Apples </example>
      <example> Oranges </example>
      <one-of>
         <item> Apples </item>
         <item> Oranges </item>
      </one-of>
   </rule>
</grammar>

Now that the input grammars are created, we can run Phrase Generator to output the list of phrases for all the rules referenced by the root rule of the file specified at the /In option to a new file that Phrase Generator creates called MyFavoriteFruits.utt.

The following command-line entry creates the list of all phrases that can be generated from the grammars PearsGrapes.grxml and ApplesOranges.grxml, and writes them to the new file MyFavoriteFruits.utt:

PhraseGenerator /In PearsGrapes.grxml /Out MyFavoriteFruits.utt

Below are the contents written by Phrase Generator into the file MyFavoriteFruits.utt, using the grammars shown above as input.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<Scenario xml:space="preserve">
  <Utterance>
    <TranscriptText>Oranges are my favorite fruit </TranscriptText>
    <Weight>0.25</Weight>
  </Utterance>
  <Utterance>
    <TranscriptText>Apples are my favorite fruit </TranscriptText>
    <Weight>0.25</Weight>
  </Utterance>
  <Utterance>
    <TranscriptText>Grapes are my favorite fruit </TranscriptText>
    <Weight>0.25</Weight>
  </Utterance>
  <Utterance>
    <TranscriptText>Pears are my favorite fruit </TranscriptText>
    <Weight>0.25</Weight>
  </Utterance>
</Scenario>

Example 2 - SampleByWeight

This example shows how to use Phrase Generator with the SampleByWeight method. We will use the following command and a hypothetical confirmation grammar (not shown):

PhraseGenerator.exe -In YesNo.grxml -Out MyUtterances.utt -MaxPhrases 3 -Method SampleByWeight

The command line does not specify a /Seed option. Therefore, Phrase Generator supplies a random value, which displays in the output utterance file, as shown below:

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<Scenario xml:space="preserve">
  <Seed>1713698674</Seed>
  <Utterance>
    <TranscriptText>yeah</TranscriptText>
    <Weight>0.032255451644366766</Weight>
  </Utterance>
  <Utterance>
    <TranscriptText>no</TranscriptText>
    <Weight>0.32255452389424816</Weight>
  </Utterance>
  <Utterance>
    <TranscriptText>yes</TranscriptText>
    <Weight>0.64511906136866892</Weight>
  </Utterance>
</Scenario>

The /Seed value produced by Phrase Generator represents a specific set of results from a specific input file. Re-running the command with a /Seed option value of "4359834", shown below, will produce the exact same set of phrases as above in the output.

PhraseGenerator.exe -In YesNo.grxml -Out MyUtterances.utt -rule MyRule -MaxPhrases 3 -Method SampleByWeight -Seed 4359834

You can use the /Seed value to determine whether or not a grammar and the weight values specified in its Item elements have been changed. Unless the input file has changed, the same command with the same /Seed value will generate the same set of phrases and phrase weights.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Phrase Generator Error Messages and Format

[image]

Phrase Generator Error Messages and Format
Send Feedback

Phrase Generator displays error messages and execution summaries in the console. It checks that all externally referenced grammars exist and attempts to load them. The tool halts execution and displays an error message when it encounters an error that prevents successful completion of a command. The tool displays an execution summary for commands that have been processed successfully.

For errors detected in an input file, error messages contain the following information.

  • File name (if applicable)

  • Number of the line that contains the error (if applicable)

  • Error code (if applicable)

  • Error description

Example Errors

Error opening input file:

testexterna.grxml: Problem opening file MyGrammar.grxml -2147024894

Error opening an externally referenced file:

C:\Program Files (x86)\Microsoft Speech Platform SDK\Tools\MyExternalGrammar.grxml 13: [0xC00CE505] - A name contained an invalid character.-2147201021

XML syntax error in input file:

MyGrammar.grxml (24): ERROR: [0xC00CE56D] - End tag 'rule' does not match the start tag 'item'. -2147201021

Error following a rule reference:

Could not find rule 'frui' in grammar MyExternalGrammar.grxml aborting phrase generation

Output file name exists and is read-only:

Problem creating output file MyPhrases.utt. Exception Access to the path 'C:\Program Files (x86)\Microsoft Speech Platform SDK\Tools\MyPhrases.utt ' is denied.

Example Execution Summaries

All phrases for the command were output successfully to MyPhrases.utt:

Successfully output 26 phrases to MyPhrases.utt

The value specified for /MaxPhrases was 60 but only 44 phrases could be generated from the rule specified, and were written to MyPhrases.utt:

Successfully output 44 phrases of 60 possible to MyPhrases.utt

Remarks

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" in the current directory (the directory for the command line), or in the directory that contains PhraseGenerator.exe. The tool will generate an error if you do not supply it with a configuration file.

Phrase Generator converts the input file and any external files it references to CFG format before generating phrases. Consequently, you may also see errors that are generated by this conversion. For a list of errors and warnings that may display as a result of converting grammar files to CFG format, see Grammar Validator Error Messages and Format.

Depending on system and memory constraints, the tool may be unable to process grammars that contain in excess of 100,000 phrases.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Check Phrase Reference Manual

[image]

Check Phrase Reference Manual
Send Feedback

Using the Check Phrase command-line tool, you can determine whether a grammar contains a given phrase and retrieve information about the returned phrase.

The Check Phrase Reference Manual contains the following topics:

  • Check Phrase Usage Scenarios

  • Check Phrase Command-Line Syntax

  • Check Phrase Input and Output File Format

  • Check Phrase Error Messages and Format

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Check Phrase Usage Scenarios

[image]

Check Phrase Usage Scenarios
Send Feedback

You can use Check Phrase to determine whether a grammar contains a given phrase. Check Phrase also returns the semantic interpretation (that is, the emulated recognition result) for a phrase found in a grammar. The tool provides answers to the following questions:

You are debugging a large or complex grammar or a grammar whose contents you have recently changed. You need to know the following:

  • Is this phrase in the grammar?

  • If so, what are the semantics and the pronunciation of the phrase?

  • Which rule tree was used to generate the phrase, its pronunciation, and semantics?

You specify the phrase that you want to check, the grammar to search, and a configuration file for the recognition engine. Check Phrase is particularly helpful when debugging a large or complex grammar. You can optionally specify a rule name in a grammar to limit the scope of the operation. See Check Phrase Command-Line Syntax.

Given the identical input phrase, and the identical grammar to check, Check Phrase will produce the same output each time. This makes the tool very useful for determining whether a change in a grammar has affected whether a phrase is recognized.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Check Phrase Command-Line Syntax

[image]

Check Phrase Command-Line Syntax
Send Feedback

The command-line syntax for CheckPhrase.exe has the following format.

CheckPhrase /In <input file name> /Phrase <input phrase> /RecoConfig <configuration file name> /Rule <rule ID> /Out <output file name>

The following table describes the command-line option names and values for Check Phrase.

Option Name | Description
/In | Required. The file name and extension of a grammar file. The tool accepts the following file formats: .grxml (grammar XML) and .cfg (compiled grammar). For example "MyGrammar.grxml", or "MyCompiledGrammar.cfg". Input files in other formats will generate an error.
/Phrase | Required. The phrase for which you want to determine whether it exists in the grammar and to receive emulated recognition results. Phrases containing multiple, space-delimited words must be enclosed in parentheses. For example: /Phrase "this phrase".
/RecoConfig | Optional. The name of the configuration file to use for the speech recognition engine. If not specified, the tool will look for a default configuration file named "RecoConfig.xml" in the current working directory and in the directory that contains CheckPhrase.exe. The tool will generate an error if you do not supply it with a configuration file.
/Rule | Optional. The ID of the rule from which analysis should begin. You can use this option for grammars that contain a set of unrelated rules, such as a grammar library. If no rule is specified, the root rule of the grammar is used.
/Out | Optional. The name of the file to which the results will be written. The output file provides more detailed results about grammar parsing than those that are written to the console, including pronunciation of the input phrase that is used in emulation. The output file is in XML format and uses elements optimized to describe utterances. If no file is specified, the tool writes an abbreviated version of the output to the console.
/? | Optional. Displays a list of acceptable option/value pairs.
Note Note

  • Command-line options and values are not case-sensitive.

  • Command-line options can be preceded by a forward slash (0x002F), a dash (0x002d), an en dash (0x2013), an em dash (0x2014), or a horizontal bar (0x2015).

  • You can enter option/value pairs in any sequence.

Caution note Caution

If an existing file has the same name as the file name specified by the /Out option, it will be overwritten. The tool does not warn that a file will be overwritten.

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" either in the current directory (the directory for the command line) or in the directory that contains CheckPhrase.exe. Use the configuration file to specify a speech recognition engine to use, to configure the parameters for connecting to it, and to configure its behavior. For more information, see Setting Up the Grammar Development Tools.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Check Phrase Input and Output File Format

[image]

Check Phrase Input and Output File Format
Send Feedback

Check Phrase takes as input an XML-based grammar file, a phrase to analyze, and a configuration file for the recognition engine. You specify the phrase to check on the command line when you run the tool. The tool writes a summary to the console that includes the input phrase and its semantics, and optionally writes detailed results of emulated recognition for the input phrase to an XML file.

Input File Format

Check Phrase accepts the following file formats for input grammar files:

  • Grammar documents in XML format that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0, for example "MyGrammar.grxml". It is an accepted convention to use the ".grxml" file extension for XML-based grammar documents that conform to the SRGS specification.

  • Compiled grammar files in CFG format, for example "MyCompiledGrammar.cfg". See the Compile Grammar Reference Manual for information about compiling grammar files.

Note Note

Input files in other formats will generate an error.

Example

The following is an example of a valid input grammar document in XML format that contains only the minimum required elements and attributes in the document's header, and a simple rule in the body of the document.

XML Copy image Copy Code
<?xml version="1.0"?>
<grammar version="1.0"
xmlns="http://www.w3.org/2001/06/grammar"
xml:lang="en-US" root="main">

   <rule id="main">
      <one-of>
         <item> hello </item>
         <item> world </item>
      </one-of>
   </rule>

</grammar>

A valid XML-format grammar document consists of a legal header followed by a body consisting of a set of legal rule definitions. The document header ends and the body of the grammar document begins with the first rule element. Grammar files used as input for Check Phrase can contain optional elements and attributes in the document header, see SRGS Grammar XML Reference (Microsoft.Speech). For more information about elements and attributes in SRGS grammars, see Speech Recognition Grammar Specification Version 1.0.

Output File Format

The tool writes a summary of the analysis to the console and generates complete results of the analysis to an XML file.

Summary Output to the Console

When the analysis is complete, a summary containing the following information displays in the console:

  • Whether the phrase is in the grammar.

  • The semantics for the phrase (if the phrase is in the grammar and the result interpretation is a literal). If the semantics for the phrase are complex, the name of the output file.

Using the grammar example above and the phrase "hello" as inputs, the following is an example of the summary output to the console:

Info: Successfully parsed "hello"

Info: Successfully output details to "HelloWorldGrammarOutput.utt"

Processing Complete: 0 Error(s). 0 Warning(s).

Check Phrase Output File

Check Phrase generates detailed results of the analysis to an output file in XML format. The output file includes the following information:

  • The phrase input for emulation.

  • Whether the phrase was successfully parsed (that is, emulated) by the engine and the grammar (that is, matched).

  • The semantics for the phrase: either a string for a literal result, or XML markup that describes complex semantics.

  • The pronunciation of an emulated match.

  • The identifier of the rule used to match the phrase, and the location of the grammar file that contains it.

Example

The following example illustrates the output format of the Check Phrase tool when the input is the phrase "hello" and it matches the example grammar above.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<Scenario xml:space="preserve">

<Utterance>
<TranscriptText>hello</TranscriptText>
<InGrammar>True</InGrammar>
<TranscriptSemantics>hello</TranscriptSemantics>
<TranscriptPronunciation>H EH L O</TranscriptPronunciation>
<TranscriptRuleTree>
<Rule id="main" uri="HelloWorldGrammar.grxml">hello</Rule>
</TranscriptRuleTree>
</Utterance>

</Scenario>

Remarks

For this release, Check Phrase returns only the top result if there are multiple matches for an input phrase.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Check Phrase Error Messages and Format

[image]

Check Phrase Error Messages and Format
Send Feedback

Check Phrase displays messages for errors, warnings, and other information in the console, as well as execution summaries. The tool halts execution and displays an error message when it encounters an error that prevents successful completion of a command. The tool returns EXIT_FAILURE (1) when it encounters an error and returns EXIT_SUCCESS (0) when it completes a command successfully. Whether or not a command completes successfully, the tool displays an execution summary after attempting to process a command.

Messages will have the following format:

<Input file name>(Line number): <Message type> <Error code>: <Error description>

Check Phrase will throw an error if it encounters any of the following conditions:

  • The grammar file specified by the /In option cannot be found, or cannot be opened.

  • The grammar file specified by the /In option is not properly formed and cannot be compiled.

  • The grammar file specified by the /In option includes the name of a rule, for example: /In MyGrammar#MyRule.

  • The phrase specified in the /Phrase option contains a syntax error, for example multiple words that are not enclosed in parentheses.

  • The file specified by the /RecoConfig option cannot be found, or cannot be opened.

  • There is no file specified by the /RecoConfig option and there is no file named "RecoConfig.xml" in the current directory.

  • The rule specified by the /Rule option cannot be found, or cannot be loaded, or contains invalid logic.

  • The /Out option is not specified with a filename.

Caution note Caution

If an existing file has the same name as the file name specified by the /Out option, it will be overwritten. The tool does not warn that a file will be overwritten.

Remarks

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" in the current directory (the directory for the command line), or in the directory that contains CheckPhrase.exe. The tool will generate an error if you do not supply it with a configuration file.

Check Phrase converts the input grammar file and any external grammar files it references to CFG format before performing analysis. Consequently, you may also see errors that are generated by this conversion. For a list of errors and warnings that may display as a result of converting grammar files to CFG format, see Grammar Validator Error Messages and Format.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Confusability Reference Manual

[image]

Confusability Reference Manual
Send Feedback

Confusability identifies phrases in a grammar that may generate false acceptances on recognition because of similarity to other phrases in the grammar.

The Confusability Reference Manual contains the following topics:

  • Confusability Usage Scenarios

  • Confusability Command-Line Syntax

  • Confusability Input and Output File Format

  • Confusability Error Messages and Format

  • Whitepaper: Analyzing Grammars for Confusable Phrases

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Confusability Usage Scenarios

[image]

Confusability Usage Scenarios
Send Feedback

The Confusability tool identifies phrases in a grammar that are phonetically similar, which may reduce the speech recognition accuracy of your application. You will typically use the Confusability tool in the following scenarios:

  • You have authored a grammar and used Grammar Validator to verify that it is syntactically correct. Before you invest in testing with utterances, you want to make sure that your grammar does not contain phonetically ambivalent phrases that could cause misrecognition.

  • You want to add new phrases to an existing grammar, but you want to make sure that they will not be confused with phrases already in the grammar.

The tool helps provide answers to the following questions:

  • Which phrases are phonetically similar?

  • Which phrases are likely to result in false accepts?

  • What is the probability that one phrase will be falsely accepted for another phrase in the grammar?

Confusability informs you whether the recognizer cannot reliably distinguish between multiple in-grammar phrases with distinct semantic meanings. Each result identifies a phrase that may be incorrectly recognized (and its semantics), the phrase with which it may be confused (and its semantics), and provides a metric for how likely it is that the confusion will occur. When calculating the probability that a phrase will be incorrectly recognized, the tool takes into account the weight assigned to each phrase.

You can run the confusability analysis on an entire grammar, or you can limit the scope for the analysis to a specific rule or to a subset of phrases in a grammar, specified in a list that you provide. The Confusability tool will detect if a grammar contains any of the following features that may adversely affect recognition accuracy:

  • Entries that cannot reliably be distinguished from each other by the recognizer

  • Homonyms

  • Duplicate entries that represent different semantics

  • Entries with misleading orthography, leading the engine to generate incorrect pronunciations

You can also use the Confusability tool to determine whether new phrases, if added to a grammar, will be confused with other entries already in the grammar. Pass in the list of new phrases using the /PhraseList option on the command line. See Confusability Command-Line Syntax.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Confusability Command-Line Syntax

[image]

Confusability Command-Line Syntax
Send Feedback

The command-line syntax for Confusability.exe has the following format.

Confusability /In <input file name(s)> /RecoConfig <configuration file name> /ComparisonType <type> /Out <output file name> /SemanticPath <XPath> /Rule <rule ID> /PhraseFile <list of input phrases>

The following table describes the command-line option names and values for the Confusability tool.

Option Name

Description

/In

Required. The file name and extension of one or more grammar files. Separate multiple file names with a space. The tool accepts the following file formats: .grxml (grammar XML), and .cfg (compiled grammar). For example "MyGrammar.grxml" or "MyCompiledGrammar.cfg". Input files in other formats will generate an error. You cannot specify a rule as part of the file name, for example "MyGrammar.grxml#MyRule ". Use the /Rule option.

/RecoConfig

Optional. The name of the configuration file to use for the speech recognition engine. If not specified, the tool will look for a default configuration file named "RecoConfig.xml" in the current working directory and in the directory that contains Confusability.exe. The tool will generate an error if you do not supply it with a configuration file.

/ComparisonType

Optional. Specifies whether the output takes into consideration the semantics of a false accept recognition. Accepts the following values:

  • CompareSemantics. (Default) Confusable terms will not be emitted when their semantics are the same (as specified by the SemanticPath option).

  • IgnoreSemantics. All confusable terms are emitted, whether or not their semantics match.

/Out

Required. The name of the file to which the results will be written. The output file provides detailed information about pairs of phrases in a grammar that may be confused during speech recognition. The output file is in XML format and uses elements optimized to describe utterances. The file is empty if no confusable phrases were identified.

/SemanticPath

Optional. Required when the value for /ComparisonType is CompareSemantics. Specifies the XML node(s) to use when comparing semantics. If the value for this option begins with a forward slash, you must precede it with an additional forward slash, for example //MyXmlNode.

By default, every node is used to compare whether the semantics match. If a string containing a single period "." is specified, then only literal semantics are compared.

/Rule

Optional. The identifier of the rule from which analysis should begin. The option is only valid when the /In option specifies a single grammar.

You can use this option when you specify a single grammar at the /In option that contains a set of unrelated rules, such as a grammar library. If no rule is specified, the root rule of the grammar is used. If using WebReco, this reference cannot point to a rule in a file on the local computer. You can also limit the scope of confusability analysis by specifying a set of phrases. See the /PhraseFile option.

/PhraseFile

Optional. An XML file that specifies the set of phrases on which to run the confusability analysis. Use this option to perform confusability analysis on a subset of one or more grammars, or on phrases that are out-of-grammar. The referenced file can contain up to 100,000 phrases. When not specified, the Confusability tool generates a list of up to 100,000 phrases in the specified grammar and performs its analysis on the entire list. See the Phrase Generator Reference Manual for help in generating a subset of phrases from a grammar. You can also limit the scope of confusability analysis by specifying a rule. See the /Rule option.

/?

Optional. Displays a list of acceptable option/value pairs.

Note Note

  • Command-line options and values are not case-sensitive.

  • Command-line options can be preceded by a forward slash (0x002F), a dash (0x002d), an en dash (0x2013), an em dash (0x2014), or a horizontal bar (0x2015).

  • You can enter option/value pairs in any sequence.

Caution note Caution

If an existing file has the same name as the file name specified by the /Out option, it will be overwritten. The tool does not warn that a file will be overwritten.

Remarks

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" either in the current directory (the directory for the command line) or in the directory that contains Confusability.exe. Use the configuration file to specify a speech recognition engine to use, to configure the parameters for connecting to it, and to configure its behavior. For more information, see Setting Up the Grammar Development Tools.

You can specify both a rule and a phrase file to analyze a list of phrases for confusability against a specific rule in a grammar. The following example is a legal command-line entry:

XML Copy image Copy Code
Confusability /In MyGrammar.grxml /Out MyOutputFile.xml /Rule MyRule /PhraseFile MyUtterances.utt /RecoConfig MyRecoConfig.xml

The following is a command-line example that uses the /SemanticPath option. Note the additional forward slash preceding the parameter (/Minute) for /SemanticPath.

Copy image Copy Code
Confusability.exe -In MyGrammar.grxml -SemanticPath //Minute -Out MyOutputFile.utt -RecoConfig MyRecoConfig.xml
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Confusability Input and Output File Format

[image]

Confusability Input and Output File Format
Send Feedback

The Confusability tool accepts as input an XML-based grammar file and a configuration file for a recognition engine. You can optionally specify the identifier for a rule in the grammar, or provide a list of phrases to analyze in a separate XML document. The tool performs the confusability analysis on the entire grammar, or on a rule within the grammar (if specified), or on a separate list of phrases (if supplied). The tool writes a summary of the analysis to the console and generates complete results of the analysis to an XML file.

Input File Format

Confusability accepts the following file formats for input grammar files:

  • Grammar documents in XML format that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0, for example "MyGrammar.grxml". It is an accepted convention to use the ".grxml" file extension for XML-based grammar documents that conform to the SRGS specification.

  • Compiled grammar files in CFG format, for example "MyCompiledGrammar.cfg". See the Compile Grammar Reference Manual for information about compiling grammar files.

Note Note

Input files in other formats will generate an error.

Example Input Grammar File

The following is an example of a valid input grammar document in XML format that contains only the minimum required elements and attributes in the document's header, and a simple rule in the body of the document.

XML Copy image Copy Code
<?xml version="1.0"?>
<grammar version="1.0"
xmlns="http://www.w3.org/2001/06/grammar"
xml:lang="en-US" root="main">

   <rule id="main">
      <one-of>
         <item> to </item>
         <item> two </item>
      </one-of>
   </rule>

</grammar>

A valid XML-format grammar document consists of a legal header followed by a body consisting of a set of legal rule definitions. The document header ends and the body of the grammar document begins with the first rule element. Grammar files used as input for Confusability can contain optional elements and attributes in the document header, see SRGS Grammar XML Reference (Microsoft.Speech). For more information about elements and attributes in SRGS grammars, see Speech Recognition Grammar Specification Version 1.0.

Note Note

  • The Confusability tool does NOT use the custom pronunciation (if specified) to create a pronunciation for a word. It uses only the lexical form of a word to create a pronunciation.

  • Confusability DOES use custom pronunciations (if specified) when searching for confusable phrases for pronunciations it created.

  • You can specify custom pronunciations either inline in XML-format grammars, or in a lexicon that is linked to a grammar. See Using Custom Pronunciations for more information.

  • The lexical form of a word may be unmarked text, or the contents of an item Element (Microsoft.Speech) or a token Element (Microsoft.Speech).

Specifying a List of Phrases

Using the /PhraseFile option, you can specify a list of phrases on which to perform the confusability analysis. The list of phrases may contain phrases that are not in the grammar. We recommend that you use Phrase Generator to produce the list of phrases for input to the Confusability tool. See Phrase Generator Reference Manual. The following is an example of an input file that contains a list of phrases to check against the grammar shown above. Note that the second phrase is not in the grammar.

Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<Scenario>
  <Utterances>
    <Utterance>
      <TranscriptText>to</TranscriptText>
    </Utterance>
    <Utterance>
      <TranscriptText>too</TranscriptText>
    </Utterance>
  </Utterances>
</Scenario>
Note Note

  • The maximum number of phrases that the confusability tool will process is 100,000. The tool will exit if it reaches this threshold.

  • The confusability tool ignores custom pronunciations included in a list of phrases used as input to the /PhraseFile option.

Output File Format

The Confusability tool writes a summary of the analysis to the console and generates complete results of the analysis to an XML file.

Summary Output to the Console

When the analysis is complete, a summary containing the following information displays in the console:

  • The total of all phrases analyzed. Depending on which options were specified on the command line, the total represents either all the phrases in the grammar, or all the phrases from a rule within the grammar, or all the phrases in the separate list of phrases.

  • A count of phrases that generated in-grammar false accepts.

  • Whether the output file was successfully generated.

The following is an example of the summary output to the console:

Info: 3 phrases analyzed.

Info: 2 phrases found with confusability greater than zero.

Info: Successfully output details to "MyOut.xml"

Processing Complete: 0 Error(s). 0 Warning(s).

Confusability Output File

The Confusability tool generates detailed results of the analysis to an output file in XML format. The output file contains each input phrase (from the phrase file or generated from the grammar) that has some likelihood of being confused by the recognition engine with another phrase in the grammar. The output file includes the following information for each input phrase:

Output File Element | Description
TranscriptText | The input phrase on which analysis was performed.
TranscriptSemantics | The semantics of the input phrase (for in-grammar phrases only).
TranscriptPronunciation | The pronunciation of the input phrase (for in-grammar phrases only).
RecoResultText | The phrase that the engine may confuse with the input phrase, causing a false acceptance.
RecoResultSemantics | The semantics of the phrase that the engine may confuse with the input phrase.
RecoResultRuleTree | The grammar and rule name from which the recognition occurred.
RecoResultPronunciation | The pronunciation of the phrase that the engine may confuse with the input phrase.
RecoResultConfidence | A metric that indicates the probability that the input phrase will be confused with the other phrase.
InGrammar | Whether the phrase is in-grammar (for out-of-grammar phrases only).

Example

The following example illustrates the output that the Confusability tool generates using the grammar and phrase file examples shown above as input.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<Scenario xml:space="preserve">
  <Utterances>
    <Utterance id="1">
      <TranscriptText>to</TranscriptText>
      <TranscriptSemantics ms:typespace="ECMA-262" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma" />
      <TranscriptPronunciation>T O</TranscriptPronunciation>
      <RecoResultText>two</RecoResultText>
      <RecoResultSemantics ms:typespace="ECMA-262" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma" />
      <RecoResultRuleTree>
        <Rule id="main" uri="file:///C:/temp/grammars/Test.grxml">two</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>T U</RecoResultPronunciation>
      <RecoResultConfidence>0.4486466</RecoResultConfidence>
    </Utterance>
    <Utterance id="2">
      <TranscriptText>too</TranscriptText>
      <RecoResultText>to</RecoResultText>
      <RecoResultSemantics ms:typespace="ECMA-262" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma" />
      <RecoResultRuleTree>
        <Rule id="main" uri="file:///C:/temp/grammars/Test.grxml">to</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>T U</RecoResultPronunciation>
      <RecoResultConfidence>1.0000000</RecoResultConfidence>
      <InGrammar>False</InGrammar>
    </Utterance>
    <Utterance id="3">
      <TranscriptText>too</TranscriptText>
      <RecoResultText>two</RecoResultText>
      <RecoResultSemantics ms:typespace="ECMA-262" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma" />
      <RecoResultRuleTree>
        <Rule id="main" uri="file:///C:/temp/grammars/Test.grxml">two</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>T U</RecoResultPronunciation>
      <RecoResultConfidence>0.4822275</RecoResultConfidence>
      <InGrammar>False</InGrammar>
    </Utterance>
  </Utterances>
</Scenario>

Remarks

It cannot be assumed that the value for RecoResultConfidence will be the same if the confused phrase is used as the input phrase. In the example above, submitting the word "to" returned the word "two" in the first utterance with a RecoResultConfidence of 0.4486466. If we submit "two" as input for analysis, the tool will return "to", but the value for RecoResultConfidence may be different.

Item weights affect the simulated set of results, such that items with low weights are less likely to be a confused result.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Confusability Error Messages and Format

[image]

Confusability Error Messages and Format
Send Feedback

Confusability displays messages for errors, warnings, and other information in the console, as well as execution summaries. The tool halts execution and displays an error message when it encounters an error that prevents successful completion of a command. The tool returns EXIT_FAILURE (1) when it encounters an error and returns EXIT_SUCCESS (0) when it completes a command successfully. Whether or not a command completes successfully, the tool displays an execution summary after attempting to process a command.

Messages will have the following format:

<Input file name>(Line number): <Message type> <Error code>: <Error description>

Confusability will throw an error if it encounters any of the following conditions:

  • The grammar file specified by the /In option cannot be found, or cannot be opened.

  • The grammar file specified by the /In option is not properly formed and cannot be compiled.

  • The grammar file specified by the /In option includes the name of a rule, for example: /In MyGrammar#MyRule.

  • The file specified in the /PhraseFile option cannot be found, or cannot be opened.

  • The file specified in the /PhraseFile option does not contain a series of utterance elements with child TranscriptText elements, or is otherwise not properly structured.

  • The file specified by the /RecoConfig option cannot be found, or cannot be opened.

  • There is no file specified by the /RecoConfig option and there is no file named "RecoConfig.xml" in the current directory.

  • The rule specified by the /Rule option cannot be found, or cannot be loaded, or contains invalid logic.

  • The /Out option is not specified with a filename.

Caution note Caution

If an existing file has the same name as the file name specified by the /Out option, it will be overwritten. The tool does not warn that a file will be overwritten.

Remarks

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" in the current directory (the directory for the command line), or in the directory that contains Confusability.exe. The tool will generate an error if you do not supply it with a configuration file.

Confusability converts the input grammar file and any external grammar files it references to CFG format before performing analysis. Consequently, you may also see errors that are generated by this conversion. For a list of errors and warnings that may display as a result of converting grammar files to CFG format, see Grammar Validator Error Messages and Format.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Whitepaper: Analyzing Grammars for Confusable Phrases

[image]

Whitepaper: Analyzing Grammars for Confusable Phrases
Send Feedback

This whitepaper describes how developers of speech-enabled applications can use Microsoft's Confusability.exe tool to detect phrases in grammars that may be confused with each other when processed by a Microsoft speech recognition engine.

Confusable phrases in grammars may cause misrecognition of speech input to an application and degrade the experience of its users. You will find discussion of issues in grammar development that the Confusability tool can and cannot help you to solve, in addition to guidance about how to leverage the results of its analysis to optimize the speech recognition experience for end-users.

Intended for the developer dealing with speech and grammar development, this whitepaper answers the following questions about the Confusability.exe tool:

  1. "What does the tool do?"

  2. "At what stage of grammar development should I use it?"

  3. "How do I use the tool?"

  4. "How do I apply the results?"

Part I: "What does the tool do?"

Confusability.exe analyzes a set of one or more grammars for phrases that could potentially be misrecognized for other phrases in the grammar(s). That is, the tool detects the risk that one phrase may be falsely accepted for another phrase.

What do we mean by "confusable" phrases? Here's an example: Suppose that you create an application in which there's a state that's listening for an end-user to say either "fight" or "bite." No problem right? When an end-user says "fight" she will draw a sword, and when the user says "bite" she shows her teeth. But what if sometimes when the user says "fight", the recognizer thinks it heard "bite"? In this case, we'd call these two phrases "confusable". In the world of speech science, confusable phrases are known as an "in-grammar false accepts", but here, we'll just refer to them as confusable phrases.

As a developer, you want to know before you ship your application whether you've created a grammar, or a set of simultaneously active grammars, that contains phrases which have a risk of being confused with other phrases in the grammar(s). And that's where Confusability.exe can help. If confusable phrases are detected, you may choose to alter your design or to invest more time in testing the performance of the two phrases in your application.

The tool may detect the following types of confusable phrases:

  • Homonyms (for example "fly it" and "flight"; "bare" and "bear")

  • Near homonyms or rhyming phrases (for example "bag it" and "tag it")

  • Unintuitive confusable phrases that the recognizer identifies as having overlapping acoustic similarities (for example "stop" and "up")

Although the tool will detect the potential for confusability in your grammars, there are some caveats to understanding its use:

  1. The tool is not a substitute for collecting end-user speech in a test production environment. The best insight into how speech and grammars perform will always be gained through their interaction with speech from end-users of your application.

  2. The tool's results are not always intuitive and may not flag phrases that we, as native speakers, think are confusable. That is, just because two phrases rhyme to you and me, it does not mean they will be flagged by the tool.

  3. Similarly, just because the tool doesn't flag terms as confusable does not mean that some end-users won't experience two phrases as being confusable under some conditions. Again, there are many factors in a production environment such as noise and speaker variation that can ultimately affect confusability.

  4. The results may differ based on which speech recognition engine you use, or on its version. For example, you might find confusable results with one recognizer but not another. Also, if you use the same recognizer that you used for a previous analysis, but there have been changes or updates to the recognizer and its components (such as its acoustic model), then this may produce a different result when run against the same grammar.

However, despite the above mentioned caveats, Confusability.exe can be a helpful tool in the grammar development workflow. The tool allows you to increment the performance of your grammar as a step toward making it work as expected.

Part II: "When should I use the tool?"

Use the Confusability.exe tool early in the development process, after you have a functional grammar, but before you've gone to the trouble of setting up a test production environment. The tool provides a sanity-check-level validation of the design of a grammar or an application state, answering questions such as:

  • Did I inadvertently create a state in the application that has multiple instructions to listen for the same phrase? For example, you may have accidentally put the same phrase in two different grammars or rules which could result in unexpected application behavior depending on whether their semantics are different.

  • Are there unintuitive phrases that could lead to users saying one thing, and the recognizer creating a match to a different phrase in the grammar?

In addition, you may run the tool on grammars following a major update or change to the recognition engine and its environment.

Part III: "Ok, now how do I use it?"

To get started, let's assume that you have your developer environment set up with the following components:

  1. You've installed the Microsoft Speech Platform SDK 11.

  2. You've configured the grammar development tools to target the recognizer that your application will use.

  3. You've authored a functional grammar that you want to analyze for confusability.

From the command line, you run the tool as follows:

Copy image Copy Code
> Confusability.exe -In <GrammarFileName > -Out <OutputFilename> -RecoConfig <RecognizerConfigurationFilename>

Note that there are additional options, but for a basic scenario with a single simple grammar we just need these three parameters. Also, if you've set up the tools to work with a recognizer via the "RecoConfig.xml" file (step 2), you don't need to specify the RecoConfig parameter at the command line as the tool will look for "RecoConfig.xml" if not specified. See Setting Up the Grammar Development Tools.

Note Note

The tool can take several minutes to process a grammar that contains up to 100 phrases, depending on your machine's hardware. Larger grammars will take longer.

An intuitive example: Dog Actions

Imagine that we have an application in which the end-user is controlling a dog avatar using her voice. After consideration of the application's design, we've arrived at a single grammar that maps five different phrases to five different actions. Our grammar is as follows:

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>

<!-- Input to Confusability.exe: "DogControl.grxml" -->

<grammarmode="voice"
  root="DOG_ACTIONS"
  tag-format="semantics/1.0-literals"
  version="1.0" xml:lang="en-US"
  xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="DOG_ACTIONS" scope="public">

    <one-of>

      <item>
        Walk
        <tag> walk </tag>
      </item>

      <item>
        Run
        <tag> run </tag>
      </item>

      <item>
        Lay down
        <tag> lay down </tag>
      </item>

      <item>
        <one-of>
          <item> Bite </item>
          <item> Snap </item>
        </one-of>
        <tag> bite </tag>
      </item>

      <item>
      Fight
        <tag> fight </tag>
      </item>

    </one-of>

  </rule>

</grammar>

To analyze the DogControl.grxml grammar for confusable phrases, you enter the following on the command line:

Copy image Copy Code
> Confusability.exe -In DogControl.grxml -Out DogControl.grxml.confusability.xml
-RecoConfig RecoConfig.xml

The tool will output the following to the console:

Info: Successfully output 6 phrases

Info: 6 phrases analyzed.

Warning: 2 phrases found with confusability greater than zero.

Info: Successfully output details to "DogControl.grxml.confusability.out.xml"

Processing Complete: 0 Error(s). 1 Warning(s)

The Warning is the key here, indicating that there are two phrases with detected risk for confusability. Opening the output file (DogControl.grxml.confusability.out.xml) reveals the following:

Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<Scenario xml:space="preserve">
  <Utterances>

    <Utterance id="1">
      <TranscriptText>Fight</TranscriptText>
      <TranscriptSemantics>fight</TranscriptSemantics>
      <TranscriptPronunciation>F AI T</TranscriptPronunciation>
      <RecoResultText>Bite</RecoResultText>
      <RecoResultSemantics>bite</RecoResultSemantics>
      <RecoResultRuleTree>
        <Rule id="DOG_ACTIONS" uri="file:///C:/Tools/DogControl.grxml">Bite</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>B AI T</RecoResultPronunciation>
      <RecoResultConfidence>0.1304087</RecoResultConfidence>
    </Utterance>

    <Utterance id="2">
      <TranscriptText>Bite</TranscriptText>
      <TranscriptSemantics>bite</TranscriptSemantics>
      <TranscriptPronunciation>B AI T</TranscriptPronunciation>
      <RecoResultText>Fight</RecoResultText>
      <RecoResultSemantics>fight</RecoResultSemantics>
      <RecoResultRuleTree>
        <Rule id="DOG_ACTIONS" uri="file:///C:/Tools/DogControl.grxml">Fight</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>F AI T</RecoResultPronunciation>
      <RecoResultConfidence>0.5065575</RecoResultConfidence>
    </Utterance>

  </Utterances>
</Scenario>

For each Utterance element, we can compare the TranscriptText element (the expected recognition result) with the RecoResultText element (the actual recognition result), indicating that "Fight" and "Bite" are at risk for confusion. This does not mean that users who say "Fight" will always be recognized as having said "Bite", but it does mean that there is a possibility of these phrases being misrecognized for each other.

The tool provides a metric that quantifies the degree of this risk via the RecoResultConfidence element. If you have a set of results with many possible confusions, you should pay more attention to phrases with values closer to "1" in the RecoResultConfidence element, and consider changing those phrases. At a higher level, the takeaway is that both phrases have a predicted risk of being confusable for some users some of the time.

Note Note

The value for RecoResultConfidence in the output of the Confusability tool is not related to the confidence score that the speech recognition engine assigns to recognition results. The Confusability tool does not take into account the confidencelevel setting of the speech recognition engine or the confidence score that it assigns to individual recognition results. It creates an independent metric that estimates the risk of confusability.

In-depth detail: Why "Bite" is more confusable with "Fight" than the other way around

You may also be asking why the results predict "Bite" to be more confusable with "Fight" than the other way around. While "Fight" and "Bite" may be similar sounding to human ears, a speech recognizer has different sensitivity to speech sounds.

To explain the difference, the following diagram provides a hypothetical schema representing each phrase's acoustic representation in a normalized distribution. Note that the Confusability tool does not generate diagrams.

The Inequality of Risk for Confusable Phrases

Figure 1: The Inequality of Risk for Confusable Phrases

The above graph visually describes why the tool can predict that two phrases will be confusable, but not at an equal level of risk. For example, with the "Bite" vs. "Fight" phrases - we see an overlap in the features representing both phrases.

Because "Fight" has a smaller variance in its distribution, it has a greater chance of being recognized for itself when spoken. "Bite", on the other hand, tends to have an acoustic representation with a lot of variance. This means that when "Bite" is spoken it has a higher chance of being mistaken for "Fight".

Part IV: "How do I apply the results of Confusability analysis?"

Based on the tool results, there are several actions that you can take:

  1. Consider altering the grammar design to mitigate the risk of confusion. For one of the confusable pairs, choose a different phrase that means the same thing. For example, in the DogControl.grxml grammar, consider changing "Fight" to "Attack". Doing so would result in zero predicted confusable phrases when you re-run the grammar back through the tool. This approach is recommended if you do not have the time and resources to do adequate utterance collection for tuning, or if modifying the phrases doesn't degrade the end-user experience (it's just as good saying "Attack" instead of "Fight").

  2. If you prefer to not change your design, then you should consider spending some extra attention on end-user testing. Do users experience a high number of false accepts (confusion) when saying those phrases in a test production environment? If not, then the production environment doesn't lend itself to a high risk of confusion for those phrases and you can feel more confident that game-play will result in a similar experience. However, if users in a test production environment encounter an unacceptable number of false accepts then you can:

    • Reconsider a design change to the grammar now that you have data from end-users that supports the results given by the tool.

    • Consider a fall-back in the game-play where a false accept can be mitigated through additional logic. For example, you may want to prompt the user to confirm her input when she speaks a confusable phrase, or give the user an opportunity to cancel a request before it's executed.

  3. And of course, you always have the option of doing nothing. You may be comfortable with this option if you are familiar with how your platform works with speech in production and how it tends to behave for your user segment.

Summary

Confusability.exe provides a sanity-check-level analysis for phrases in a grammar that have a potential to be misrecognized for one another.

Reminders and guidance:

  • Use the tool after the design process but before you go out and collect lots of speaker utterances.

  • You should not equate the metric returned directly with probability, but rather indicate which pairs of phrases have some risk of confusion.

  • If you see confusion in one direction, assume potential confusion in both directions. For example, your use of the tool might reveal that "foo bar" is confusable with "too far" but not vice-versa. For the sake of action items, assume that there's a risk that "too far" may be misrecognized as "foo bar."

Patterns more likely to be flagged by the tool include:

  • Near homonyms in which phrases differ by one or a few sounds (for example, "tog" and "pog").

  • Homonyms in which phrases are duplicated (for example, "cake" and "cake").

  • Phrase length, when equal, can increase the likelihood of a confusable pair; however, shorter phrases also tend to be more likely flagged as confusable than longer phrases

The tool is not a substitute for testing with actual speech from end-users, which provides the most accurate insight into how a grammar affects the speech recognition experience. But in reality, collecting lots of user data may not be feasible or practical for all applications. Running Confusability.exe before pre-production testing of speech in the application can help identify some potentially confusable phrases.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Simulator Reference Manual

[image]

Simulator Reference Manual
See Also Send Feedback

Simulator connects to a speech recognition engine and performs speech recognition on batches of recorded utterances.

The Simulator Reference Manual contains the following topics.

  • Simulator/Simulator Results Analyzer Usage Scenarios

  • Generating Simulations and Performing Analysis

  • Simulator Command-Line Syntax

  • Simulator Input and Output File Contents

  • Simulator Error Messages and Format

  • EMMA Document Examples

  • EMMA Documentation

See Also

Concepts

Simulator Results Analyzer Reference Manual
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Simulator/Simulator Results Analyzer Usage Scenarios

[image]

Simulator/Simulator Results Analyzer Usage Scenarios
See Also Send Feedback

Simulator takes as input an EMMA document that references a set of utterances (for example ".wav" files), associated grammars, and optional transcriptions. Configured against a specific recognizer, the tool returns a set of recognition results.

You can use Simulator together with Simulator Results Analyzer to debug and tune the components of speech recognition. The two tools play complimentary roles:

  • Simulator is primarily concerned with performing recognitions and getting raw results.

  • Simulator Results Analyzer is primarily concerned with extracting actionable measurements from the raw results produced by Simulator.

Usage Scenarios

The following examples describe the scenarios in which you can use Simulator and Simulator Results Analyzer together to generate recognition results and to analyze the factors that contribute to recognition.

Text-Based Analysis

You have a new grammar and want to measure its performance before deploying it into a live service. However, you do not have any audio files with which to test the grammar. You assemble a set of text phrases and incorporate them in an EMMA document that you can provide to Simulator as input. When you run Simulator, it performs emulated recognition on the input text phrases, generating a set of recognition results. Then, you use Simulator Results Analyzer to analyze the results obtained by emulation.

Audio-Based Analysis

Having analyzed a grammar by providing text as input, you now want to analyze the grammar using audio for input. You obtain a set of audio files that you can use to test the grammar. You add references to these audio files in the EMMA document that you will use as input to Simulator. When you run Simulator, you receive recognition results that were produced by recognition of the audio files. Then you use Simulator Results Analyzer to analyze the results obtained by recognition of audio input.

Analysis of Transcribed Audio

You have an EMMA document that contains references to audio files. The EMMA document can be created from scratch or obtained from an utterance-capture web service. You modify the EMMA document by adding a transcription for each utterance and then use Simulator to provide recognitions for each utterance. Then, you use Simulator Results Analyzer to perform an analysis against the recognition results.

The output from Simulator Results Analyzer includes calculation of correct-accept/false-accept (CA/FA) rates for the complete range of confidencelevel settings on the speech recognition engine, identifies out-of-grammar phrases, and calculates error rates that illustrate the overall accuracy of your grammars. You can use this data to create graphs and tables that highlight significant data points in the recognition results, or as input to other tools for additional analysis.

Comparison of Results from Different Runs

You have a set of recognition results from a previous run of Simulator which used an older version of the application grammar. Using a newer version of the grammar as input to Simulator, you generate an updated set of recognition results. You can use Simulator Results Analyzer to produce a set of graphs that compare the relative performance of the older and newer grammars. This will assist you to determine whether one grammar does a better job of correctly recognizing a set of utterances versus another grammar.

Offsite Analysis of Run Data

As an IVR application developer, you perform a log tuning run and obtain results that are unexpectedly different from previous runs. You then call customer support to find out why the recognition results were not as expected. You send the output from the recognition engine to the support analyst, who examines the output and determines that engine version and configuration did not match the ones used in the previous runs.

See Also

Concepts

Simulator Reference Manual
Simulator Results Analyzer Reference Manual
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Generating Simulations and Performing Analysis

[image]

Generating Simulations and Performing Analysis
See Also Send Feedback

The following procedure describes how to use Simulator together with Simulator Results Analyzer to generate simulated recognition from utterances (such as ".wav" files containing speech), and to analyze the results of recognition.

Typical steps for using Simulator with Simulator Results Analyzer

  1. Identify a set of utterances (".wav" files) for which you want to obtain recognition results.

  2. Identify the set of grammars to use for recognizing the utterances.

  3. Create an input EMMA document that contains paths to the grammar files and the ".wav" files.

  4. Create a configuration file that specifies the speech recognition engine that you want to use and configures its settings.

  5. Run Simulator.exe and reference the EMMA document and the configuration file. Here's an example command-line entry for running the tool:

    Simulator.exe /In EmmaBatchFile.xml /Out MyRecognitionResults.xml /RecoConfig MyRecognizerConfiguration.xml

    • Simulator.exe generates an EMMA output file that contains the raw recognition results for the batch of utterances. You can use the output EMMA file as input to your own analysis tools. Optionally, you can use the EMMA output file as input to SimulatorResultsAnalyzer.exe, as follows:

  6. Run SimulatorResultsAnalyzer.exe and specify the output file from Simulator at the /In option. Here is an example command-line entry:

    SimulatorResultsAnalyzer /In MyRecognitionResults.xml /Out MyRecognitionAnalysis.xml

    • The output file generated by SimulatorResultsAnalyzer.exe includes calculation of CA/FA rates for the complete range of confidencelevel settings on the speech recognition engine, identifies out-of-grammar phrases, and calculates error rates that illustrate the overall accuracy of your grammars. You can use the output from SimulatorResultsAnalyzer.exe to generate tables and graphs using XML transforms of your design or as the basis for further analysis by your own tools.

Important note Important

The configuration file (step 4) should set the confidence threshold to zero (confidencelevel="0") to ensure that all recognitions are returned, regardless of confidence score. This will ensure that you properly assess the confidence threshold setting for your application via the output of Simulator Results Analyzer. See Speech Recognition Engine Configuration File Settings.

For more information on valid command-line options and their use, see Simulator Command-Line Syntax and Simulator Results Analyzer Command-Line Syntax.

See Also

Concepts

Simulator Reference Manual
Simulator Results Analyzer Reference Manual
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Simulator Command-Line Syntax

[image]

Simulator Command-Line Syntax
Send Feedback

The command-line syntax for Simulator has the following format.

Simulator.exe /In <input file name> /Out <output file name> /MaxActiveRecognitions <integer value> /RecoConfig <config file name> /Filter <filter file name> /IncludeInitialEngineState <boolean>

The following table describes the option names and values for Simulator.

Option Name

Description

/In

Required. A string that contains the name of the input EMMA document. See Simulator Input and Output File Contents.

/Out

Optional. A string that contains the name (and path, as required) of the output EMMA document. Simulator logs a critical error and exits if the output file name and input file name refer to the same file.

If no output file is specified, a file with the name <inputfilename>.out.xml is created, and output is sent to it.

/MaxActiveRecognitions

Optional. An integer that specifies the maximum number of connections that the recognition engine should make at any given time. If not specified, the default value is 10. The value must be greater than zero and not larger than 2147483647.

/RecoConfig

Optional. The name of the configuration file to use for the speech recognition engine. If not specified, the tool will look for a default configuration file named "RecoConfig.xml" in the current working directory and in the directory that contains Simulator.exe. The tool will generate an error if you do not supply it with a configuration file.

/Filter

Optional. A string that contains the name of the configuration file to use for filtering. If no file is specified, all recognitions are run and all transcripts are processed for semantics.

The file contains a Filter element, which contains an IsTranscript element whose value can be either true or false. A value of true indicates that only transcripts are to be processed. A value of false indicates that only speech recognitions are to be performed. See an example of a filter configuration file after this table.

/IncludeInitialEngineState

Optional. Removes the serialized state information from the output file that Simulator generates, significantly reducing the size of the output file. Accepted values are true and false. The default value is true.

/?

Optional. Displays a list of acceptable option/value pairs.

The following XML code is an example of a filter configuration file.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<Filter>
  <IsTranscript>true</IsTranscript>
</Filter>
Note Note

  • Command-line options and values are not case-sensitive.

  • Command-line options can be preceded by a forward slash (0x002F), a dash (0x002d), an en dash (0x2013), an em dash (0x2014), or a horizontal bar (0x2015).

  • You can enter option/value pairs in any sequence.

Caution note Caution

If an existing file has the same name as the file name specified by the /Out option, it will be overwritten. The tool does not warn that a file will be overwritten.

Remarks

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" either in the current directory (the directory for the command line) or in the directory that contains Simulator.exe. Use the configuration file to specify a speech recognition engine to use, to configure the parameters for connecting to it, and to configure its behavior. For more information, see Setting Up the Grammar Development Tools.

To properly assess the confidence threshold setting for your application via the output of Simulator Results Analyzer, set confidencelevel="0" in your RecoConfig file. This will ensure that all recognitions are returned, regardless of confidence score.

Note Note

Simulator may generate the following error if it cannot locate one or more of the grammars listed in the EMMA input document specified by the /In option:

Error Name | Hexadecimal | Decimal | Description
SPERR_NOT_FOUND | 0x8004503a | -2147200966 | The requested data item (data key, value, etc.) was not found.

Example Usage

The following demonstrates the syntax for using Simulator.

Simulator.exe -In InputFile.xml -Out OutputFile.xml -MaxActiveRecognitions 15 -RecoConfig MyRecoConfigFile.xml -IncludeInitialEngineState false

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Simulator Input and Output File Contents

[image]

Simulator Input and Output File Contents
Send Feedback

Simulator takes as input an EMMA document and writes its output to an EMMA-formatted file. This topic describes the contents of both types of files.

Input File Contents

The input for Simulator is an EMMA document that contains one or more utterances. The EMMA document can contain:

  • A single utterance

  • An ordered sequence of utterances (similar to those in a telephone call)

  • An unordered group of utterances

  • A mixture of ordered and unordered groups of utterances

Grammar and audio inputs can be offered in the form of local file content, or as URIs. If text is entered into the field for the location of audio content, this text is used as input to be processed through emulation, rather than recognition. Transcripts contain text that represents the ideal expected recognition for the supplied audio. Transcripts may also contain tags indicating the presence of noise or garbage audio. The EMMA document may contain additional information not needed by Simulator.

EMMA files used as input to Simulator can define sets of grammars, which can be assigned collectively to recognize an utterance. Each set of grammars must have a unique identifier. For each utterance, you can designate the grammars that are active for recognition by referencing the identifier for a set of grammars. A set of grammars designated to recognize an utterance comprises the "grammar state" for an utterance. When using grammar states, each utterance should reference exactly one grammar state.

SimulatorResultsAnalyzer will always create a separate analysis section for each grammar set. This makes it easier to identify utterances that use a particular grammar state and to tune the associated grammars. Otherwise, you may specify grammars individually, using a unique identifier for each. However, SimulatorResultsAnalyzer will not create a separate analysis section for individually specified grammars; they will only be included in the default analysis that includes all utterances.

The information in an input file that is relevant to Simulator is shown in the following list:

  • Grammars

  • Groups of grammars labeled with an identifier

  • Audio files (optional)

  • Audio files with audio overridden by text input (optional)

  • Serialized engine state (optional)

  • Engine parameter settings (optional)

  • Engine version information (optional)

  • Transcripts (optional)

  • Cookies containing information about individual utterances or the entire EMMA document (optional)

Example Use of Grammar States

The following example is an EMMA input file for Simulator. The example creates two grammar states (MyState1 and MyState2) by defining two sets of grammars and assigning each set an identifier. The first utterance specifies the identifier MyState1 to designate the grammars that will be active for recognition of the utterance. The second utterance designates a different set of grammars to use for recognition by specifying MyState2.

Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<emma:emma version="1.0" xmlns:ms="http://www.microsoft.com/xmlns/webreco"
  xmlns:emma="http://www.w3.org/2003/04/emma"
  xmlns="http://www.example.com/example">
  <!--
  This first block allows us to defining different grammar states, using the
  ms namespace, and active grammar ids.
  -->
  <emma:info>

    <!--
    The definition of the first 'state.' Each utterance references a set of one
    or more active grammars, based on an id. In this way, a user can run offline
    batch recognitions on a set of utterances that may have different 'states'
    defined by active grammars and their rules. The analysis results will be
    bucketed based on the active-grammars id.
    -->
    <ms:active-grammar-set id="MyState1">
      <ms:grammar weight="1.1" emma:grammar-ref="grammar-0"/>
      <ms:grammar weight="1.2" emma:grammar-ref="grammar-1"/>
      <ms:grammar weight="1.3" emma:grammar-ref="grammar-2"/>
      <ms:grammar weight="1.4" emma:grammar-ref="grammar-3"/>
      <ms:grammar weight="1.5" emma:grammar-ref="grammar-4"/>
      <ms:grammar weight="1.6" emma:grammar-ref="grammar-5"/>
    </ms:active-grammar-set>

    <!-- The definition of the second set of 'state.' -->
    <ms:active-grammar-set id="MyState2">
      <ms:grammar weight="1.4" emma:grammar-ref="grammar-6"/>
      <ms:grammar weight="1.5" emma:grammar-ref="grammar-7"/>
      <ms:grammar weight="1.6" emma:grammar-ref="grammar-8"/>
    </ms:active-grammar-set>

  </emma:info>

  <emma:grammar id="grammar-0" ref="http://contoso.com/grammars/Grammar0.grxml />
  <emma:grammar id="grammar-1" ref="http://contoso.com/grammars/Grammar1.grxml />
  <emma:grammar id="grammar-2" ref="http://contoso.com/grammars/Grammar2.grxml />
  <emma:grammar id="grammar-3" ref="http://contoso.com/grammars/Grammar3.grxml />
  <emma:grammar id="grammar-4" ref="http://contoso.com/grammars/Grammar4.grxml />
  <emma:grammar id="grammar-5" ref="http://contoso.com/grammars/Grammar5.grxml />
  <emma:grammar id="grammar-6" ref="http://contoso.com/grammars/Grammar6.grxml />
  <emma:grammar id="grammar-7" ref="http://contoso.com/grammars/Grammar7.grxml />
  <emma:grammar id="grammar-8" ref="http://contoso.com/grammars/Grammar8.grxml />

  <!--
  The following emma:group contains the set of utterances to be recognized against.
  In this example, there are two utterances, each to be recognized by a different
  'state' of active grammars.
  -->
  <emma:group id="SetofUtterances">

    <emma:group id="MyFirstUtterance">
      <emma:info>
        <ms:audio ref="http://capture.contoso.com/call/utt01.wav"/>
        <ms:active-grammar-set-ref ref="MyState1"/>
        <ms:transcript>
          <ms:original> sports </ms:original>
        </ms:transcript>
      </emma:info>
    </emma:group>

    <emma:group id="MySecondUtterance">
      <emma:info>
        <ms:audio ref="http://capture.contoso.com/call/utt02.wav" type="audio/x-wav" />
        <ms:active-grammar-set-ref ref="MyState2"/>
        <ms:transcript>
          <ms:original> weather please </ms:original>
        </ms:transcript>
      </emma:info>
    </emma:group>

  </emma:group>

</emma:emma>

Remarks

The EMMA structure specifies whether to reuse the serialized state based on whether recognized utterances are organized within emma:sequence elements or not. The serialized state for a recognition, also known as the recognition context block, contains user-specific speech engine adaptations.

If you specify utterances using the emma:sequence element in the EMMA structure, then all utterances contained in the first level emma:group element beneath the emma:sequence element will maintain serialized state, passing information learned about one utterance to the next utterance in the emma:sequence. If you do not use emma:sequence elements, the serialized state will not be reused and the recognizer will treat the utterances as a collection of unrelated calls.

When configured for local recognition, Simulator will send cookie information with the request for the grammar. You can add cookies for local or remote grammars that are referenced with a link to an HTTP or HTTPS URL address. Use the ms:cookie-jar element to add cookies to an emma:info element contained either within the global emma:emma element, or within an utterance's emma:group element. An emma:info element can contain only one ms:cookie-jar element.

The global scope and utterance scope of an EMMA document, and the recognition engine configuration file scope may all contribute unique cookies to the final collection of cookies. If a new cookie has the identical name, domain, and path as an older cookie, the new cookie will replace the older cookie.

For example, if the recognition engine configuration file specifies two unique cookies, and the global emma:info section of the EMMA document specifies two more unique cookies, and the emma:info section of the utterance also specifies two more unique cookies, then the collection of cookies will contain six cookies total. See Speech Recognition Engine Configuration File Settings for more information about cookies.

Output File Contents

Simulator creates EMMA-formatted output files that may contain all the information from the input file, as well as the following information:

  • Detailed recognition results (that is, the actual recognition, confidence values, semantics, pronunciation, lattice, rule tree, and other recognition results)

  • A unique RequestId and SessionId for the recognition

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Simulator Error Messages and Format

[image]

Simulator Error Messages and Format
Send Feedback

Simulator displays descriptive error messages that provide details about the cause of errors encountered while processing input files.

For errors detected in an input file, such as EMMA input, grammars, and audio files, error messages contain the following information.

  • File name (if applicable)

  • Number of the line that contains the error (if applicable)

  • Message type: Error, Warning, or Info

  • Error code (if applicable)

  • Error description

Upon successful completion, Simulator displays a message indicating that processing is complete and returns EXIT_SUCCESS (0).

Fatal Errors

When a fatal error occurs, Simulator displays an error message indicating that a fatal error has occurred, halts execution of the tool, and returns EXIT_FAILURE (1). Examples of fatal errors include the following:

  • Basic file problems such as failure to find a file, open a file, or write to a file.

  • XML file validation issues.

  • Configuration issues.

Errors that occur in the underlying recognition services are passed through to the user.

Nonfatal Errors

Nonfatal errors are displayed on the console, and are recorded inside the EMMA document, but do not halt execution. The nonfatal errors are as shown in the following list:

  • Cannot connect to recognition services.

  • Grammar not found.

  • Audio not found.

  • Recognition failed.

Note Note

Simulator may generate the following error if it cannot locate one or more of the grammars listed in the EMMA input document specified by the /In option:

Error Name | Hexadecimal | Decimal | Description
SPERR_NOT_FOUND | 0x8004503a | -2147200966 | The requested data item (data key, value, etc.) was not found.

Remarks

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" in the current directory (the directory for the command line), or in the directory that contains Simulator.exe. The tool will generate an error if you do not supply it with a configuration file.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EMMA Document Examples

[image]

EMMA Document Examples
Send Feedback

This topic presents two examples of EMMA documents. You can use the first example as input to Simulator. The second example is the output generated by Simulator from the input file example. You can use the Simulator output file as input to the Simulator Results Analyzer tool.

Example 1: EMMA Input File

The following is an example of an EMMA file that you can use as input for Simulator. You can find this file under the Samples folder where you installed the Microsoft Speech Platform SDK 11. The audio files and grammars referenced in this document are in the Waves and Grammars folders, respectively.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<emma:emma version="1.0" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma" xmlns="http://www.example.com/example">

  <emma:grammar id="grammar0" ref="grammars\menu_choices.grxml" />
  <emma:grammar id="grammar1" ref="grammars\help_choices.grxml" />

  <emma:group id="toplevel">
    <emma:group id="utterance_0.0.0.0">
      <emma:info>
<ms:audio ref="waves/utt_00.wav" type="audio/x-wav" />
        <ms:transcript>
          <ms:original>sports</ms:original>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
      </emma:info>
    </emma:group>

<emma:group id="utterance_0.0.1.0">
      <emma:info>
<ms:audio ref="waves/utt_01.wav" type="audio/x-wav" />
        <ms:transcript>
          <ms:original>[noise]</ms:original>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
      </emma:info>
    </emma:group>

<emma:group id="utterance_0.0.2.0">
      <emma:info>
<ms:audio ref="waves/utt_02.wav" type="audio/x-wav" />
        <ms:transcript>
          <ms:original>sports</ms:original>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
      </emma:info>
    </emma:group>

<emma:group id="utterance_0.0.3.0">
      <emma:info>
<ms:audio ref="waves/utt_03.wav" type="audio/x-wav" />
        <ms:transcript>
          <ms:original>weather</ms:original>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
      </emma:info>
    </emma:group>

<emma:group id="utterance_0.0.4.0">
      <emma:info>
<ms:audio ref="waves/utt_04.wav" type="audio/x-wav" />
        <ms:transcript>
          <ms:original>news</ms:original>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
      </emma:info>
    </emma:group>

<emma:group id="utterance_0.0.5.0">
      <emma:info>
<ms:audio ref="waves/utt_05.wav" type="audio/x-wav" />
        <ms:transcript>
          <ms:original>top stories</ms:original>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
      </emma:info>
    </emma:group>

<emma:group id="utterance_0.0.6.0">
      <emma:info>
<ms:audio ref="waves/utt_06.wav" type="audio/x-wav" />
        <ms:transcript>
          <ms:original>sport</ms:original>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
      </emma:info>
    </emma:group>

<emma:group id="utterance_0.0.7.0">
      <emma:info>
<ms:audio ref="waves/utt_07.wav" type="audio/x-wav" />
<ms:transcript>
          <ms:original>stock quotes</ms:original>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
      </emma:info>
    </emma:group>

<emma:group id="utterance_0.0.8.0">
      <emma:info>
<ms:audio ref="waves/utt_08.wav" type="audio/x-wav" />
        <ms:transcript>
          <ms:original>weather</ms:original>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
      </emma:info>
    </emma:group>

<emma:group id="utterance_0.0.9.0">
      <emma:info>
        <ms:audio ref="waves/utt_09.wav" type="audio/x-wav" />
        <ms:transcript>
          <ms:original>weather</ms:original>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
      </emma:info>
    </emma:group>

<emma:group id="utterance_0.0.10.0">
      <emma:info>
        <ms:audio ref="waves/utt_10.wav" type="audio/x-wav" />
        <ms:transcript>
          <ms:original>sports</ms:original>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
      </emma:info>
    </emma:group>

  </emma:group>
</emma:emma>

Example 2: EMMA Output File

Simulator takes the EMMA input file of the first example and produces the following EMMA output file, which can be used as input to Simulator Results Analyzer. You can find the example file under the Samples folder where you installed the Speech Platform SDK 11. The audio files and grammars referenced in this document are in the Waves and Grammars folders, respectively.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<emma:emma version="1.0" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma" xmlns="http://www.example.com/example">
  <emma:grammar id="grammar0" ref="grammars\menu_choices.grxml" />
  <emma:grammar id="grammar1" ref="grammars\help_choices.grxml" />
  <emma:group id="toplevel">

    <emma:group id="utterance_0.0.0.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_00.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>sports</ms:original>
          <emma:one-of id="utterance_0.0.0.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.0.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.0.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>51b96944-25a7-4bc8-902c-5066ee5eb369</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.0.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.0.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="0.5638461" emma:time-ref-uri="#utterance_0.0.0.0-reco-nbest-list" emma:offset-to-start="330" emma:duration="810" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.0.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.5618123" ms:actualConfidence="0" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
          <grammar emma:confidence="0.5618123" ms:actualConfidence="0" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>

    <emma:group id="utterance_0.0.1.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_01.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>[noise]</ms:original>
          <emma:interpretation emma:uninterpreted="true" id="utterance_0.0.1.0-transcript-reco-nbest-list-1" emma:mode="voice" emma:medium="acoustic" />
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>0d758c5c-6d32-45a5-ba9e-308a8c036832</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:interpretation emma:uninterpreted="true" id="utterance_0.0.1.0-reco-nbest-list-1" emma:mode="voice" emma:medium="acoustic" />
    </emma:group>

    <emma:group id="utterance_0.0.2.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_02.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>sports</ms:original>
          <emma:one-of id="utterance_0.0.2.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.2.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.2.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>c2945818-5fa6-455c-ba5e-612a74da3187</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.2.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.2.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="0.9479059" emma:time-ref-uri="#utterance_0.0.2.0-reco-nbest-list" emma:offset-to-start="140" emma:duration="840" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.2.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.8497295" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
          <grammar emma:confidence="0.8497295" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>

    <emma:group id="utterance_0.0.3.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_03.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>weather</ms:original>
          <emma:one-of id="utterance_0.0.3.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.3.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="weather" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.3.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>b6643747-e6c3-4776-bacb-a853e4ccb4f9</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.3.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.3.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="weather" emma:confidence="0.9449926" emma:time-ref-uri="#utterance_0.0.3.0-reco-nbest-list" emma:offset-to-start="220" emma:duration="750" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.3.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.9668913" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
          <grammar emma:confidence="0.9668913" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>

    <emma:group id="utterance_0.0.4.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_04.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>news</ms:original>
          <emma:one-of id="utterance_0.0.4.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.4.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="news" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.4.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">NEWS</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>1c0a2052-bdc2-4e7b-acfa-c40e901b735f</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.4.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.4.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="news" emma:confidence="0.9319434" emma:time-ref-uri="#utterance_0.0.4.0-reco-nbest-list" emma:offset-to-start="230" emma:duration="930" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.4.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.9612538" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">NEWS</application>
          <grammar emma:confidence="0.9612538" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>

    <emma:group id="utterance_0.0.5.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_05.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>top stories</ms:original>
          <emma:interpretation emma:uninterpreted="true" id="utterance_0.0.5.0-transcript-reco-nbest-list-1" emma:mode="voice" emma:medium="acoustic" />
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>c553ff53-0bef-42ce-aad7-394d2d77d904</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:interpretation emma:uninterpreted="true" id="utterance_0.0.5.0-reco-nbest-list-1" emma:mode="voice" emma:medium="acoustic" />
    </emma:group>
    <emma:group id="utterance_0.0.6.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_06.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>sport</ms:original>
          <emma:interpretation emma:uninterpreted="true" id="utterance_0.0.6.0-transcript-reco-nbest-list-1" emma:mode="voice" emma:medium="acoustic" />
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>db35f5f0-7c87-45e8-a9b0-f393ce4a7025</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.6.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.6.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="0.9216749" emma:time-ref-uri="#utterance_0.0.6.0-reco-nbest-list" emma:offset-to-start="130" emma:duration="600" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.6.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.9370015" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
          <grammar emma:confidence="0.9370015" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>
    <emma:group id="utterance_0.0.7.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_07.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>stock quotes</ms:original>
          <emma:one-of id="utterance_0.0.7.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.7.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="stock quotes" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.7.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <longform emma:confidence="1" ms:actualConfidence="1" ms:dataType="boolean" ms:valueType="boolean" xmlns="">true</longform>
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">STOCKS</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>dc25a5ce-e546-4376-91f4-eb7b2e924721</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.7.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.7.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="stock quotes" emma:confidence="0.8928868" emma:time-ref-uri="#utterance_0.0.7.0-reco-nbest-list" emma:offset-to-start="250" emma:duration="970" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.7.0-rule-tree-1" composite="false" />
          <longform emma:confidence="0.8609061" ms:actualConfidence="1" ms:dataType="boolean" ms:valueType="boolean" xmlns="">true</longform>
          <application emma:confidence="0.8609061" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">STOCKS</application>
          <grammar emma:confidence="0.8609061" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>
    <emma:group id="utterance_0.0.8.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_08.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>weather</ms:original>
          <emma:one-of id="utterance_0.0.8.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.8.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="weather" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.8.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>6fe369ac-a87a-4f16-ab25-ec7f5ca265ee</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.8.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.8.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="weather" emma:confidence="0.6197259" emma:time-ref-uri="#utterance_0.0.8.0-reco-nbest-list" emma:offset-to-start="230" emma:duration="790" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.8.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.6058497" ms:actualConfidence="0" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
          <grammar emma:confidence="0.6058497" ms:actualConfidence="0" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>
    <emma:group id="utterance_0.0.9.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_09.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>weather</ms:original>
          <emma:one-of id="utterance_0.0.9.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.9.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="weather" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.9.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>7a2c3ee0-7fbc-487f-b617-351ca8e458b9</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.9.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.9.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="weather" emma:confidence="0.9403493" emma:time-ref-uri="#utterance_0.0.9.0-reco-nbest-list" emma:offset-to-start="230" emma:duration="770" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.9.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.962913" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
          <grammar emma:confidence="0.962913" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>
    <emma:group id="utterance_0.0.10.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_10.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>sports</ms:original>
          <emma:one-of id="utterance_0.0.10.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.10.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.10.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>18d942f8-6278-4bc5-8ed1-9b9b75aa4a22</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.10.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.10.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="0.8278435" emma:time-ref-uri="#utterance_0.0.10.0-reco-nbest-list" emma:offset-to-start="140" emma:duration="810" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.10.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.8705698" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
          <grammar emma:confidence="0.8705698" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>
  </emma:group>
  <emma:derivation>
    <emma:one-of id="utterance_0.0.0.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.0.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.0.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.5638461" emma:offset-to-start="0" emma:duration="690">sports<emma:info><ms:sapiPhraseElement ms:pronunciation="S P AO RA T S" ms:lexicalForm="sports" ms:displayAttributes="2" ms:actualConfidence="0" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.0.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.0.0-rule-tree-1" emma:confidence="0.5638461" emma:time-ref-uri="#utterance_0.0.0.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.0.0-word-list-1" composite="false" />
        <top emma:confidence="0.5638461" ms:actualConfidence="0" emma:offset-to-start="0" emma:duration="690" xmlns="">sports</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.2.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.2.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.2.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.9479059" emma:offset-to-start="0" emma:duration="740">sports<emma:info><ms:sapiPhraseElement ms:pronunciation="S P AO RA T S" ms:lexicalForm="sports" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.2.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.2.0-rule-tree-1" emma:confidence="0.9479059" emma:time-ref-uri="#utterance_0.0.2.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.2.0-word-list-1" composite="false" />
        <top emma:confidence="0.9479059" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="740" xmlns="">sports</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.3.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.3.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.3.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.9449926" emma:offset-to-start="0" emma:duration="650">weather<emma:info><ms:sapiPhraseElement ms:pronunciation="W EH DH AX RA" ms:lexicalForm="weather" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.3.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.3.0-rule-tree-1" emma:confidence="0.9449926" emma:time-ref-uri="#utterance_0.0.3.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.3.0-word-list-1" composite="false" />
        <top emma:confidence="0.9449926" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="650" xmlns="">weather</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.4.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.4.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.4.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.9319434" emma:offset-to-start="0" emma:duration="820">news<emma:info><ms:sapiPhraseElement ms:pronunciation="N U Z" ms:lexicalForm="news" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.4.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.4.0-rule-tree-1" emma:confidence="0.9319434" emma:time-ref-uri="#utterance_0.0.4.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.4.0-word-list-1" composite="false" />
        <top emma:confidence="0.9319434" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="820" xmlns="">news</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.6.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.6.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.6.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.9216749" emma:offset-to-start="0" emma:duration="500">sports<emma:info><ms:sapiPhraseElement ms:pronunciation="S P AO RA T S" ms:lexicalForm="sports" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.6.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.6.0-rule-tree-1" emma:confidence="0.9216749" emma:time-ref-uri="#utterance_0.0.6.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.6.0-word-list-1" composite="false" />
        <top emma:confidence="0.9216749" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="500" xmlns="">sports</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.7.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.7.0-word-list-1">
        <emma:lattice initial="1" final="3" emma:time-ref-uri="#utterance_0.0.7.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.8581361" emma:offset-to-start="0" emma:duration="430">stock<emma:info><ms:sapiPhraseElement ms:pronunciation="S T AA K" ms:lexicalForm="stock" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
          <emma:arc from="2" to="3" emma:confidence="0.9216229" emma:offset-to-start="430" emma:duration="520">quotes<emma:info><ms:sapiPhraseElement ms:pronunciation="K W O T S" ms:lexicalForm="quotes" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.7.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.7.0-rule-tree-1" emma:confidence="0.8928868" emma:time-ref-uri="#utterance_0.0.7.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.7.0-word-list-1" composite="false" />
        <top emma:confidence="0.8928868" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="950" xmlns="">stock quotes</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.8.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.8.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.8.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.6197259" emma:offset-to-start="0" emma:duration="680">weather<emma:info><ms:sapiPhraseElement ms:pronunciation="W EH DH AX RA" ms:lexicalForm="weather" ms:displayAttributes="2" ms:actualConfidence="0" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.8.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.8.0-rule-tree-1" emma:confidence="0.6197259" emma:time-ref-uri="#utterance_0.0.8.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.8.0-word-list-1" composite="false" />
        <top emma:confidence="0.6197259" ms:actualConfidence="0" emma:offset-to-start="0" emma:duration="680" xmlns="">weather</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.9.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.9.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.9.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.9403493" emma:offset-to-start="0" emma:duration="680">weather<emma:info><ms:sapiPhraseElement ms:pronunciation="W EH DH AX RA" ms:lexicalForm="weather" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.9.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.9.0-rule-tree-1" emma:confidence="0.9403493" emma:time-ref-uri="#utterance_0.0.9.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.9.0-word-list-1" composite="false" />
        <top emma:confidence="0.9403493" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="680" xmlns="">weather</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.10.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.10.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.10.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.8278435" emma:offset-to-start="0" emma:duration="710">sports<emma:info><ms:sapiPhraseElement ms:pronunciation="S P AO RA T S" ms:lexicalForm="sports" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.10.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.10.0-rule-tree-1" emma:confidence="0.8278435" emma:time-ref-uri="#utterance_0.0.10.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.10.0-word-list-1" composite="false" />
        <top emma:confidence="0.8278435" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="710" xmlns="">sports</top>
      </emma:interpretation>
    </emma:one-of>
  </emma:derivation>
</emma:emma>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EMMA Documentation

[image]

EMMA Documentation
Send Feedback

This section provides a brief description of Extensible MultiModal Annotation (EMMA) types and Microsoft extensions to EMMA. For more information, see EMMA: Extensible MultiModal Annotation markup language.

The types described in the first four topics of this section are defined in W3C schema definition for EMMA. Elements in this schema definition have either an xs: prefix or an emma: prefix. The namespace for those elements with the xs: prefix is http://www.w3.org/2001/XMLSchema. The fifth topic in this section presents schema definition files with Microsoft EMMA extensions.

  • EMMA Attributes

  • EMMA Complex Types

  • EMMA Groups

  • EMMA Attribute Groups

  • Microsoft Extensions to EMMA

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EMMA Attributes

[image]

EMMA Attributes
Send Feedback

The attributes listed in the following table are defined in W3C schema definition for EMMA. The types of these attributes are defined in http://www.w3.org/2001/XMLSchema.

Attribute | Type
composite | xs:boolean
confidence | xs:decimal 0.0 through 1.0, inclusive
cost | xs:decimal 0.0 through 10,000,000, inclusive
dialog-turn | xs:string
disjunction-type | xs:NMTOKEN recognition, understanding, multi-device, multi-process
duration | xs:nonNegativeInteger The default value is 0.
end | xs:unsignedLong
endpoint-address | xs:anyURI
endpoint-info-ref | xs:IDREF
endpoint-pair-ref | xs:anyURI
endpoint-role | xs:NMTOKEN source, sink, reply-to, router
final | xs:list of xs:nonNegativeInteger
from | xs:nonNegativeInteger
function | xs:NMTOKEN
grammar-ref | xs:IDREF
hook | xs:string
id | xs:ID
initial | xs:nonNegativeInteger
lang | xs:language
media-type | xs:string
medium | xs:NMTOKENS acoustic, tactic, visual
message-id | xs:anyURI
mode | xs:NMTOKENS
model-ref | xs:IDREF
name | xs:string
node-number | xs:nonNegativeInteger
no-input | xs:boolean
offset-to-start | xs:integer default is 0
port-num | xs:nonNegativeInteger
port-type | xs:QName
process | xs:anyURI
ref | xs:anyURI
resource | xs:anyURI
service-name | xs:string
signal | xs:anyURI
signal-size | xs:nonNegativeInteger
source | xs:anyURI
start | xs:unsignedLong
time-ref-anchor-point | xs:NMTOKEN start, end The default value is start.
time-ref-uri | xs:anyURI
to | xs:nonNegativeInteger
tokens | xs:string
uninterpreted | xs:boolean
verbal | xs:boolean
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EMMA Complex Types

[image]

EMMA Complex Types
Send Feedback

The following EMMA complex types are described in this section.

  • emma:arc

  • emma:derivation

  • emma:derived-from

  • emma:emma

  • emma:endpoint

  • emma:endpoint-info

  • emma:grammar

  • emma:group

  • emma:group-info

  • emma:info

  • emma:interpretation

  • emma:lattice

  • emma:literal

  • emma:model

  • emma:node

  • emma:one-of

  • emma:sequence

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:arc

[image]

emma:arc
Send Feedback

An emma:arc element is one of two child elements of an emma:lattice element (the other child element is the emma:node element).

Element Definition

Copy image Copy Code
<xs:complexType name="arc" mixed="true">
  <xs:choice minOccurs="0" maxOccurs="unbounded">
    <xs:any namespace="##other" processContents="lax"/>
    <xs:element ref="emma:info"/>
  </xs:choice>
  <xs:attributeGroup ref="emma:arc.attribs"/>
</xs:complexType>

Parent Element

emma:lattice

Remarks

The emma:arc.attribs attribute group provides information about the two emma:node elements that are joined by the emma:arc element, as well as other optional information.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:derivation

[image]

emma:derivation
Send Feedback

An emma:derivation element contains an emma:interpretation element or container elements that represent earlier processing stages of input.

Element Definition

XML Copy image Copy Code
<xs:complexType name="derivation">
  <xs:choice maxOccurs="unbounded">
    <xs:element ref="emma:interpretation" />
    <xs:element ref="emma:one-of" />
    <xs:element ref="emma:sequence" />
    <xs:element ref="emma:group" />
  </xs:choice>
</xs:complexType>

Parent Element

emma:emma

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:derived-from

[image]

emma:derived-from
Send Feedback

An emma:derived-from element

Element Definition

XML Copy image Copy Code
<xs:complexType name="derived-from">
  <xs:attributeGroup ref="emma:derived-from.attribs" />
</xs:complexType>

Parent Element

An emma:derived-from element can be the child of any of the following elements.

  • emma:group

  • emma:interpretation

  • emma:one-of

  • emma:sequence

Remarks

The data in an emma:derived-from element is contained in an emma:derived-from.attribs attribute group.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:emma

[image]

emma:emma
Send Feedback

An emma:emma element is the root element in every EMMA document.

Element Definition

XML Copy image Copy Code
<xs:complexType name="emma">
  <xs:annotation>
    <xs:documentation>
       emma content model and root attributes
    </xs:documentation>
  </xs:annotation>
  <xs:group ref="emma:emma.class" minOccurs="0" maxOccurs="unbounded" />
  <xs:attribute name="version" type="xs:string" use="required" />
</xs:complexType>

Parent Element

None

Remarks

An emma:emma element contains a reference to an emma:emma.class element and a required version string whose current value is 1.0.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:endpoint

[image]

emma:endpoint
Send Feedback

An emma:endpoint element is a container for the endpoint that receives input.

Element Definition

XML Copy image Copy Code
<xs:complexType name="endpoint">
  <xs:choice maxOccurs="unbounded">
    <xs:any namespace="##other" processContents="lax" />
  </xs:choice>
  <xs:attributeGroup ref="emma:endpoint.attribs" />
</xs:complexType>

Parent Element

emma:endpoint-info

Remarks

An emma:endpoint element contains a reference to an emma:endpoint.attribs attribute group, which contains nearly all of the information about the endpoint.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:endpoint-info

[image]

emma:endpoint-info
Send Feedback

An emma:endpoint-info element is a container for information about the communications environment.

Element Definition

XML Copy image Copy Code
<xs:complexType name="endpoint-info">
  <xs:choice maxOccurs="unbounded">
    <xs:element ref="emma:endpoint" />
  </xs:choice>
  <xs:attribute name="id" type="xs:ID" use="required" />
</xs:complexType>

Parent Element

emma:emma

Remarks

An emma:endpoint-info element contains one or more references to emma:endpoint elements, each of which contains a reference to an emma:endpoint.attribs attribute group. The emma:endpoint.attribs attribute group can be used to hold information about the endpoint such as address and port number, as well as application-specific annotations.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:grammar

[image]

emma:grammar
Send Feedback

An emma:grammar element contains a reference to a grammar that is used to process input.

Element Definition

XML Copy image Copy Code
<xs:complexType name="grammar">
  <xs:attributeGroup ref="emma:grammar.attribs" />
</xs:complexType>

Parent Element

emma:emma

Remarks

Information about the grammar (URI and an ID) are contained in an emma:grammar.attribs attribute group.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:group

[image]

emma:group
Send Feedback

An emma:group element represents a collection of emma:interpretation elements or container elements (emma:one-of, emma:group, or emma:sequence) that are related according to some criteria.

Element Definition

XML Copy image Copy Code
<xs:complexType name="group">
  <xs:group ref="emma:group.class" minOccurs="0" maxOccurs="unbounded" />
  <xs:attributeGroup ref="emma:group.attribs" />
</xs:complexType>

Parent Element

An emma:group element can be the child of any of the following elements.

  • emma:derivation

  • emma:emma

  • emma:group

  • emma:one-of

  • emma:sequence

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:group-info

[image]

emma:group-info
Send Feedback

An emma:group-info element specifies the grouping criteria for the elements in an emma:group element.

Element Definition

XML Copy image Copy Code
<xs:complexType name="group-info">
  <xs:choice minOccurs="0" maxOccurs="unbounded">
    <xs:any namespace="##other" processContents="lax" />
  </xs:choice>
  <xs:attributeGroup ref="emma:group-info.attribs" />
</xs:complexType>

Parent Element

emma:group

Remarks

The grouping criteria are contained in an emma:group.attribs attribute group.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:info

[image]

emma:info
Send Feedback

An emma:info element contains application-specific metadata associated with user input.

Element Definition

XML Copy image Copy Code
<xs:complexType name="info">
  <xs:choice maxOccurs="unbounded">
    <xs:any namespace="##other" processContents="lax" />
  </xs:choice>
  <xs:attribute name="id" type="xs:ID" />
</xs:complexType>

Parent Element

An emma:info element can be the child of any of the following elements

  • emma:arc

  • emma:emma

  • emma:group

  • emma:interpretation

  • emma:one-of

  • emma:node

  • emma:sequence

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:interpretation

[image]

emma:interpretation
Send Feedback

An emma:interpretation element contains a single interpretation, a single emma:lattice element, or a single emma:literal element.

Element Definition

XML Copy image Copy Code
<xs:complexType name="interpretation">
  <xs:group ref="emma:interpretation.class" minOccurs="0" maxOccurs="unbounded" />
  <xs:attributeGroup ref="emma:interpretation.attribs" />
</xs:complexType>

Parent Element

An emma:interpretation element can be the child of any of the following elements.

  • emma:derivation

  • emma:emma

  • emma:group

  • emma:one-of

  • emma:sequence

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:lattice

[image]

emma:lattice
Send Feedback

An emma:lattice element represents a list of transitions between emma:node elements. An emma:arc element describes one possible transition between nodes. One use for an emma:lattice is to compactly represent different interpretations from speech recognition.

Element Definition

XML Copy image Copy Code
<xs:complexType name="lattice">
  <xs:choice minOccurs="0" maxOccurs="unbounded">
    <xs:element ref="emma:arc" />
    <xs:element ref="emma:node" />
  </xs:choice>
  <xs:attributeGroup ref="emma:lattice.attribs" />
</xs:complexType>

Parent Element

emma:interpretation

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:literal

[image]

emma:literal
Send Feedback

An emma:literal element contains output in the form of a string literal.

Element Definition

XML Copy image Copy Code
<xs:complexType name="literal" mixed="true" />

Parent Element

emma:interpretation

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:model

[image]

emma:model
Send Feedback

An emma:model element contains either an inline data model or a reference to a data model.

Element Definition

XML Copy image Copy Code
<xs:complexType name="model">
  <xs:choice minOccurs="0" maxOccurs="unbounded">
    <xs:any namespace="##other" processContents="lax" />
  </xs:choice>
  <xs:attributeGroup ref="emma:model.attribs" />
</xs:complexType>

Parent Element

emma:emma

Remarks

The data model plays a role analogous to a grammar, by specifying constraints on the content and structure of input data. The reference to a data model is contained in an emma:model.attribs attribute group.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:node

[image]

emma:node
Send Feedback

An emma:node element is one of two possible child elements of an emma:lattice element (the other child element is the emma:arc element).

Element Definition

XML Copy image Copy Code
<xs:complexType name="node">
  <xs:choice minOccurs="0" maxOccurs="unbounded">
    <xs:element ref="emma:info" />
  </xs:choice>
  <xs:attributeGroup ref="emma:node.attribs" />
</xs:complexType>

Parent Element

emma:lattice

Remarks

Information about the node is contained in an emma:node.attribs attribute group.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:one-of

[image]

emma:one-of
Send Feedback

An emma:one-of element is a container element that indicates a choice among a number of mutually exclusive child elements.

Element Definition

XML Copy image Copy Code
<xs:complexType name="one-of">
  <xs:group ref="emma:one-of.class" minOccurs="0" maxOccurs="unbounded" />
  <xs:attribute name="disjunction-type">
    <xs:simpleType>
      <xs:restriction base="xs:NMTOKEN">
        <xs:enumeration value="recognition" />
        <xs:enumeration value="understanding" />
        <xs:enumeration value="multi-device" />
        <xs:enumeration value="multi-process" />
      </xs:restriction>
    </xs:simpleType>
  </xs:attribute>
  <xs:attributeGroup ref="emma:group.attribs" />
</xs:complexType>

Parent Element

An emma:one-of element can be the child of any of the following elements.

  • emma:derivation

  • emma:emma

  • emma:group

  • emma:one-of

  • emma:sequence

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:sequence

[image]

emma:sequence
Send Feedback

An emma:sequence element contains interpretations of user input that are ordered in time.

Element Definition

XML Copy image Copy Code
<xs:complexType name="sequence">
  <xs:group ref="emma:sequence.class" minOccurs="0" maxOccurs="unbounded" />
  <xs:attributeGroup ref="emma:group.attribs" />
</xs:complexType>

Parent Element

An emma:sequence element can be the child of any of the following elements.

  • emma:derivation

  • emma:emma

  • emma:group

  • emma:one-of

  • emma:sequence

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EMMA Groups

[image]

EMMA Groups
Send Feedback

The following EMMA groups are described in this section.

  • emma:emma.class

  • emma:group.class

  • emma:interpretation.class

  • emma:one-of.class

  • emma:sequence.class

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:emma.class

[image]

emma:emma.class
Send Feedback

An emma:class group specifies the type of the immediate child of an emma:emma element.

Element Definition

XML Copy image Copy Code
<xs:group name="emma.class">
  <xs:annotation>
    <xs:documentation>
       emma content model
       </xs:documentation>
  </xs:annotation>
  <xs:choice>
    <xs:element ref="emma:derivation" />
    <xs:element ref="emma:grammar" />
    <xs:element ref="emma:model" />
    <xs:element ref="emma:endpoint-info" />
    <xs:element ref="emma:info" />
    <xs:element ref="emma:interpretation" />
    <xs:element ref="emma:one-of" />
    <xs:element ref="emma:group" />
    <xs:element ref="emma:sequence" />
  </xs:choice>
</xs:group>

Parent Element

emma:emma

Remarks

A reference to an emma:emma.class group can appear in an emma:emma element zero or more times.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:group.class

[image]

emma:group.class
Send Feedback

An emma:group.class group specifies the type of the immediate child of an emma:group element.

Element Definition

XML Copy image Copy Code
xs:group name="group.class">
  <xs:choice>
    <xs:element ref="emma:derived-from" />
    <xs:element ref="emma:group-info" />
    <xs:element ref="emma:info" />
    <xs:element ref="emma:interpretation" />
    <xs:element ref="emma:one-of" />
    <xs:element ref="emma:group" />
    <xs:element ref="emma:sequence" />
  </xs:choice>
</xs:group>

Parent Element

emma:group

Remarks

A reference to an emma:group.class group can appear within an emma:group zero or more times.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:interpretation.class

[image]

emma:interpretation.class
Send Feedback

An emma:interpretation.class group specifies the type of the immediate child of an emma:interpretation element.

Element Definition

XML Copy image Copy Code
<xs:group name="interpretation.class">
  <xs:choice>
    <xs:element ref="emma:derived-from" />
    <xs:element ref="emma:info" />
    <xs:element ref="emma:lattice" />
    <xs:element ref="emma:literal" />
    <xs:any namespace="##other" processContents="lax" />
  </xs:choice>
</xs:group>

Parent Element

emma:interpretation

Remarks

A reference to an emma:interpretation.class group can appear within an emma:interpretation element zero or more times.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:one-of.class

[image]

emma:one-of.class
Send Feedback

An emma:one-of.class group specifies the type of the immediate child of an emma:one-of element.

Element Definition

XML Copy image Copy Code
<xs:group name="one-of.class">
  <xs:choice>
    <xs:element ref="emma:derived-from" />
    <xs:element ref="emma:info" />
    <xs:element ref="emma:interpretation" />
    <xs:element ref="emma:one-of" />
    <xs:element ref="emma:group" />
    <xs:element ref="emma:sequence" />
  </xs:choice>
</xs:group>

Parent Element

emma:one-of

Remarks

A reference to an emma:one-of.class group can appear within an emma:one-of element zero or more times.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:sequence.class

[image]

emma:sequence.class
Send Feedback

An emma:sequence.class group specifies the type of the immediate child of an emma:sequence element.

Element Definition

XML Copy image Copy Code
xs:group name="sequence.class">
  <xs:choice>
    <xs:element ref="emma:derived-from" />
    <xs:element ref="emma:info" />
    <xs:element ref="emma:interpretation" />
    <xs:element ref="emma:one-of" />
    <xs:element ref="emma:group" />
    <xs:element ref="emma:sequence" />
  </xs:choice>
</xs:group>

Parent Element

emma:sequence

Remarks

A reference to an emma:sequence.class group can appear within an emma:sequence element zero or more times.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EMMA Attribute Groups

[image]

EMMA Attribute Groups
Send Feedback

The following EMMA attribute groups are described in this section.

  • emma:arc.attribs

  • emma:derived-from.attribs

  • emma:endpoint.attribs

  • emma:grammar.attribs

  • emma:group.attribs

  • emma:group-info.attribs

  • emma:interpretation.attribs

  • emma:lattice.attribs

  • emma:model.attribs

  • emma:node.attribs

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:arc.attribs

[image]

emma:arc.attribs
Send Feedback

An emma:arc.attribs attribute group contains information about an emma:arc element.

Element Definition

XML Copy image Copy Code
<xs:attributeGroup name="arc.attribs">
  <xs:attribute name="from" type="xs:nonNegativeInteger" use="required" />
  <xs:attribute name="to" type="xs:nonNegativeInteger" use="required" />
  <xs:attribute ref="emma:start" />
  <xs:attribute ref="emma:end" />
  <xs:attribute ref="emma:offset-to-start" />
  <xs:attribute ref="emma:duration" />
  <xs:attribute ref="emma:confidence" />
  <xs:attribute ref="emma:cost" />
  <xs:attribute ref="emma:lang" />
  <xs:attribute ref="emma:medium" />
  <xs:attribute ref="emma:mode" />
  <xs:attribute ref="emma:source" />
</xs:attributeGroup>

Parent Element

emma:arc

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:derived-from.attribs

[image]

emma:derived-from.attribs
Send Feedback

An emma:derived-from.attribs attribute group contains information about an emma:derived-from element.

Element Definition

XML Copy image Copy Code
<xs:attributeGroup name="derived-from.attribs">
  <xs:attribute name="resource" type="xs:anyURI" use="required" />
  <xs:attribute name="composite" type="xs:boolean" />
</xs:attributeGroup>

Parent Element

emma:derived-from

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:endpoint.attribs

[image]

emma:endpoint.attribs
Send Feedback

An emma:endpoint.attribs attribute group contains information about an emma:endpoint element.

Element Definition

XML Copy image Copy Code
<xs:attributeGroup name="endpoint.attribs">
  <xs:attribute name="id" type="xs:ID" use="required" />
  <xs:attribute ref="emma:endpoint-role" />
  <xs:attribute ref="emma:endpoint-address" />
  <xs:attribute ref="emma:message-id" />
  <xs:attribute ref="emma:port-num" />
  <xs:attribute ref="emma:port-type" />
  <xs:attribute ref="emma:endpoint-pair-ref" />
  <xs:attribute ref="emma:service-name" />
  <xs:attribute ref="emma:media-type" />
  <xs:attribute ref="emma:medium" />
  <xs:attribute ref="emma:mode" />
</xs:attributeGroup>

Parent Element

emma:endpoint

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:grammar.attribs

[image]

emma:grammar.attribs
Send Feedback

An emma:grammar.attribs attribute group contains information about an emma:grammar element.

Element Definition

XML Copy image Copy Code
<xs:attributeGroup name="grammar.attribs">
  <xs:attribute name="id" type="xs:ID" use="required" />
  <xs:attribute name="ref" type="xs:anyURI" use="required" />
</xs:attributeGroup>

Parent Element

emma:grammar

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:group.attribs

[image]

emma:group.attribs
Send Feedback

An emma:group.attribs attribute group contains information about an emma:group element.

Element Definition

XML Copy image Copy Code
<xs:attributeGroup name="group.attribs">
  <xs:attribute name="id" type="xs:ID" use="required" />
  <xs:attribute ref="emma:tokens" />
  <xs:attribute ref="emma:process" />
  <xs:attribute ref="emma:lang" />
  <xs:attribute ref="emma:signal" />
  <xs:attribute ref="emma:signal-size" />
  <xs:attribute ref="emma:media-type" />
  <xs:attribute ref="emma:confidence" />
  <xs:attribute ref="emma:source" />
  <xs:attribute ref="emma:start" />
  <xs:attribute ref="emma:end" />
  <xs:attribute ref="emma:time-ref-uri" />
  <xs:attribute ref="emma:time-ref-anchor-point" />
  <xs:attribute ref="emma:offset-to-start" />
  <xs:attribute ref="emma:duration" />
  <xs:attribute ref="emma:medium" />
  <xs:attribute ref="emma:mode" />
  <xs:attribute ref="emma:function" />
  <xs:attribute ref="emma:verbal" />
  <xs:attribute ref="emma:cost" />
  <xs:attribute ref="emma:grammar-ref" />
  <xs:attribute ref="emma:endpoint-info-ref" />
  <xs:attribute ref="emma:model-ref" />
  <xs:attribute ref="emma:dialog-turn" />
</xs:attributeGroup>

Parent Element

emma:group

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:group-info.attribs

[image]

emma:group-info.attribs
Send Feedback

An emma:group-info.attribs attribute group contains information about an emma:group-info element.

Element Definition

XML Copy image Copy Code
<xs:attributeGroup name="group-info.attribs">
  <xs:attribute name="ref" type="xs:anyURI" />
</xs:attributeGroup>

Parent Element

emma:group-info

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:interpretation.attribs

[image]

emma:interpretation.attribs
Send Feedback

An emma:interpretation.attribs attribute group contains information about an emma:interpretation element.

Element Definition

XML Copy image Copy Code
<xs:attributeGroup name="interpretation.attribs">
  <xs:attributeGroup ref="emma:group.attribs" />
  <xs:attribute ref="emma:no-input" />
  <xs:attribute ref="emma:uninterpreted" />
</xs:attributeGroup>

Parent Element

emma:interpretation

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:lattice.attribs

[image]

emma:lattice.attribs
Send Feedback

An emma:lattice.attribs attribute group contains information about an emma:lattice element.

Element Definition

XML Copy image Copy Code
<xs:attributeGroup name="lattice.attribs">
  <xs:attribute name="initial" type="xs:nonNegativeInteger" use="required" />
  <xs:attribute name="final" use="required">
    <xs:simpleType>
      <xs:list itemType="xs:nonNegativeInteger" />
    </xs:simpleType>
  </xs:attribute>
  <xs:attribute ref="emma:time-ref-uri" />
  <xs:attribute ref="emma:time-ref-anchor-point" />
</xs:attributeGroup>

Parent Element

emma:lattice

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:model.attribs

[image]

emma:model.attribs
Send Feedback

An emma:model.attribs attribute group contains information about an emma:model element.

Element Definition

XML Copy image Copy Code
<xs:attributeGroup name="model.attribs">
  <xs:attribute name="id" type="xs:ID" use="required" />
  <xs:attribute name="ref" type="xs:anyURI" />
</xs:attributeGroup>

Parent Element

emma:model

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


emma:node.attribs

[image]

emma:node.attribs
Send Feedback

An emma:node.attribs attribute group contains information about an emma:node element.

Element Definition

XML Copy image Copy Code
<xs:attributeGroup name="node.attribs">
  <xs:attribute name="node-number" type="xs:nonNegativeInteger" use="required" />
  <xs:attribute ref="emma:confidence" />
  <xs:attribute ref="emma:cost" />
</xs:attributeGroup>

Parent Element

emma:node

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Microsoft Extensions to EMMA

[image]

Microsoft Extensions to EMMA
Send Feedback

This topic presents three schema definitions for Microsoft extensions to EMMA.

WebRecoExtensions.xsd

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="WebRecoExtensions"
    targetNamespace="http://www.microsoft.com/xmlns/webreco"
    elementFormDefault="qualified"
    xmlns="http://www.microsoft.com/xmlns/webreco"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:emma="http://www.w3.org/2003/04/emma"
>

    <xs:import schemaLocation="http://www.w3.org/TR/2009/REC-emma-20090210/emma.xsd" namespace="http://www.w3.org/2003/04/emma"/>

    <!-- Attribute type for 'ms:actualConfidence' -->
    <xs:simpleType name="actualConfidence">
        <xs:restriction base="xs:integer">
            <xs:minInclusive value="-1"/>
            <xs:maxInclusive value="1"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- Attribute type for 'confidencelevel', 'speedvsaccuracy' etc. -->
    <xs:simpleType name="percent">
        <xs:restriction base="xs:decimal">
            <xs:minInclusive value="0.0"/>
            <xs:maxInclusive value="1.0"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- Attribute type for 'timeout', 'completetimeout' etc. -->
    <xs:simpleType name="duration">
        <xs:restriction base="xs:string">
            <xs:pattern value="\+?(([0-9]*\.[0-9]+)|([0-9]+))(s|ms)|(-|\+)?(0+|0*\.0+)(s|ms)?"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- Attribute type for 'dataType' and 'valueType' -->
    <xs:simpleType name="ecmaDataType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="object"/>
            <xs:enumeration value="array"/>
            <xs:enumeration value="string"/>
            <xs:enumeration value="number"/>
            <xs:enumeration value="boolean"/>
            <xs:enumeration value="undefined"/>
            <xs:enumeration value="null"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- Type for 'ms:properties' element -->
    <xs:complexType name="properties">
        <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:element ref="property"/>
        </xs:choice>
        <xs:attribute name="time" type="xs:dateTime"/>
        <xs:attribute name="status" type="xs:string"/>
        <xs:attribute name="reason" type="xs:integer"/>
        <xs:attribute name="timeout" type="duration"/>
        <xs:attribute name="completetimeout" type="duration"/>
        <xs:attribute name="incompletetimeout" type="duration"/>
        <xs:attribute name="requesttimeout" type="duration"/>
        <xs:attribute name="confidencelevel" type="percent"/>
        <xs:attribute name="sensitivity" type="percent"/>
        <xs:attribute name="speedvsaccuracy" type="percent"/>
        <xs:attribute name="engineproperty" type="xs:string"/>
        <xs:attribute name="maxnbest" type="xs:positiveInteger"/>
        <xs:attribute name="enginerequiredattributes" type="xs:string"/>
        <xs:attribute name="engineoptionalattributes" type="xs:string"/>
    </xs:complexType>

    <!-- Type for 'ms:property' element -->
    <xs:complexType name="property">
        <xs:attribute name="name" type="xs:string" use="required"/>
        <xs:attribute name="value" type="xs:string" use="required"/>
    </xs:complexType>

    <!-- Type for 'ms:audio' element -->
    <xs:complexType name="audio" mixed="true">
        <xs:attribute name="type" type="xs:string"/>
        <xs:attribute name="ref" type="xs:anyURI"/>
    </xs:complexType>

    <!-- Type for 'ms:transcript' element -->
    <xs:complexType name="transcript">
        <xs:choice maxOccurs="unbounded">
            <xs:element ref="original"/>
            <xs:element ref="matched-string"/>
            <xs:element ref="error"/>
            <xs:element ref="emma:one-of"/>
            <xs:element ref="emma:interpretation"/>
        </xs:choice>
        <xs:attribute ref="status"/>
    </xs:complexType>

    <!-- Type for 'ms:matched-string' element -->
    <xs:complexType name="matched-string" mixed="true">
        <xs:attribute name="mappingrulelog" type="xs:string"/>
        <xs:attribute name="modificationlevel" type="xs:nonNegativeInteger"/>
    </xs:complexType>

    <!-- Type for 'ms:initial-engine-state' element -->
    <xs:complexType name="initial-engine-state" mixed="true">
        <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:any namespace="##any" processContents="lax"/>
        </xs:choice>
    </xs:complexType>

    <!-- Type for 'ms:active-grammars' element -->
    <xs:complexType name="active-grammars">
        <xs:choice maxOccurs="unbounded">
            <xs:element ref="grammar"/>
        </xs:choice>
    </xs:complexType>

    <!-- Type for 'ms:grammar' element -->
    <xs:complexType name="grammar">
        <xs:attribute name="weight" type="xs:decimal"/>
        <xs:attribute ref="emma:grammar-ref" use="required"/>
    </xs:complexType>

    <!-- Type for 'ms:item' element -->
    <xs:complexType name="item" mixed="true">
        <xs:choice minOccurs ="0" maxOccurs="unbounded">
            <xs:any namespace="##any"/>
        </xs:choice>
        <xs:attribute ref="index"/>
        <xs:attribute ref="dataType"/>
        <xs:attribute ref="valueType"/>
    </xs:complexType>

    <!-- Type for 'ms:sapiPhraseReplacement' element -->
    <xs:complexType name="sapiPhraseReplacement">
        <xs:attribute ref="displayAttributes"/>
    </xs:complexType>

    <!-- Type for 'ms:sapiPhraseElement' element -->
    <xs:complexType name="sapiPhraseElement">
        <xs:attribute ref="displayAttributes"/>
        <xs:attribute ref="pronunciation"/>
        <xs:attribute ref="lexicalForm"/>
        <xs:attribute ref="actualConfidence"/>
    </xs:complexType>

    <!-- Type for 'ms:error' element -->
    <xs:complexType name="error" mixed="true">
        <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:any namespace="##any" processContents="lax"/>
        </xs:choice>
        <xs:anyAttribute namespace="##any" processContents="lax"/>
    </xs:complexType>

    <!-- Attributes -->
    <xs:attribute name="status" type="xs:string"/>
    <xs:attribute name="dataType" type="xs:string"/>
    <xs:attribute name="valueType" type="xs:string"/>
    <xs:attribute name="typespace" type="xs:string"/>
    <xs:attribute name="actualConfidence" type="actualConfidence"/>
    <xs:attribute name="displayAttributes" type="xs:nonNegativeInteger"/>
    <xs:attribute name="pronunciation" type="xs:string"/>
    <xs:attribute name="lexicalForm" type="xs:string"/>
    <xs:attribute name="index" type="xs:nonNegativeInteger"/>
    <xs:attribute name="length" type="xs:nonNegativeInteger"/>

    <!-- Elements -->
    <xs:element name="properties" type="properties"/>
    <xs:element name="property" type="property"/>
    <xs:element name="audio" type="audio"/>
    <xs:element name="initial-engine-state" type="initial-engine-state"/>
    <xs:element name="transcript" type="transcript"/>
    <xs:element name="original" type="xs:string"/>
    <xs:element name="matched-string" type="matched-string"/>
    <xs:element name="sessionid" type="xs:string"/>
    <xs:element name="requestid" type="xs:string"/>
    <xs:element name="logstring" type="xs:string"/>
    <xs:element name="active-grammars" type="active-grammars"/>
    <xs:element name="grammar" type="grammar"/>
    <xs:element name="error" type="error"/>

</xs:schema>

EmmaWithWebRecoExtension.xsd

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="EmmaWithWebRecoExtensions"
  targetNamespace="http://www.w3.org/2003/04/emma"
  elementFormDefault="qualified"
  xmlns="http://www.w3.org/2003/04/emma"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:ms="http://www.microsoft.com/xmlns/webreco"
  xmlns:tm="http://www.tellme.com/ns/2009/01/emma"
>

  <xs:import schemaLocation="WebRecoExtensions.xsd" namespace="http://www.microsoft.com/xmlns/webreco"/>

  <xs:import schemaLocation="TellMeExtensions.xsd" namespace="http://www.tellme.com/ns/2009/01/emma"/>

  <xs:redefine schemaLocation="http://www.w3.org/TR/2009/REC-emma-20090210/emma.xsd">

    <!-- Add 'ms:status' and 'tm:version' attributes to emma:emma -->
    <xs:complexType name="emma">
      <xs:complexContent>
        <xs:extension base="emma">
          <xs:attribute ref="ms:status" />
          <xs:attribute ref="tm:version" />
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>

    <!-- Add 'ms:status' attribute to emma:info -->
    <xs:complexType name="info">
      <xs:complexContent>
        <xs:extension base="info">
          <xs:attribute ref="ms:status" />
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>

    <!-- Add 'tm:name' attribute to emma:grammar  -->
    <xs:complexType name="grammar">
      <xs:complexContent>
        <xs:extension base="grammar">
          <xs:attribute ref="tm:name" />
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>

    <!-- Add 'ms:dataType' and 'ms:valueType' attributes to emma:literal -->
    <xs:complexType name="literal">
      <xs:complexContent>
        <xs:extension base="literal">
          <xs:attribute ref="ms:dataType" />
          <xs:attribute ref="ms:valueType" />
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>

    <!-- Add 'ms:typespace' and 'ms:length' attributes to emma:interpretation -->
    <xs:complexType name="interpretation">
      <xs:complexContent>
        <xs:extension base="interpretation">
          <xs:choice>
            <xs:any minOccurs="0" maxOccurs="unbounded" namespace ="##local" processContents="lax"/>
          </xs:choice>
          <xs:attribute ref="ms:typespace" />
          <xs:attribute ref="ms:length" />
        </xs:extension>
      </xs:complexContent>
    </xs:complexType>

  </xs:redefine>

</xs:schema>

TellMeExtensions.xsd

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="TellMeExtensions"
  targetNamespace="http://www.tellme.com/ns/2009/01/emma"
  elementFormDefault="qualified"
  xmlns="http://www.tellme.com/ns/2009/01/emma"
  xmlns:mstns="http://www.tellme.com/ns/2009/01/emma"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:attribute name="version" type="xs:string"/>
  <xs:attribute name="name" type="xs:string"/>
</xs:schema>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Simulator Results Analyzer Reference Manual

[image]

Simulator Results Analyzer Reference Manual
See Also Send Feedback

Simulator Results Analyzer is a command-line tool that analyzes EMMA recognition results produced by Simulator.exe. The tool outputs the result of the analysis to an XML-format file. You can feed the output XML file into your own tools for further analysis.

You can use the analysis performed by the Simulator Results Analyzer to tune your speech applications and the grammars they use. See Simulator/Simulator Results Analyzer Usage Scenarios.

The Simulator Results Analyzer Reference Manual contains the following topics.

  • Simulator Results Analyzer Command-Line Syntax

  • Simulator Results Analyzer Input and Output File Format

  • Simulator Results Analyzer Error Messages and Format

  • Simulator Results Analyzer Interpreting the Results

See Also

Concepts

Simulator/Simulator Results Analyzer Usage Scenarios
Simulator Reference Manual
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Simulator Results Analyzer Command-Line Syntax

[image]

Simulator Results Analyzer Command-Line Syntax
Send Feedback

The command-line syntax for Simulator Results Analyzer contains the following options and values:

SimulatorResultsAnalyzer [-?] /In <input file name(s)> /Out <output file name> /SemanticPath <path of semantic value node(s)> /RecoConfig <configuration file name>

The following table describes the command-line option names and values for Simulator Results Analyzer.

Option Name

Description

/In

Required. One or more EMMA XML files to be analyzed.

If multiple input files are specified and a file cannot be found, the Simulator Results Analyzer issues a warning and begins processing the next file in the list. Wildcards (* and ?) can be used.

/Out

Required. The output file with the results of analysis.

/SemanticPath

Optional. The XML node(s) to use when comparing semantics. If the value for this option begins with a forward slash, you must precede it with an additional forward slash, for example //MyXmlNode.

The value of the /SemanticPath option is used to filter utterances and compare their semantics. If the /SemanticPath option is not specified, the Simulator Results Analyzer processes all utterances and compares their semantics, both simple and complex.

The default value of the /SemanticPath option is a string that contains a single period ".". This option value indicates that no filtering should occur and that all semantics comparisons are to occur at the root level.

For more information, see Semantic Value Selection.

/RecoConfig

Optional. The name of the configuration file to use for the speech recognition engine. If not specified, the tool will look for a default configuration file named "RecoConfig.xml" in the current working directory and in the directory that contains SimulatorResultsAnalyzer.exe.

/?

Optional. Displays a list of acceptable option/value pairs.

Note Note

  • Command-line options and values are not case-sensitive.

  • Command-line options can be preceded by a forward slash (0x002F), a dash (0x002d), an en dash (0x2013), an em dash (0x2014), or a horizontal bar (0x2015).

  • You can enter option/value pairs in any sequence.

Caution note Caution

If an existing file has the same name as the file name specified by the /Out option, it will be overwritten. The tool does not warn that a file will be overwritten.

Examples

Get help for using command-line options and values with Simulator Results Analyzer.

SimulatorResultsAnalyzer.exe /?

A sample command-line syntax for simple semantics: Analyze EMMAInput.xml and send the output to Results.xml. When '.' is specified as the value for the /SemanticPath option, only utterances with simple semantics are filtered.

SimulatorResultsAnalyzer /In EMMAInput.xml /Out Results.xml /SemanticPath "."

A sample command-line syntax for complex semantics: Analyze all files whose names match the wildcard specification SimOutput*.xml and send the output to Results.xml.

SimulatorResultsAnalyzer -In SimOutput*.xml -Out Results.xml -SemanticPath //city

A sample command-line syntax for complex semantics: Analyze the files whose names match the wildcard specification SimOutput*.xml and AnotherFile.xml, and send the output to Results.xml.

SimulatorResultsAnalyzer /In SimOutput*.xml AnotherFile.xml /Out Results.xml /SemanticPath //city

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Semantic Value Selection

[image]

Semantic Value Selection
Send Feedback

The /SemanticPath option uses XPath syntax to identify the specific semantic value in the emma:interpretation nodes of both the EMMATranscription and EMMAAudio section of the EMMA document. If more than one transcription is present, the semantic values of each transcription are compared with the semantic of the recognition results and a match of any one of the transcription semantics with the recognition semantics is counted as a match. Only the top recognition result from the N-Best list is compared.

Simple Semantics

In the case where simple semantics are used (out = "Coffee"), the semantic value is listed in the output EMMA document as a literal. This can be seen in the following example.

XML Copy image Copy Code
<emma:interpretation emma:tokens="coffee" id="utterance-1-reco-nbest-1"
    emma:start="1251745149648" emma:end="1251745150878" emma:confidence="0.8866627"
    ms:typespace="ECMA-262" emma:grammar-ref="utterance-1-grammar-0" emma:lang="en-us">
  <emma:derived-from resource="#utterance-1-rule-tree-1" composite="false" />
  <emma:literal ms:dataType="string" ms:valueType="string">Coffee</emma:literal>
</emma:interpretation>

In this case, the XPath path specified in the SemanticPath parameter is ".". When "." is specified, utterances that contain complex semantics in either the transcription or the interpretation elements are skipped.

Complex Semantics

In the case of complex semantics, an XML document constitutes the semantic values. An XPath path rooted at the level of the emma:interpretation identifies the relevant semantic values to be compared. Utterances that do not contain the specified semantic value(s) in either the transcription or the interpretation are skipped.

If the XPath path is a leaf node, the semantic value is compared to the corresponding semantic value in the transcription. A match is recorded if the values are exactly the same. If the XPath path is not a leaf node, the entire sub-tree of semantic values is matched. Each node in the subtree must exactly the corresponding node in the subtree in the semantics. The names of the nodes must match and the values of each of the leaf nodes in the subtree must also match.

For complex semantics, multiple XPath values can be specified. All semantics specified must be matched in order for the recognition to be considered to have been correctly matched.

XML Copy image Copy Code
<emma:one-of id="r1" emma:start="1087995961542" emma:end="1087995963542">
  <emma:interpretation id="int1" emma:confidence="0.75" emma:tokens="flights from boston to denver">
    <origin emma:confidence="0.981347" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">Boston</origin>
    <destination emma:confidence="0.952872" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">Denver</destination>
  </emma:interpretation>

  <emma:interpretation id="int2" emma:confidence="0.68" emma:tokens="flights from austin to denver">
    <origin emma:confidence="0.728751" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">Austin</origin>
    <destination emma:confidence="0.947814" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">Denver</destination>
  </emma:interpretation>
</emma:one-of>

If attributes have been added to the semantics result, the value of these attributes must also match. EMMA and Microsoft attributes, such as emma:confidence and ms:actualConfidence are ignored.

The following is an example of semantic results with attributes of "method" and "ratio".

XML Copy image Copy Code
<martini method="shaken">
  <gin ratio="8">Bombay Sapphire</gin>
  <vermouth ratio="1">Noilly Prat</vermouth>
</martini>

When arrays are present in the selected semantic results, the number of items in the array must match, as well as each individual element of the array.

The following is an example of semantic results with an array (topping).

XML Copy image Copy Code
<pizza>
  <number>3</number>
  <pizzasize>large</pizzasize>

  <topping length="2">
    <item index="0">pepperoni</item>
    <item index="1">mushrooms</item>
  </topping>
</pizza>
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Simulator Results Analyzer Input and Output File Format

[image]

Simulator Results Analyzer Input and Output File Format
Send Feedback

Simulator Results Analyzer takes as input an EMMA document created by Simulator and produces an output file in EMMA format.

Input File Format

EMMA-format files used as input to Simulator Results Analyzer can contain the following information:

  • Detailed recognition results (that is, the actual recognition, confidence values, semantics, pronunciation, lattice, rule tree, and other recognition results)

  • A unique RequestId and SessionId for the recognition

The following is an example of an EMMA file generated by Simulator to use as input for Simulator Results Analyzer. You can find this file in the \Samples\Sample Simulator folder where you installed the Microsoft Speech Platform SDK 11. The audio files and grammars referenced in this document are in the Waves and Grammars folders, respectively.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<emma:emma version="1.0" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma" xmlns="http://www.example.com/example">
  <emma:grammar id="grammar0" ref="grammars\menu_choices.grxml" />
  <emma:grammar id="grammar1" ref="grammars\help_choices.grxml" />
  <emma:group id="toplevel">

    <emma:group id="utterance_0.0.0.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_00.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>sports</ms:original>
          <emma:one-of id="utterance_0.0.0.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.0.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.0.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>51b96944-25a7-4bc8-902c-5066ee5eb369</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.0.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.0.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="0.5638461" emma:time-ref-uri="#utterance_0.0.0.0-reco-nbest-list" emma:offset-to-start="330" emma:duration="810" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.0.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.5618123" ms:actualConfidence="0" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
          <grammar emma:confidence="0.5618123" ms:actualConfidence="0" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>

    <emma:group id="utterance_0.0.1.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_01.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>[noise]</ms:original>
          <emma:interpretation emma:uninterpreted="true" id="utterance_0.0.1.0-transcript-reco-nbest-list-1" emma:mode="voice" emma:medium="acoustic" />
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>0d758c5c-6d32-45a5-ba9e-308a8c036832</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:interpretation emma:uninterpreted="true" id="utterance_0.0.1.0-reco-nbest-list-1" emma:mode="voice" emma:medium="acoustic" />
    </emma:group>

    <emma:group id="utterance_0.0.2.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_02.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>sports</ms:original>
          <emma:one-of id="utterance_0.0.2.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.2.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.2.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>c2945818-5fa6-455c-ba5e-612a74da3187</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.2.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.2.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="0.9479059" emma:time-ref-uri="#utterance_0.0.2.0-reco-nbest-list" emma:offset-to-start="140" emma:duration="840" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.2.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.8497295" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
          <grammar emma:confidence="0.8497295" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>

    <emma:group id="utterance_0.0.3.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_03.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>weather</ms:original>
          <emma:one-of id="utterance_0.0.3.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.3.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="weather" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.3.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>b6643747-e6c3-4776-bacb-a853e4ccb4f9</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.3.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.3.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="weather" emma:confidence="0.9449926" emma:time-ref-uri="#utterance_0.0.3.0-reco-nbest-list" emma:offset-to-start="220" emma:duration="750" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.3.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.9668913" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
          <grammar emma:confidence="0.9668913" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>

    <emma:group id="utterance_0.0.4.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_04.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>news</ms:original>
          <emma:one-of id="utterance_0.0.4.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.4.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="news" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.4.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">NEWS</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>1c0a2052-bdc2-4e7b-acfa-c40e901b735f</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.4.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.4.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="news" emma:confidence="0.9319434" emma:time-ref-uri="#utterance_0.0.4.0-reco-nbest-list" emma:offset-to-start="230" emma:duration="930" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.4.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.9612538" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">NEWS</application>
          <grammar emma:confidence="0.9612538" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>

    <emma:group id="utterance_0.0.5.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_05.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>top stories</ms:original>
          <emma:interpretation emma:uninterpreted="true" id="utterance_0.0.5.0-transcript-reco-nbest-list-1" emma:mode="voice" emma:medium="acoustic" />
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>c553ff53-0bef-42ce-aad7-394d2d77d904</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:interpretation emma:uninterpreted="true" id="utterance_0.0.5.0-reco-nbest-list-1" emma:mode="voice" emma:medium="acoustic" />
    </emma:group>

    <emma:group id="utterance_0.0.6.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_06.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>sport</ms:original>
          <emma:interpretation emma:uninterpreted="true" id="utterance_0.0.6.0-transcript-reco-nbest-list-1" emma:mode="voice" emma:medium="acoustic" />
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>db35f5f0-7c87-45e8-a9b0-f393ce4a7025</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.6.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.6.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="0.9216749" emma:time-ref-uri="#utterance_0.0.6.0-reco-nbest-list" emma:offset-to-start="130" emma:duration="600" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.6.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.9370015" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
          <grammar emma:confidence="0.9370015" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>

    <emma:group id="utterance_0.0.7.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_07.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>stock quotes</ms:original>
          <emma:one-of id="utterance_0.0.7.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.7.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="stock quotes" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.7.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <longform emma:confidence="1" ms:actualConfidence="1" ms:dataType="boolean" ms:valueType="boolean" xmlns="">true</longform>
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">STOCKS</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>dc25a5ce-e546-4376-91f4-eb7b2e924721</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.7.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.7.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="stock quotes" emma:confidence="0.8928868" emma:time-ref-uri="#utterance_0.0.7.0-reco-nbest-list" emma:offset-to-start="250" emma:duration="970" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.7.0-rule-tree-1" composite="false" />
          <longform emma:confidence="0.8609061" ms:actualConfidence="1" ms:dataType="boolean" ms:valueType="boolean" xmlns="">true</longform>
          <application emma:confidence="0.8609061" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">STOCKS</application>
          <grammar emma:confidence="0.8609061" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>

    <emma:group id="utterance_0.0.8.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_08.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>weather</ms:original>
          <emma:one-of id="utterance_0.0.8.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.8.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="weather" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.8.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>6fe369ac-a87a-4f16-ab25-ec7f5ca265ee</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.8.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.8.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="weather" emma:confidence="0.6197259" emma:time-ref-uri="#utterance_0.0.8.0-reco-nbest-list" emma:offset-to-start="230" emma:duration="790" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.8.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.6058497" ms:actualConfidence="0" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
          <grammar emma:confidence="0.6058497" ms:actualConfidence="0" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>

    <emma:group id="utterance_0.0.9.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_09.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>weather</ms:original>
          <emma:one-of id="utterance_0.0.9.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.9.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="weather" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.9.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>7a2c3ee0-7fbc-487f-b617-351ca8e458b9</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.9.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.9.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="weather" emma:confidence="0.9403493" emma:time-ref-uri="#utterance_0.0.9.0-reco-nbest-list" emma:offset-to-start="230" emma:duration="770" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.9.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.962913" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
          <grammar emma:confidence="0.962913" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>

    <emma:group id="utterance_0.0.10.0">
      <emma:info ms:status="OK">
        <ms:audio ref="waves/utt_10.wav" type="audio/x-wav" />
        <ms:transcript ms:status="OK">
          <ms:original>sports</ms:original>
          <emma:one-of id="utterance_0.0.10.0-transcript-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
            <emma:interpretation id="utterance_0.0.10.0-transcript-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="1" emma:time-ref-uri="#utterance_0.0.10.0-transcript-reco-nbest-list" emma:offset-to-start="0" emma:duration="0" ms:typespace="ECMA-262" ms:dataType="object">
              <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
              <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
            </emma:interpretation>
          </emma:one-of>
        </ms:transcript>
        <ms:active-grammars>
          <ms:grammar emma:grammar-ref="grammar0" />
          <ms:grammar emma:grammar-ref="grammar1" />
        </ms:active-grammars>
        <ms:requestid>18d942f8-6278-4bc5-8ed1-9b9b75aa4a22</ms:requestid>
        <ms:sessionid>5af4af52-1095-406c-a27c-83d42ed287c1</ms:sessionid>
      </emma:info>
      <emma:one-of id="utterance_0.0.10.0-reco-nbest-list" disjunction-type="understanding" emma:medium="acoustic" emma:mode="voice">
        <emma:interpretation id="utterance_0.0.10.0-reco-nbest-1" emma:grammar-ref="grammar0" emma:lang="en-US" emma:tokens="sports" emma:confidence="0.8278435" emma:time-ref-uri="#utterance_0.0.10.0-reco-nbest-list" emma:offset-to-start="140" emma:duration="810" ms:typespace="ECMA-262" ms:dataType="object">
          <emma:derived-from resource="#utterance_0.0.10.0-rule-tree-1" composite="false" />
          <application emma:confidence="0.8705698" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
          <grammar emma:confidence="0.8705698" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
        </emma:interpretation>
      </emma:one-of>
    </emma:group>
  </emma:group>

  <emma:derivation>
    <emma:one-of id="utterance_0.0.0.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.0.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.0.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.5638461" emma:offset-to-start="0" emma:duration="690">sports<emma:info><ms:sapiPhraseElement ms:pronunciation="S P AO RA T S" ms:lexicalForm="sports" ms:displayAttributes="2" ms:actualConfidence="0" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.0.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.0.0-rule-tree-1" emma:confidence="0.5638461" emma:time-ref-uri="#utterance_0.0.0.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.0.0-word-list-1" composite="false" />
        <top emma:confidence="0.5638461" ms:actualConfidence="0" emma:offset-to-start="0" emma:duration="690" xmlns="">sports</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.2.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.2.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.2.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.9479059" emma:offset-to-start="0" emma:duration="740">sports<emma:info><ms:sapiPhraseElement ms:pronunciation="S P AO RA T S" ms:lexicalForm="sports" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.2.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.2.0-rule-tree-1" emma:confidence="0.9479059" emma:time-ref-uri="#utterance_0.0.2.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.2.0-word-list-1" composite="false" />
        <top emma:confidence="0.9479059" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="740" xmlns="">sports</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.3.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.3.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.3.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.9449926" emma:offset-to-start="0" emma:duration="650">weather<emma:info><ms:sapiPhraseElement ms:pronunciation="W EH DH AX RA" ms:lexicalForm="weather" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.3.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.3.0-rule-tree-1" emma:confidence="0.9449926" emma:time-ref-uri="#utterance_0.0.3.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.3.0-word-list-1" composite="false" />
        <top emma:confidence="0.9449926" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="650" xmlns="">weather</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.4.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.4.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.4.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.9319434" emma:offset-to-start="0" emma:duration="820">news<emma:info><ms:sapiPhraseElement ms:pronunciation="N U Z" ms:lexicalForm="news" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.4.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.4.0-rule-tree-1" emma:confidence="0.9319434" emma:time-ref-uri="#utterance_0.0.4.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.4.0-word-list-1" composite="false" />
        <top emma:confidence="0.9319434" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="820" xmlns="">news</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.6.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.6.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.6.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.9216749" emma:offset-to-start="0" emma:duration="500">sports<emma:info><ms:sapiPhraseElement ms:pronunciation="S P AO RA T S" ms:lexicalForm="sports" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.6.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.6.0-rule-tree-1" emma:confidence="0.9216749" emma:time-ref-uri="#utterance_0.0.6.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.6.0-word-list-1" composite="false" />
        <top emma:confidence="0.9216749" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="500" xmlns="">sports</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.7.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.7.0-word-list-1">
        <emma:lattice initial="1" final="3" emma:time-ref-uri="#utterance_0.0.7.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.8581361" emma:offset-to-start="0" emma:duration="430">stock<emma:info><ms:sapiPhraseElement ms:pronunciation="S T AA K" ms:lexicalForm="stock" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
          <emma:arc from="2" to="3" emma:confidence="0.9216229" emma:offset-to-start="430" emma:duration="520">quotes<emma:info><ms:sapiPhraseElement ms:pronunciation="K W O T S" ms:lexicalForm="quotes" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.7.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.7.0-rule-tree-1" emma:confidence="0.8928868" emma:time-ref-uri="#utterance_0.0.7.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.7.0-word-list-1" composite="false" />
        <top emma:confidence="0.8928868" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="950" xmlns="">stock quotes</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.8.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.8.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.8.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.6197259" emma:offset-to-start="0" emma:duration="680">weather<emma:info><ms:sapiPhraseElement ms:pronunciation="W EH DH AX RA" ms:lexicalForm="weather" ms:displayAttributes="2" ms:actualConfidence="0" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.8.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.8.0-rule-tree-1" emma:confidence="0.6197259" emma:time-ref-uri="#utterance_0.0.8.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.8.0-word-list-1" composite="false" />
        <top emma:confidence="0.6197259" ms:actualConfidence="0" emma:offset-to-start="0" emma:duration="680" xmlns="">weather</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.9.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.9.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.9.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.9403493" emma:offset-to-start="0" emma:duration="680">weather<emma:info><ms:sapiPhraseElement ms:pronunciation="W EH DH AX RA" ms:lexicalForm="weather" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.9.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.9.0-rule-tree-1" emma:confidence="0.9403493" emma:time-ref-uri="#utterance_0.0.9.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.9.0-word-list-1" composite="false" />
        <top emma:confidence="0.9403493" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="680" xmlns="">weather</top>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.10.0-word-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.10.0-word-list-1">
        <emma:lattice initial="1" final="2" emma:time-ref-uri="#utterance_0.0.10.0-reco-nbest-1">
          <emma:arc from="1" to="2" emma:confidence="0.8278435" emma:offset-to-start="0" emma:duration="710">sports<emma:info><ms:sapiPhraseElement ms:pronunciation="S P AO RA T S" ms:lexicalForm="sports" ms:displayAttributes="2" ms:actualConfidence="1" /></emma:info></emma:arc>
        </emma:lattice>
      </emma:interpretation>
    </emma:one-of>
    <emma:one-of id="utterance_0.0.10.0-rule-tree-list" disjunction-type="recognition">
      <emma:interpretation id="utterance_0.0.10.0-rule-tree-1" emma:confidence="0.8278435" emma:time-ref-uri="#utterance_0.0.10.0-reco-nbest-1">
        <emma:derived-from resource="#utterance_0.0.10.0-word-list-1" composite="false" />
        <top emma:confidence="0.8278435" ms:actualConfidence="1" emma:offset-to-start="0" emma:duration="710" xmlns="">sports</top>
      </emma:interpretation>
    </emma:one-of>
  </emma:derivation>
</emma:emma>

Output File Format

The output from Simulator Results Analyzer is an XML document that contains information about each utterance, an analysis for all utterances, and an analysis for utterances contained in any specified grammar sets. Information for individual utterances includes confidence scores, semantics, and whether the transcript matches the recognition result. Simulator Results Analyzer compares the transcripts (if they exist) to the recognition result to identify in-grammar and out-of-grammar recognitions. The output file also contains sums and percentages that illustrate whether utterances were correctly or incorrectly accepted or rejected for a range of confidence scores.

Note Note

Only utterances containing both an audio recognition and a transcript recognition, and that contain no recognition errors (identified by ms:status="ERROR") will be included in the output file.

You can use the output file as input to your own tools for further analysis. See Generating Simulations and Performing Analysis.

The following example demonstrates the structure of an output file generated by Simulator Results Analyzer, using the input file example.

Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<Scenario xml:space="preserve">
  <Utterances>

    <Utterance id="utterance_0.0.0.0">
      <AudioUri>waves/utt_00.wav</AudioUri>
      <AudioType>audio/x-wav</AudioType>
      <TranscriptText>sports</TranscriptText>
      <TranscriptSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
        <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </TranscriptSemantics>
      <TranscriptConfidence>1.0000000</TranscriptConfidence>
      <TranscriptSemanticConfidence>1.0000000</TranscriptSemanticConfidence>
      <RecoResultText>sports</RecoResultText>
      <RecoResultSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="0.5618123" ms:actualConfidence="0" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
        <grammar emma:confidence="0.5618123" ms:actualConfidence="0" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </RecoResultSemantics>
      <RecoResultRuleTree>
        <Rule id="top" uri="grammars\menu_choices.grxml">sports</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>S P AO RA T S</RecoResultPronunciation>
      <RecoResultConfidence>0.5638461</RecoResultConfidence>
      <RecoResultSemanticConfidence>0.5618123</RecoResultSemanticConfidence>
      <InGrammar>True</InGrammar>
      <SemanticsMatch>True</SemanticsMatch>
      <WordError wordCount="1" insertions="0" deletions="0" substitutions="0" />
    </Utterance>

    <Utterance id="utterance_0.0.1.0">
      <AudioUri>waves/utt_01.wav</AudioUri>
      <AudioType>audio/x-wav</AudioType>
      <TranscriptText>[noise]</TranscriptText>
      <RecoResultConfidence>0.0000000</RecoResultConfidence>
      <RecoResultSemanticConfidence>0.0000000</RecoResultSemanticConfidence>
      <InGrammar>False</InGrammar>
      <SemanticsMatch>True</SemanticsMatch>
      <WordError wordCount="1" insertions="0" deletions="1" substitutions="0" />
    </Utterance>

    <Utterance id="utterance_0.0.2.0">
      <AudioUri>waves/utt_02.wav</AudioUri>
      <AudioType>audio/x-wav</AudioType>
      <TranscriptText>sports</TranscriptText>
      <TranscriptSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
        <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </TranscriptSemantics>
      <TranscriptConfidence>1.0000000</TranscriptConfidence>
      <TranscriptSemanticConfidence>1.0000000</TranscriptSemanticConfidence>
      <RecoResultText>sports</RecoResultText>
      <RecoResultSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="0.8497295" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
        <grammar emma:confidence="0.8497295" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </RecoResultSemantics>
      <RecoResultRuleTree>
        <Rule id="top" uri="grammars\menu_choices.grxml">sports</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>S P AO RA T S</RecoResultPronunciation>
      <RecoResultConfidence>0.9479059</RecoResultConfidence>
      <RecoResultSemanticConfidence>0.8497295</RecoResultSemanticConfidence>
      <InGrammar>True</InGrammar>
      <SemanticsMatch>True</SemanticsMatch>
      <WordError wordCount="1" insertions="0" deletions="0" substitutions="0" />
    </Utterance>

    <Utterance id="utterance_0.0.3.0">
      <AudioUri>waves/utt_03.wav</AudioUri>
      <AudioType>audio/x-wav</AudioType>
      <TranscriptText>weather</TranscriptText>
      <TranscriptSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
        <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </TranscriptSemantics>
      <TranscriptConfidence>1.0000000</TranscriptConfidence>
      <TranscriptSemanticConfidence>1.0000000</TranscriptSemanticConfidence>
      <RecoResultText>weather</RecoResultText>
      <RecoResultSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="0.9668913" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
        <grammar emma:confidence="0.9668913" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </RecoResultSemantics>
      <RecoResultRuleTree>
        <Rule id="top" uri="grammars\menu_choices.grxml">weather</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>W EH DH AX RA</RecoResultPronunciation>
      <RecoResultConfidence>0.9449926</RecoResultConfidence>
      <RecoResultSemanticConfidence>0.9668913</RecoResultSemanticConfidence>
      <InGrammar>True</InGrammar>
      <SemanticsMatch>True</SemanticsMatch>
      <WordError wordCount="1" insertions="0" deletions="0" substitutions="0" />
    </Utterance>

    <Utterance id="utterance_0.0.4.0">
      <AudioUri>waves/utt_04.wav</AudioUri>
      <AudioType>audio/x-wav</AudioType>
      <TranscriptText>news</TranscriptText>
      <TranscriptSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">NEWS</application>
        <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </TranscriptSemantics>
      <TranscriptConfidence>1.0000000</TranscriptConfidence>
      <TranscriptSemanticConfidence>1.0000000</TranscriptSemanticConfidence>
      <RecoResultText>news</RecoResultText>
      <RecoResultSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="0.9612538" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">NEWS</application>
        <grammar emma:confidence="0.9612538" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </RecoResultSemantics>
      <RecoResultRuleTree>
        <Rule id="top" uri="grammars\menu_choices.grxml">news</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>N U Z</RecoResultPronunciation>
      <RecoResultConfidence>0.9319434</RecoResultConfidence>
      <RecoResultSemanticConfidence>0.9612538</RecoResultSemanticConfidence>
      <InGrammar>True</InGrammar>
      <SemanticsMatch>True</SemanticsMatch>
      <WordError wordCount="1" insertions="0" deletions="0" substitutions="0" />
    </Utterance>

    <Utterance id="utterance_0.0.5.0">
      <AudioUri>waves/utt_05.wav</AudioUri>
      <AudioType>audio/x-wav</AudioType>
      <TranscriptText>top stories</TranscriptText>
      <RecoResultConfidence>0.0000000</RecoResultConfidence>
      <RecoResultSemanticConfidence>0.0000000</RecoResultSemanticConfidence>
      <InGrammar>False</InGrammar>
      <SemanticsMatch>True</SemanticsMatch>
      <WordError wordCount="2" insertions="0" deletions="2" substitutions="0" />
    </Utterance>

    <Utterance id="utterance_0.0.6.0">
      <AudioUri>waves/utt_06.wav</AudioUri>
      <AudioType>audio/x-wav</AudioType>
      <TranscriptText>sport</TranscriptText>
      <RecoResultText>sports</RecoResultText>
      <RecoResultSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="0.9370015" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
        <grammar emma:confidence="0.9370015" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </RecoResultSemantics>
      <RecoResultRuleTree>
        <Rule id="top" uri="grammars\menu_choices.grxml">sports</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>S P AO RA T S</RecoResultPronunciation>
      <RecoResultConfidence>0.9216749</RecoResultConfidence>
      <RecoResultSemanticConfidence>0.9370015</RecoResultSemanticConfidence>
      <InGrammar>False</InGrammar>
      <SemanticsMatch>False</SemanticsMatch>
      <WordError wordCount="1" insertions="0" deletions="0" substitutions="1" />
    </Utterance>

    <Utterance id="utterance_0.0.7.0">
      <AudioUri>waves/utt_07.wav</AudioUri>
      <AudioType>audio/x-wav</AudioType>
      <TranscriptText>stock quotes</TranscriptText>
      <TranscriptSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <longform emma:confidence="1" ms:actualConfidence="1" ms:dataType="boolean" ms:valueType="boolean" xmlns="">true</longform>
        <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">STOCKS</application>
        <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </TranscriptSemantics>
      <TranscriptConfidence>1.0000000</TranscriptConfidence>
      <TranscriptSemanticConfidence>1.0000000</TranscriptSemanticConfidence>
      <RecoResultText>stock quotes</RecoResultText>
      <RecoResultSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <longform emma:confidence="0.8609061" ms:actualConfidence="1" ms:dataType="boolean" ms:valueType="boolean" xmlns="">true</longform>
        <application emma:confidence="0.8609061" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">STOCKS</application>
        <grammar emma:confidence="0.8609061" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </RecoResultSemantics>
      <RecoResultRuleTree>
        <Rule id="top" uri="grammars\menu_choices.grxml">stock quotes</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>S T AA K K W O T S</RecoResultPronunciation>
      <RecoResultConfidence>0.8928868</RecoResultConfidence>
      <RecoResultSemanticConfidence>0.8609061</RecoResultSemanticConfidence>
      <InGrammar>True</InGrammar>
      <SemanticsMatch>True</SemanticsMatch>
      <WordError wordCount="2" insertions="0" deletions="0" substitutions="0" />
    </Utterance>

    <Utterance id="utterance_0.0.8.0">
      <AudioUri>waves/utt_08.wav</AudioUri>
      <AudioType>audio/x-wav</AudioType>
      <TranscriptText>weather</TranscriptText>
      <TranscriptSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
        <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </TranscriptSemantics>
      <TranscriptConfidence>1.0000000</TranscriptConfidence>
      <TranscriptSemanticConfidence>1.0000000</TranscriptSemanticConfidence>
      <RecoResultText>weather</RecoResultText>
      <RecoResultSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="0.6058497" ms:actualConfidence="0" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
        <grammar emma:confidence="0.6058497" ms:actualConfidence="0" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </RecoResultSemantics>
      <RecoResultRuleTree>
        <Rule id="top" uri="grammars\menu_choices.grxml">weather</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>W EH DH AX RA</RecoResultPronunciation>
      <RecoResultConfidence>0.6197259</RecoResultConfidence>
      <RecoResultSemanticConfidence>0.6058497</RecoResultSemanticConfidence>
      <InGrammar>True</InGrammar>
      <SemanticsMatch>True</SemanticsMatch>
      <WordError wordCount="1" insertions="0" deletions="0" substitutions="0" />
    </Utterance>

    <Utterance id="utterance_0.0.9.0">
      <AudioUri>waves/utt_09.wav</AudioUri>
      <AudioType>audio/x-wav</AudioType>
      <TranscriptText>weather</TranscriptText>
      <TranscriptSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
        <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </TranscriptSemantics>
      <TranscriptConfidence>1.0000000</TranscriptConfidence>
      <TranscriptSemanticConfidence>1.0000000</TranscriptSemanticConfidence>
      <RecoResultText>weather</RecoResultText>
      <RecoResultSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="0.962913" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">WEATHER</application>
        <grammar emma:confidence="0.962913" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </RecoResultSemantics>
      <RecoResultRuleTree>
        <Rule id="top" uri="grammars\menu_choices.grxml">weather</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>W EH DH AX RA</RecoResultPronunciation>
      <RecoResultConfidence>0.9403493</RecoResultConfidence>
      <RecoResultSemanticConfidence>0.9629130</RecoResultSemanticConfidence>
      <InGrammar>True</InGrammar>
      <SemanticsMatch>True</SemanticsMatch>
      <WordError wordCount="1" insertions="0" deletions="0" substitutions="0" />
    </Utterance>

    <Utterance id="utterance_0.0.10.0">
      <AudioUri>waves/utt_10.wav</AudioUri>
      <AudioType>audio/x-wav</AudioType>
      <TranscriptText>sports</TranscriptText>
      <TranscriptSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
        <grammar emma:confidence="1" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </TranscriptSemantics>
      <TranscriptConfidence>1.0000000</TranscriptConfidence>
      <TranscriptSemanticConfidence>1.0000000</TranscriptSemanticConfidence>
      <RecoResultText>sports</RecoResultText>
      <RecoResultSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
        <application emma:confidence="0.8705698" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
        <grammar emma:confidence="0.8705698" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
      </RecoResultSemantics>
      <RecoResultRuleTree>
        <Rule id="top" uri="grammars\menu_choices.grxml">sports</Rule>
      </RecoResultRuleTree>
      <RecoResultPronunciation>S P AO RA T S</RecoResultPronunciation>
      <RecoResultConfidence>0.8278435</RecoResultConfidence>
      <RecoResultSemanticConfidence>0.8705698</RecoResultSemanticConfidence>
      <InGrammar>True</InGrammar>
      <SemanticsMatch>True</SemanticsMatch>
      <WordError wordCount="1" insertions="0" deletions="0" substitutions="0" />
    </Utterance>
  </Utterances>

  <Analysis>
    <WordError wordCount="13" insertions="0" deletions="3" substitutions="1" rate="0.3076923" />
    <PhraseError phraseCount="11" correct="8" incorrect="3" rate="0.2727273" />
    <SemanticError phraseCount="11" correct="10" incorrect="1" rate="0.0909091" />
    <OutOfGrammar total="3">
      <Phrase count="1">[noise]</Phrase>
      <Phrase count="1">sport</Phrase>
      <Phrase count="1">top stories</Phrase>
    </OutOfGrammar>
    <ConfidenceThreshold type="phrase">
      <Bin threshold="0.00" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.01" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.02" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.03" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.04" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.05" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.06" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.07" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.08" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.09" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.10" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.11" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.12" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.13" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.14" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.15" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.16" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.17" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.18" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.19" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.20" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.21" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.22" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.23" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.24" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.25" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.26" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.27" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.28" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.29" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.30" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.31" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.32" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.33" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.34" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.35" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.36" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.37" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.38" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.39" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.40" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.41" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.42" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.43" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.44" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.45" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.46" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.47" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.48" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.49" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.50" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.51" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.52" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.53" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.54" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.55" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.56" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.57" CA_all="0.6363636" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0909091" CA_in="0.8750000" FA_in="0.0000000" FR_in="0.1250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="7" FA_in_count="0" FR_in_count="1" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.58" CA_all="0.6363636" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0909091" CA_in="0.8750000" FA_in="0.0000000" FR_in="0.1250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="7" FA_in_count="0" FR_in_count="1" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.59" CA_all="0.6363636" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0909091" CA_in="0.8750000" FA_in="0.0000000" FR_in="0.1250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="7" FA_in_count="0" FR_in_count="1" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.60" CA_all="0.6363636" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0909091" CA_in="0.8750000" FA_in="0.0000000" FR_in="0.1250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="7" FA_in_count="0" FR_in_count="1" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.61" CA_all="0.6363636" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0909091" CA_in="0.8750000" FA_in="0.0000000" FR_in="0.1250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="7" FA_in_count="0" FR_in_count="1" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.62" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.63" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.64" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.65" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.66" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.67" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.68" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.69" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.70" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.71" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.72" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.73" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.74" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.75" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.76" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.77" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.78" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.79" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.80" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.81" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.82" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.83" CA_all="0.4545455" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.2727273" CA_in="0.6250000" FA_in="0.0000000" FR_in="0.3750000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="5" FA_in_count="0" FR_in_count="3" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.84" CA_all="0.4545455" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.2727273" CA_in="0.6250000" FA_in="0.0000000" FR_in="0.3750000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="5" FA_in_count="0" FR_in_count="3" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.85" CA_all="0.4545455" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.2727273" CA_in="0.6250000" FA_in="0.0000000" FR_in="0.3750000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="5" FA_in_count="0" FR_in_count="3" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.86" CA_all="0.4545455" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.2727273" CA_in="0.6250000" FA_in="0.0000000" FR_in="0.3750000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="5" FA_in_count="0" FR_in_count="3" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.87" CA_all="0.4545455" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.2727273" CA_in="0.6250000" FA_in="0.0000000" FR_in="0.3750000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="5" FA_in_count="0" FR_in_count="3" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.88" CA_all="0.4545455" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.2727273" CA_in="0.6250000" FA_in="0.0000000" FR_in="0.3750000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="5" FA_in_count="0" FR_in_count="3" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.89" CA_all="0.4545455" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.2727273" CA_in="0.6250000" FA_in="0.0000000" FR_in="0.3750000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="5" FA_in_count="0" FR_in_count="3" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.90" CA_all="0.3636364" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.3636364" CA_in="0.5000000" FA_in="0.0000000" FR_in="0.5000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="4" FA_in_count="0" FR_in_count="4" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.91" CA_all="0.3636364" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.3636364" CA_in="0.5000000" FA_in="0.0000000" FR_in="0.5000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="4" FA_in_count="0" FR_in_count="4" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.92" CA_all="0.3636364" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.3636364" CA_in="0.5000000" FA_in="0.0000000" FR_in="0.5000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="4" FA_in_count="0" FR_in_count="4" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.93" CA_all="0.3636364" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.3636364" CA_in="0.5000000" FA_in="0.0000000" FR_in="0.5000000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="4" FA_in_count="0" FR_in_count="4" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="0.94" CA_all="0.2727273" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.4545455" CA_in="0.3750000" FA_in="0.0000000" FR_in="0.6250000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="3" FA_in_count="0" FR_in_count="5" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="0.95" CA_all="0.0000000" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.7272727" CA_in="0.0000000" FA_in="0.0000000" FR_in="1.0000000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="0" FA_in_count="0" FR_in_count="8" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="0.96" CA_all="0.0000000" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.7272727" CA_in="0.0000000" FA_in="0.0000000" FR_in="1.0000000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="0" FA_in_count="0" FR_in_count="8" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="0.97" CA_all="0.0000000" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.7272727" CA_in="0.0000000" FA_in="0.0000000" FR_in="1.0000000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="0" FA_in_count="0" FR_in_count="8" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="0.98" CA_all="0.0000000" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.7272727" CA_in="0.0000000" FA_in="0.0000000" FR_in="1.0000000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="0" FA_in_count="0" FR_in_count="8" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="0.99" CA_all="0.0000000" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.7272727" CA_in="0.0000000" FA_in="0.0000000" FR_in="1.0000000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="0" FA_in_count="0" FR_in_count="8" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="1.00" CA_all="0.0000000" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.7272727" CA_in="0.0000000" FA_in="0.0000000" FR_in="1.0000000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="0" FA_in_count="0" FR_in_count="8" CR_out_count="3" FA_out_count="0" />
    </ConfidenceThreshold>
    <ConfidenceThreshold type="semantic">
      <Bin threshold="0.00" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.01" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.02" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.03" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.04" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.05" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.06" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.07" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.08" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.09" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.10" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.11" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.12" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.13" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.14" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.15" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.16" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.17" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.18" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.19" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.20" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.21" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.22" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.23" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.24" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.25" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.26" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.27" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.28" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.29" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.30" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.31" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.32" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.33" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.34" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.35" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.36" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.37" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.38" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.39" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.40" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.41" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.42" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.43" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.44" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.45" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.46" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.47" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.48" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.49" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.50" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.51" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.52" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.53" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.54" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.55" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.56" CA_all="0.7272727" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0000000" CA_in="1.0000000" FA_in="0.0000000" FR_in="0.0000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="8" FA_in_count="0" FR_in_count="0" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.57" CA_all="0.6363636" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0909091" CA_in="0.8750000" FA_in="0.0000000" FR_in="0.1250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="7" FA_in_count="0" FR_in_count="1" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.58" CA_all="0.6363636" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0909091" CA_in="0.8750000" FA_in="0.0000000" FR_in="0.1250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="7" FA_in_count="0" FR_in_count="1" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.59" CA_all="0.6363636" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0909091" CA_in="0.8750000" FA_in="0.0000000" FR_in="0.1250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="7" FA_in_count="0" FR_in_count="1" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.60" CA_all="0.6363636" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.0909091" CA_in="0.8750000" FA_in="0.0000000" FR_in="0.1250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="7" FA_in_count="0" FR_in_count="1" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.61" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.62" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.63" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.64" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.65" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.66" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.67" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.68" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.69" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.70" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.71" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.72" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.73" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.74" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.75" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.76" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.77" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.78" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.79" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.80" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.81" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.82" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.83" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.84" CA_all="0.5454545" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.1818182" CA_in="0.7500000" FA_in="0.0000000" FR_in="0.2500000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="6" FA_in_count="0" FR_in_count="2" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.85" CA_all="0.4545455" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.2727273" CA_in="0.6250000" FA_in="0.0000000" FR_in="0.3750000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="5" FA_in_count="0" FR_in_count="3" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.86" CA_all="0.4545455" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.2727273" CA_in="0.6250000" FA_in="0.0000000" FR_in="0.3750000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="5" FA_in_count="0" FR_in_count="3" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.87" CA_all="0.3636364" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.3636364" CA_in="0.5000000" FA_in="0.0000000" FR_in="0.5000000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="4" FA_in_count="0" FR_in_count="4" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.88" CA_all="0.2727273" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.4545455" CA_in="0.3750000" FA_in="0.0000000" FR_in="0.6250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="3" FA_in_count="0" FR_in_count="5" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.89" CA_all="0.2727273" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.4545455" CA_in="0.3750000" FA_in="0.0000000" FR_in="0.6250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="3" FA_in_count="0" FR_in_count="5" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.90" CA_all="0.2727273" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.4545455" CA_in="0.3750000" FA_in="0.0000000" FR_in="0.6250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="3" FA_in_count="0" FR_in_count="5" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.91" CA_all="0.2727273" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.4545455" CA_in="0.3750000" FA_in="0.0000000" FR_in="0.6250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="3" FA_in_count="0" FR_in_count="5" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.92" CA_all="0.2727273" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.4545455" CA_in="0.3750000" FA_in="0.0000000" FR_in="0.6250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="3" FA_in_count="0" FR_in_count="5" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.93" CA_all="0.2727273" FA_all="0.0909091" CR_all="0.1818182" FR_all="0.4545455" CA_in="0.3750000" FA_in="0.0000000" FR_in="0.6250000" CR_out="0.6666667" FA_out="0.3333333" CA_in_count="3" FA_in_count="0" FR_in_count="5" CR_out_count="2" FA_out_count="1" />
      <Bin threshold="0.94" CA_all="0.2727273" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.4545455" CA_in="0.3750000" FA_in="0.0000000" FR_in="0.6250000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="3" FA_in_count="0" FR_in_count="5" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="0.95" CA_all="0.2727273" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.4545455" CA_in="0.3750000" FA_in="0.0000000" FR_in="0.6250000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="3" FA_in_count="0" FR_in_count="5" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="0.96" CA_all="0.2727273" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.4545455" CA_in="0.3750000" FA_in="0.0000000" FR_in="0.6250000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="3" FA_in_count="0" FR_in_count="5" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="0.97" CA_all="0.0000000" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.7272727" CA_in="0.0000000" FA_in="0.0000000" FR_in="1.0000000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="0" FA_in_count="0" FR_in_count="8" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="0.98" CA_all="0.0000000" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.7272727" CA_in="0.0000000" FA_in="0.0000000" FR_in="1.0000000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="0" FA_in_count="0" FR_in_count="8" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="0.99" CA_all="0.0000000" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.7272727" CA_in="0.0000000" FA_in="0.0000000" FR_in="1.0000000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="0" FA_in_count="0" FR_in_count="8" CR_out_count="3" FA_out_count="0" />
      <Bin threshold="1.00" CA_all="0.0000000" FA_all="0.0000000" CR_all="0.2727273" FR_all="0.7272727" CA_in="0.0000000" FA_in="0.0000000" FR_in="1.0000000" CR_out="1.0000000" FA_out="0.0000000" CA_in_count="0" FA_in_count="0" FR_in_count="8" CR_out_count="3" FA_out_count="0" />
    </ConfidenceThreshold>
  </Analysis>
</Scenario>

The following table lists and describes the elements and attributes of the XML file generated by Simulator Results Analyzer, as shown in the example above.

Element or Attribute | Parent | Description
Scenario | - | The root element of the utterance file.
Utterances | Scenario | The parent element containing Utterance elements.
Utterance | Utterances | The parent element for each utterance.
AudioUri | Utterance | The location of the source audio.
AudioType | Utterance | The format of the audio.
TranscriptText | Utterance | The text spoken in the utterance.
TranscriptSemantics | Utterance | The meaning assigned to the utterance by the grammar.
TranscriptRuleTree | Utterance | The rule(s) in the grammar that were triggered.
Rule | TranscriptRuleTree | The rule that contains the text recognized by the grammar and was used to recognize the phrase.
id | TranscriptRuleTree|Rule | Attribute. The name of the rule that was triggered.
uri | TranscriptRuleTree|Rule | Attribute. The location of the grammar containing the rule.
TranscriptPronunciation | Utterance | The phonetic spelling of the pronunciation for the transcript text.
TranscriptConfidence | Utterance | A measure of the certainty that the transcript for the utterance is correct.
TranscriptSemanticConfidence | Utterance | A measure of the certainty that the returned semantic is correct for the transcript.
RecoResultText | Utterance | The recognition result returned by the engine.
RecoResultConfidence | Utterance | The confidence score assigned to the recognition result by the engine.
RecoResultSemanticConfidence | Utterance | A measure of the certainty that the returned semantic is correct for the recognized word.
RecoResultSemantics | Utterance | The semantics attached to the recognition result.
RecoResultRuleTree | Utterance | The rule(s) in the grammar that were triggered.
Rule | RecoResultRuleTree | The rule that contains the text recognized by the grammar and was used to recognize the phrase.
id | RecoResultRuleTree|Rule | Attribute. The name of the rule that was triggered.
uri | RecoResultRuleTree|Rule | Attribute. The location of the grammar containing the rule.
RecoResultPronunciation | Utterance | The phonetic spelling of the recognition result.
InGrammar | Utterance | Whether the transcript text was recognized during emulation by any grammar reference by the utterance.
SemanticsMatch | Utterance | Whether the semantics in the transcript match the grammar.
WordError | Utterance | A summary of the number of words that had errors, and the numbers of insertions, deletions, and substitutions made during recognition of the utterance.
wordCount | Utterance|WordError | Attribute. The count of all words in the transcript of the utterance.
insertions | Utterance|WordError | Attribute. The number of insertions made by the recognition of the utterance.
deletions | Utterance|WordError | Attribute. The number of words deleted by the recognition of the utterance.
substitutions | Utterance | WordError | Attribute. The number of words substituted by the recognition of the utterance.
Analysis | Scenario | The parent element containing recognition information for all utterances and grammar groups.
WordError | Analysis | A summary of the number of words, the number of insertions, deletions, and substitutions, and the result of the combined insertions, deletions, and substitutions divided by the number of words, for all utterances.
wordCount | Analysis|WordError | Attribute. The count of all words recognized.
insertions | Analysis|WordError | Attribute. The number of insertions made by all recognitions.
deletions | Analysis|WordError | Attribute. The number of deletions made by all recognitions.
substitutions | Analysis|WordError | Attribute. The number of substitutions made by all recognitions.
rate | Analysis|WordError | Attribute. The result of the combined insertions, deletions, and substitutions divided by the number of words.
PhraseError | Analysis | A summary of phrases that had errors that includes the total number of phrases, the number of correct and incorrect phrases, and the rate of errors.
phraseCount | PhraseError | Attribute. The count of all phrases recognized.
correct | PhraseError | Attribute. The count of all correctly recognized phrases.
incorrect | PhraseError | Attribute. The count of all incorrectly recognized phrases.
rate | PhraseError | Attribute. The number of incorrect phrases divided by phraseCount.
SemanticError | Analysis | A summary of semantic errors that includes the total number of phrases, the number of correct and incorrect phrases, and the rate of errors.
phraseCount | SemanticError | Attribute. The count of all phrases recognized.
correct | SemanticError | Attribute. The count of all phrases for which the correct semantics were returned.
incorrect | SemanticError | Attribute. The count of all phrases for which incorrect semantics were returned.
rate | SemanticError | Attribute. The number of phrases with incorrect semantics divided by phraseCount.
OutOfGrammar | Analysis | Contains the phrases whose transcriptions do not produce a match when emulated.
total | OutOfGrammar | Attribute. The number of phrases whose transcriptions do not produce a match when emulated.
Phrase | OutOfGrammar | The transcribed text of the phrase and the number of times the phrase occurred.
count | Phrase | Attribute. The number of times the phrase occurred.
ConfidenceThreshold | Analysis | The parent element for Bin elements. Its type attribute can be either "semantic" or "phrase".
type | ConfidenceThreshold | Attribute. Indicates the type of results the ConfidenceThreshold element contains. Values are "semantic" or "phrase".
Bin | ConfidenceThreshold | Contains a summary of the acceptance rates at a specified threshold.
threshold | Bin | Attribute. The confidencelevel setting of the speech recognition engine that would generate the results in the Bin element.
CA_all | Bin | Attribute. Correctly accepted utterances as a percentage of all user utterances.
FA_all | Bin | Attribute. Falsely accepted utterances as a percentage of all user utterances. This is the percentage of all utterances that are incorrectly recognized.
CR_all | Bin | Attribute. Correctly rejected utterances as a percentage of all user utterances.
FR_all | Bin | Attribute. Falsely rejected utterances as a percentage of all user utterances. This is the percentage of all utterances that are rejected but should have been recognized.
CA_in | Bin | Attribute. Correctly accepted utterances as a percentage of in-grammar utterances.
CR_out | Bin | Attribute. Correctly rejected utterances as a percentage of out-of-grammar utterances. This is the percentage of utterances that are not covered by the grammar and are correctly rejected.
CR_total | Bin | Attribute. The total number of utterances that were correctly rejected.
FA_in | Bin | Attribute. Falsely accepted utterances as a percentage of in-grammar utterances. This is the percentage of all utterances that are covered by the grammar but are falsely recognized by the recognizer.
FA_out | Bin | Attribute. Falsely accepted utterances as a percentage of out-of-grammar utterances. This is the percentage of all utterances that are not covered by the grammar and are falsely accepted by the recognizer.
FR_in | Bin | Attribute. Falsely rejected utterances as a percentage of in-grammar utterances. This is the percentage of all utterances that are covered by the grammar, but were rejected by the recognizer.
CA_in_count | Bin | Attribute. The number of correctly accepted in-grammar utterances.
FA_in_count | Bin | Attribute. The number of falsely accepted in-grammar utterances.
FR_in_count | Bin | Attribute. The number of falsely rejected in-grammar utterances.
CR_out_count | Bin | Attribute. The number of correctly rejected out-of-grammar utterances.
FA_out_count | Bin | Attribute. The number of falsely accepted out-of-grammar utterances.
Group | Analysis | Contains results for a group of grammars specified by the identifier for an ms:active-grammars element.
Name | Group | Attribute. Contains the identifier for an ms:active-grammars element, which represents the group of grammars that were active during recognition.
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Simulator Results Analyzer Error Messages and Format

[image]

Simulator Results Analyzer Error Messages and Format
Send Feedback

Simulator Results Analyzer detects errors in input files and generates messages with the following information.

  • File name (if applicable)

  • Number of the line that contains the error (if applicable)

  • Message type: Error, Warning, or Info

  • Error code (if applicable)

  • Error description

Execution continues until all available input files have been processed or until a fatal error has been encountered. If errors are encountered Simulator Results Analyzer returns EXIT_FAILURE (1). Upon successful completion, with no errors, the tool returns EXIT_SUCCESS (0).

The following table describes how Simulator Results Analyzer responds to error and warning conditions.

Condition | Type | Description and Simulator Results Analyzer Behavior
No Input File Specified | Error | At least one input file must be specified. Execution halts, tool exits.
No Output File Specified | Error | An output file must be specified. Execution halts, tool exits.
Cannot Open Output File '%s' | Error | The output file was found but could not be opened. Execution halts, tool exits.
No Input | Error | Cannot open any input files. Execution halts, tool exits.
Write Error: cannot write to '%s' | Error | The simulator results analyzer could not write to the output file. Execution halts, tool exits.
Malformed Semantic Path | Error | Improperly formed XPath specified in the /semanticPath option. Execution halts, tool exits.
Cannot Open Input File '%s' | Warning | An input file could not be opened. Improperly formed XPath. Execution continues.
Reco Error Encountered: Utterance Skipped | Warning | An utterance in the input file caused a recognition error and was skipped. Execution continues.

Example Error Messages

SimulatorResultsAnalyzer : Error: No Input File Specified

C:\myfiles\input.xml : Error : Write Error: Cannot write to "g:\myshare\output.xml"

C:\myfiles\input.xml (352) : Warning : Reco Error Encountered : Utterance Skipped

Incorrectly Typed Input File Name

SimulatorResultsAnalyzer /In myimputfile.xml /Out myoutputfile.xml /SemanticPath "/City"

SimulatorResultsAnalyzer : Warning: Cannot open Input File 'myimputfile.xml'

SimulatorResultsAnalyzer : Error: No Input

Processed 0/1 input files.

1 Errors, 1 Warnings.

Processing Complete.

Unmatched Wildcard on Input File

> SimulatorResultsAnalyzer /In *.xml /Out myoutputfile.xml /SemanticPath "City"

SimulatorResultsAnalyzer : Warning: Cannot open Input File '*.xml'

SimulatorResultsAnalyzer : Error: No Input

Processed 0/1 input files.

1 Errors, 1 Warnings.

Processing Complete.

Incorrectly Typed Input File Name (Multiple Input Files)

> SimulatorResultsAnalyzer /In input1.xml imput2.xml input3.xml /Out myoutputfile.xml /SemanticPath "City"

inputfile1.xml: 34 utterances processed

SimulatorResultsAnalyzer : Warning: Cannot open Input File 'imput2.xml'

inputfile3.xml: 287 utterances processed

Processed 2/3 input files.

0 Errors, 1 Warnings.

Processing Complete.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Simulator Results Analyzer Interpreting the Results

[image]

Simulator Results Analyzer Interpreting the Results
Send Feedback

The output file generated by the Simulator Results Analyzer contains detailed information about each utterance and the decisions that the speech recognition engine made when recognizing each utterance. In addition, the Analysis section of the output file contains calculated percentages and totals that summarize the results of recognition for the entire batch of utterances used as input to Simulator. The information in the Analysis section will help you do the following:

  • Evaluate the overall accuracy for your grammars.

  • Examine out-of-grammar (OOG) phrases and consider whether to add them as synonyms for in-grammar phrases.

  • Identify the confidencelevel setting for speech recognition engine that provides optimum recognition accuracy.

Interpreting Accepted and Rejected Recognitions

To interpret the output of the Simulator Results Analyzer, it is useful to have some insight into the decisions that a speech recognition engine makes during recognition. For a given speech recognition grammar, a given utterance, and a given confidencelevel setting, a speech recognition engine can make one of five choices.

  1. Correctly recognize (accept) an in-grammar utterance (CA/in). This means that:

    • There is a phrase in the grammar that is intended to capture the utterance.

    • The recognizer matches the utterance to the phrase.

    • The recognizer assigns a confidence score to the recognition result that is greater than or equal to its confidencelevel setting.

  2. Correctly reject an out-of-grammar utterance (CR/out). This means that:

    • There is no phrase in the grammar that is intended to capture the utterance.

    • The recognizer does not create a recognition result or assigns a confidence score to the recognition result that is less than its confidencelevel setting.

  3. Falsely reject an in-grammar utterance (FR/in). This means that:

    • There is a phrase in the grammar that is intended to capture the utterance.

    • The recognizer does not create a recognition result or assigns a confidence score to the recognition result that is less than its confidencelevel setting.

  4. Falsely recognize (accept) an in-grammar utterance (FA/in). This means that:

    • There is a phrase in the grammar that is intended to capture the utterance.

    • The recognizer matches the utterance to a different phrase in the grammar.

    • The recognizer assigns a confidence score to the recognition result that is greater than or equal to its confidencelevel setting.

  5. Falsely recognize (accept) an out-of-grammar utterance (FA/out). This means that:

    • There is no phrase in the grammar that is intended to capture the utterance.

    • The recognizer incorrectly matches the utterance to a phrase in the grammar.

    • The recognizer assigns a confidence score to the recognition result that is greater than or equal to its confidencelevel setting.

The examples in the following table provide additional clarification on these five categories. In each example it is assumed that the grammar consists of the names of cities in the United States, and that the application prompt is "For which city would you like the weather?"

Category | Example
CA/in (Confidence score => confidencelevel) | Caller: "Boston" Application: "The weather in Boston is ..."
CR/out (Confidence score < confidencelevel) | Caller: "Pizza" Application: "I didn't understand that"
FR/in (Confidence score < confidencelevel) | Caller: "Boston" Application: "I didn't understand that"
FA/in (Confidence score => confidencelevel) | Caller: "Boston" Application: "The weather in Austin is ..."
FA/out (Confidence score => confidencelevel) | Caller: "Pizza" Application: "The weather in Poughkeepsie is ..."

For a list and description of all the elements and attributes in the output file that the Simulator Results Analyzer produces, see Simulator Results Analyzer Input and Output File Format.

Evaluating the Overall Accuracy of Your Grammars

The Analysis section in the output file provides counts and percentages for all utterances that were not correctly recognized. You can evaluate the overall accuracy of your grammars by looking at how many errors were generated, and what percentage this number constitutes in the total of all attempted recognitions. There are separate error categories for words, phrases, and semantics. The following excerpt from the output file shown in Simulator Results Analyzer Input and Output File Format shows the summary of recognition errors for a batch of utterances.

Copy image Copy Code
<Analysis>
  <WordError wordCount="13" insertions="0" deletions="3" substitutions="1" rate="0.3076923" />
  <PhraseError phraseCount="11" correct="8" incorrect="3" rate="0.2727273" />
  <SemanticError phraseCount="11" correct="10" incorrect="1" rate="0.0909091" />

In the WordError element, the rate attribute indicates what percentage of the attempts to recognize individual words were unsuccessful. The deletions attribute contains the number of words for which there was no recognition result. The substitutions attribute contains the number of words that were incorrectly matched to a phrase in a grammar.

The figures for SemanticError are particularly important, because they indicate that an incorrect semantic result was returned to your application. The semantics of a recognized phrase are the actionable portion of a recognition result for your application. In the FA/In example in the table above, there is a mismatch between the semantics of what the caller said (Boston) and the semantics of the recognition result (Austin). Because the semantics do not match, the caller receives the weather report for the wrong city.

Out-of-Grammar Utterances

Words that were not in the grammar but that were accepted for an in-grammar phrase by mistake may indicate that you can improve a grammar's performance by adding one or more phrases. The OutOfGrammar section in the output file lists each out-of-grammar phrase that was mistakenly recognized for a phrase in the grammar and keeps a count of how many times each phrase was accepted in error. An out-of-grammar word that is repeatedly accepted in error for in-grammar phrase may be a good candidate for adding to a grammar.

The following excerpt from the output file shown in Simulator Results Analyzer Input and Output File Format shows the summary of out-of-grammar utterances for a batch of recognitions.

Copy image Copy Code
<OutOfGrammar total="3">
  <Phrase count="1">[noise]</Phrase>
  <Phrase count="1">sport</Phrase>
  <Phrase count="1">top stories</Phrase>
</OutOfGrammar>

In the above example, the utterance "sport" may be a candidate for adding to the grammar. It was probably misrecognized for a phrase in the grammar (sports). You can determine this by inspecting the individual recognition result for the utterance "sport", shown below. You can see that the speech recognition engine produced the recognition result "sports" (RecoResultText) from the utterance "sport" (TranscriptText), even though the word "sport" is not in the grammar (InGrammar).

Copy image Copy Code
<Utterance id="utterance_0.0.6.0">
  <AudioUri>../Samples/Sample%20Simulator/waves/utt_06.wav</AudioUri>
  <AudioType>audio/x-wav</AudioType>
  <TranscriptText>sport</TranscriptText><RecoResultText>sports</RecoResultText>
  <RecoResultSemantics ms:typespace="ECMA-262" ms:dataType="object" xmlns:ms="http://www.microsoft.com/xmlns/webreco" xmlns:emma="http://www.w3.org/2003/04/emma">
    <application emma:confidence="0.9370015" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">SPORTS</application>
    <grammar emma:confidence="0.9370015" ms:actualConfidence="1" ms:dataType="string" ms:valueType="string" xmlns="">menu_choices.grxml</grammar>
  </RecoResultSemantics>
  <RecoResultRuleTree>
    <Rule id="top" uri="grammars\menu_choices.grxml">sports</Rule>
  </RecoResultRuleTree>
  <RecoResultPronunciation>S P AO RA T S</RecoResultPronunciation>
  <RecoResultConfidence>0.9216749</RecoResultConfidence>
  <RecoResultSemanticConfidence>0.9370015</RecoResultSemanticConfidence>
  <InGrammar>False</InGrammar>
  <SemanticsMatch>False</SemanticsMatch>
  <WordError wordCount="1" insertions="0" deletions="0" substitutions="1" />
</Utterance>

Adding commonly mispronounced words to your grammar can improve its performance and increases the likelihood that mispronunciations return the same semantic results back to the application as a correct pronunciation.

Choosing the Optimum confidencelevel Setting

Simulator Results Analyzer uses the confidence scores that the speech recognition engine assigns to each utterance to calculate acceptance and rejection rates for each of the available confidencelevel settings that are available on the Microsoft speech recognition engine. There are two ConfidenceThreshold sections in the output file; one for phrases and one for semantics.

  • The <ConfidenceThreshold type="phrase"> sections shows how the confidencelevel setting on the speech recognition engine affects acceptance/rejection rates for recognized phrases.

  • The <ConfidenceThreshold type="semantics"> shows how the confidencelevel on the speech recognition engine affects the acceptance/rejection rates for the semantics of recognized phrases.

By inspecting the results in the ConfidenceThreshold sections, you can identify the confidence level that produces the best results for the batch of input utterances. It is important to understand that no single metric can fully describe speech recognition accuracy. Often, improving one metric can have a negative effect on another metric. Reducing the number of false acceptances can raise the number of false rejections.

Important note Important

To properly assess the confidence threshold setting for your application via the output of Simulator Results Analyzer, set confidencelevel="0" in the configuration file that you specify in the /RecoConfig option on the command line when you launch the Simulator tool. This will ensure that all recognitions are returned, regardless of confidence score.

The following diagram illustrates the roles played by the confidence score assigned to an utterance (by the speech recognition engine) and the speech recognition engine's confidencelevel setting (which you can set) in determining whether or not the utterance is accepted (recognized). Whether correctly or incorrectly recognized, whether in-grammar or out-of-grammar, an utterance is accepted if the confidence score assigned by the speech recognition engine to the utterance is greater than or equal to the value of its confidencelevel. The speech recognition engine contains logic that calculates a confidence score for each utterance and its semantics. You can set the confidencelevel of the speech recognition engine in the RecoConfig file. See Speech Recognition Engine Configuration File Settings.

Speech Recognition Engine Accept/Reject Utterances
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile Grammar Reference Manual

[image]

Compile Grammar Reference Manual
See Also Send Feedback

CompileGrammar.exe is a command-line tool that you can use to optimize grammar files for use by the Microsoft Grammar Development Tools (Technical Preview).

The Compile Grammar Reference Manual contains the following topics.

  • Compile Grammar Usage Scenarios

  • Compile Grammar Command-Line Syntax

  • Compile Grammar Input and Output File Format

  • Compile Grammar Error Messages and Format

See Also

Concepts

Prepare Grammar Reference Manual
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile Grammar Usage Scenarios

[image]

Compile Grammar Usage Scenarios
Send Feedback

You can use CompileGrammar to convert source grammar files into binary files of the format that the Microsoft Speech Platform Runtime 11 expects. Compiling grammars prior to loading reduces the processing that the Speech Platform Runtime 11 must perform when loading a grammar, which reduces the likelihood of application latency when loading grammars, in particular large grammars.

You will typically use CompileGrammar in the following scenarios:

  • You have a large grammar that may introduce latency into your application when it is loaded.

  • Your application loads and unloads grammars frequently.

  • Your application needs to fetch grammars over the internet.

  • You want to use an ARPA-format statistical language model (SLM) grammar with a Microsoft speech recognition engine.

CompileGrammar provides answers to the following questions:

  • How can I minimize the possibility of application latency when loading grammars?

  • How can I convert grammars of multiple source formats into the format expected by the Speech Platform Runtime 11?

CompileGrammar accepts as input XML-format grammar files that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0, or files that conform to the Advanced Research Projects Agency (ARPA) format. The tool generates compiled grammar files in binary format with the ".cfg" extension (a Microsoft format). CompileGrammar reduces the size of grammar files and optimizes them for use by the Speech Platform Runtime 11.

You can use the files that the Compile Grammar tool produces as input to PrepareGrammar.exe. See Prepare Grammar Reference Manual.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile Grammar Command-Line Syntax

[image]

Compile Grammar Command-Line Syntax
Send Feedback

The command-line syntax for CompileGrammar.exe has the following format.

CompileGrammar /In <input file name> /Out <output file name> /InFormat <format of input file>

Compile Grammar

The following table describes the command-line option names and values for Prepare Grammar.exe.

Option Name

Description

/In

Required. The file name and extension of the grammar file to compile, for example "MyGrammar.grxml" or "MyGrammar.arpa".

/Out

Optional. The file name and extension of the compiled grammar file, for example "MyGrammar.cfg". Files of the CFG format are optimized for the speech platform.

If no output file is specified, a file with the name <inputfilename>.cfg is created, and the output is sent to it.

/InFormat

Optional. The format of the input file. Acceptable values are SRGS and ARPA. The default file format is SRGS. SRGS files must be in XML format.

/RecoConfig

Optional. The name of the configuration file to use for the speech recognition engine. If not specified, the tool will look for a default configuration file named "RecoConfig.xml" in the current working directory and in the directory that contains CompileGrammar.exe. The tool will generate an error if you do not supply it with a configuration file.

/?

Optional. Displays a list of acceptable option/value pairs.

Note Note

  • Command-line options and values are not case-sensitive.

  • Command-line options can be preceded by a forward slash (0x002F), a dash (0x002d), an en dash (0x2013), an em dash (0x2014), or a horizontal bar (0x2015).

  • You can enter option/value pairs in any sequence.

Caution note Caution

If an existing file has the same name as the file name specified by the /Out option, it will be overwritten. The tool does not warn that a file will be overwritten.

Remarks

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" either in the current directory (the directory for the command line) or in the directory that contains CompileGrammar.exe. Use the configuration file to specify a speech recognition engine to use, to configure the parameters for connecting to it, and to configure its behavior. For more information, see Setting Up the Grammar Development Tools.

CompileGrammar.exe will follow rule references to external documents. For example, if MyGrammar.grxml contains a reference to a rule in MyExternalGrammar.grxml, the rule contained in MyExternalGrammar.grxml is included in MyGrammar.cfg.

It is an accepted convention to use the .grxml file extension for XML-based grammar documents that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0.

For ARPA-format source grammars only, the Compile Grammar tool will look for a language declaration in the configuration file specified by the /RecoConfig option. The Compile Grammar tool will use the language declaration in the configuration file to set the language of the compiled grammar file. You can specify the language for a grammar file compiled from ARPA source in the enginerequiredattributes attribute of the properties element in the configuration file. See Speech Recognition Engine Configuration File Settings. If the configuration file does not declare a language, then the language of the compiled file will be US English.

Example

The following is an example command-line entry for CompileGrammar.exe.

CompileGrammar /In InputFile.grxml /InFormat SRGS /Out OutputFile.cfg

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile Grammar Input and Output File Format

[image]

Compile Grammar Input and Output File Format
Send Feedback

Compile Grammar converts XML-format grammar files to binary grammar files with the ".cfg" extension. Input files may conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0 or to the Advanced Research Projects Agency (ARPA) format.

The output of the Compile Grammar tool can be used as input to the Prepare Grammar tool, and as a convenient format for transporting grammar files.

Input File Format

The following describes the input file formats for Compile Grammar.

SRGS Format

The default input file format for Compile Grammar is an SRGS-compliant grammar file in XML format.

A valid XML-format grammar document consists of a legal header followed by a body consisting of a set of legal rule definitions. A legal header in a grammar document must include the xml declaration element and may include an optional DOCTYPE declaration element. These are followed in the header by the root grammar element. Grammar files used as input to the Compile Grammar tool must contain the following required attributes in the root grammar element for a grammar to compile successfully:

Attribute | Description | Example
Version | Attribute of the grammar element. The version of the specification implemented by the grammar. | version="1.0" A grammar that complies with SRGS Version 1.0 must declare the version to be "1.0".
Xmlns | Attribute of the grammar element. The URI of the namespace for the grammar. | xmlns="http://www.w3.org/2001/06/grammar"
Xml:lang | Attribute of the grammar element. The primary language contained by the document and optionally a country or other variation. | xml:lang="en-US" The xml:lang attribute is required if grammar mode="voice" or if the mode attribute is omitted, in which case the value defaults to voice. The xml:lang attribute is not required if grammar mode="dtmf".
Note Note

Grammar files in Augmented Backus-Naur Form (ABNF) format are not supported.

Example

The following is an example of a valid XML-format, SRGS-compliant grammar document that contains only the minimum required elements and attributes in the document's header, and a simple rule in the body of the document.

XML Copy image Copy Code
<?xml version="1.0"?>
<grammar version="1.0"
         xmlns="http://www.w3.org/2001/06/grammar"
         xml:lang="en-US">

   <rule id="main">
      <one-of>
         <item>hello</item>
         <item>world</item>
      </one-of>
   </rule>

</grammar>

The document header ends and the body of the grammar document begins with the first rule element. Grammar files used as input to the grammar compiler can contain optional elements and attributes in the document header, see SRGS Grammar XML Reference (Microsoft.Speech). For more information about elements and attributes in SRGS grammars, see Speech Recognition Grammar Specification Version 1.0.

ARPA Format

Optionally, Compile Grammar accepts input files that conform to the Advanced Research Projects Agency (ARPA) format. The ARPA format expresses language models using n-grams. N-gram language models are traditionally used in speech recognition systems based on large vocabularies. The following table lists and describes the components that comprise an ARPA file:

Tag | Description
<header> | Optional. Contains comments that describe the language model. Applications will ignore any information in it.
\data\ | Required. Marks the beginning of the language model data. This is followed immediately by the number of unigrams, bigrams, and trigrams that the language model contains. Compile Grammar ignores any content before the \data\ tag.
ngram 1 | Required. The number of unigrams in the language model.
ngram 2 | Required. The number of bigrams in the language model.
ngram 3 | Required. The number of trigrams in the language model.
\1-grams | Required. Marks the beginning of the enumeration of unigrams in the language model.
\2-grams | Optional. Marks the beginning of the enumeration of bigrams in the language model.
\3-grams | Optional. Marks the beginning of the enumeration of trigrams in the language model.
<unk> | Optional. Represents an unknown word. Tag must be in lower case.
<s> | Optional. Represents the beginning of a sentence. This is counted as a word in the n-gram. For example, "<s> When" is a bigram. Tag must be in lower case.
</s> | Required. Represents the end of a sentence. This is counted as a word in the n-gram. For example, "go up </s>" is a trigram. Tag must be in lower case.
\end\ | Required. Marks the end of the language model data.
Note Note

Tags other than those listed in the table cannot be used.

Example

The following is an example of an ARPA file. See the remarks for a discussion about the significance of the numbers.

Copy image Copy Code
<header - information ignored by applications>

\data\
ngram 1=9
ngram 2=11
ngram 3=3

\1-grams:
-0.8953 <unk>        -0.7373
-0.7404 </s> -0.6515
-0.7861 <s>   -0.1764
-1.0414 When -0.4754
-1.0414 will -0.1315
-0.9622 the   0.0080
-1.4393 Stock        -0.3100
-1.0414 Go    -0.3852
-0.9622 Up    -0.1286

\2-grams:
-0.3626 <s> When     0.1736
-1.2765 <s> the      0.0000
-1.2765 <s> Up       0.0000
-0.2359 When will    0.1011
-1.0212 will </s>    0.0000
-0.4191 will the     0.0000
-1.1004 the </s>     0.0000
-1.1004 the Go       0.0000
-0.6232 Stock Go     0.0000
-0.2359 Go Up        0.0587
-0.4983 Up </s>

\3-grams:
-0.4260 <s> When will
-0.6601 When will the
-0.6601 Go Up </s>

\end\

Remarks

N-gram entries in ARPA files must include numbers that express recognition probabilities. The number to the left of the n-gram is called probability, and must always be present. The number to the right is called back-off probability, and may be omitted for some n-gram entries.

A probability in an ARPA file will always appear in its log (base 10) format. This is a value from -∞ to 0, which when processed and converted to its actual value will be from 0 to 1. A back-off value is specified the same way.

Here is a 2-gram from the example above:

-0.2359 Go Up 0.0587

The number on the left (probability) is the log probability that the word "Up" will be recognized, given that the word "Go" has been recognized. The actual probability is 10-0.2359. Similarly, the probability to the left of a trigram "A B C" is the probability that the recognition engine will recognize "C", given that it has just recognized an "A" followed by a "B". This is written as P(C|A B). For unigrams, the number on the left is just the probability that the given word will be recognized.

The number on the right (back-off probability) is the probability that the following state for an n-gram is not defined by any of the (n+1)-grams. Consider the following entry from the ARPA example above:

-1.0414 Go -0.3852

There is only one state that follows this unigram. That is, there is only one bigram defined in the example that begins with "Go", in this case "Go Up". The back-off probability that the recognition engine will NOT recognize "Up", given that it has already recognized "Go", is 10-0.3852.

If the ARPA example above also included bigrams for "Go Down" and "Go Left", then the back-off probability for "Go" would be the probability that the recognition engine will NOT recognize "Up" or "Down" or "Left" given that it has just recognized "Go". The back-off probability for "Go" added to the probabilities for "Go Up", "Go Down", and "Go Left", when converted to their actual values, will equal 1.

For a given n-gram, the sum of its back-off probability and of all the probabilities of the n+1 grams that start with the same word/phrases specified in n-gram, ideally should sum to 1. However, Compile Grammar does not verify this so they are essentially treated as weights.

It also follows that for any n-gram "A B C", if there is no n-gram "A B C X", then there is no need to specify a back-off probability for "A B C". If you do specify one it will be ignored. This is illustrated in the example above by the bigram "Up <s>" and by all of the trigrams.

Back-off weights also need to be adjusted to account for the followers from the state to which you are backing off. The description of that process is outside the scope of these remarks.

ARPA files for consumption by Compile Grammar must also adhere to the following guidelines for structure and syntax:

  • The enumeration of unigrams must come before the enumeration of bigrams, and so forth.

  • N-grams of dimension greater than 3 (for example, 4-grams) can be specified but will be ignored by this version of Compile Grammar.

  • The enumerations within each n-gram set need not follow any specific order.

  • Lines must be separated by carriage returns, empty lines will be ignored.

  • Words in n-grams must be separated from each other by one or more blanks or tabs or both.

  • N-gram entries use the lexical form of a word, and are case-sensitive. This matches the lexical form used in the dictionary file.

  • Compile Grammar supports ANSI and UNICODE text formats.

Output File Format

The output of Compile Grammar is a binary grammar file with the ".cfg" extension. Grammar files with the ".cfg" extension are optimized for the Microsoft Speech Platform Runtime 11 and are ready for conversion to grammar files with the ".cfgpp" extension, either by the Prepare Grammar tool or by a hosted speech recognizer.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile Grammar Error Messages and Format

[image]

Compile Grammar Error Messages and Format
Send Feedback

CompileGrammar.exe displays error messages and execution summaries in the console. The tool halts execution and displays an error message when it encounters an error that prevents successful completion of a command. The tool returns EXIT_FAILURE (1) when it encounters an error and returns EXIT_SUCCESS (0) when it completes a command successfully. Whether or not a command completes successfully, the tool displays an execution summary after attempting to process a command.

Compile Grammar validates input files for adherence to SRGS or ARPA formats. Errors are often the result of incorrect structure or syntax in the input file, see Compile Grammar Input and Output File Format. Errors may also be caused by incorrect syntax on the command line when launching the tool, see Compile Grammar Command-Line Syntax.

Compile Grammar will throw an error if it encounters any of the following conditions:

  • The grammar file specified by the /In option cannot be found, or cannot be opened.

  • The grammar file specified by the /In option is not properly formed and cannot be compiled.

  • The /Out option is not specified with a filename.

  • There is no configuration file specified by the /RecoConfig option and there is no default configuration file named "RecoConfig.xml" in the current directory, or in the directory that contains CompileGrammar.exe.

Caution note Caution

If an existing file has the same name as the file name specified by the /Out option, it will be overwritten. The tool does not warn that a file will be overwritten.

Error messages will have the following format:

<Input file name>(Line number): <Error or Warning> <Error code>: <Error description>

Compile Grammar generates warning and information messages when encounters any of the following conditions while compiling ARPA format source files:

  • The tool finds an entry that is an exact duplicate of another entry in the grammar. The tool ignores the duplicate entry and generates a warning message, for example:

    • contoso.arpa(7130): Warning: Duplicate entry ignored: "The Big"

  • The tool finds a unigram entry that differs from another entry only by letter case, for example "Jack" vs "jack". The tool compiles both entries and emits an information message, for example:

    • contoso.arpa(741): Info: Entry differs from another entry by case: "Jack" (line 741) vs. "jack" (line 120).

      Note Note

      Information messages may not be emitted for n-grams greater than 1.

Execution summaries will have the following format.

Successful execution:

<CommandName>: <FileName successfully created>

Unsuccessful execution:

<CommandName>: <FileName failed to compile>: <n warnings, n errors>

Remarks

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" in the current directory (the directory for the command line), or in the directory that contains CompileGrammar.exe. The tool will generate an error if you do not supply it with a configuration file.

Examples

The following are examples of errors and execution summaries emitted by CompileGrammar:

Example Errors

test.grxml(10): Error: Missing required attribute "xml:lang" for <grammar>

test.arpa(17): Error: Back-off weights must be supplied where required.

Example Execution Summaries

CompileGrammar: 'test.grxml' failed to compile: 0 warnings, 1 errors

CompileGrammar: 'test.arpa' successfully created

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prepare Grammar Reference Manual

[image]

Prepare Grammar Reference Manual
See Also Send Feedback

PrepareGrammar.exe is a command-line tool that you can use to optimize grammar files in binary format for use by a specific instance of a speech recognition engine.

The Prepare Grammar Reference Manual contains the following topics.

  • Prepare Grammar Usage Scenarios

  • Prepare Grammar Command-Line Syntax

  • Prepare Grammar Input and Output File Format

  • Prepare Grammar Error Messages and Format

See Also

Concepts

Compile Grammar Reference Manual
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prepare Grammar Usage Scenarios

[image]

Prepare Grammar Usage Scenarios
Send Feedback

PrepareGrammar helps you to optimize your application's grammars for the speech recognition engine that your application will use in production.

You convert compiled grammar files with the ".cfg" extension (generated by the CompileGrammar tool) to compiled grammar files with the ".cfgpp" extension to optimize them for the instance of the speech recognition engine that the production application will use. This is called "preparing" grammar files.

PrepareGrammar uses a RecoConfig file to connect to the speech recognition engine and to obtain information it can use to perform its compilation. See Setting Up the Grammar Development Tools. You will typically want to connect to the production speech recognition that your application will use when using PrepareGrammar. PrepareGrammar performs additional optimization on the ".cfg" file generated by the CompileGrammar tool to help you guard against latency in your application while grammars are being loaded.

You will typically use PrepareGrammar in the following scenario:

  • You want to optimize a grammar for a specific instance of a Microsoft speech recognition engine.

PrepareGrammar answers the following questions:

  • How can I minimize the possibility of application latency when loading grammars?

  • How can I optimize a grammar for the exact instance of the Microsoft speech recognition engine that my application will use in production?

Note Note

If a grammar is being fetched across the internet by a hosted speech recognition engine (for example, a hosted IVR service such as Tellme), the grammar should never be prepared by the developer. Instead, the grammar's optimization should remain at the CFG format, which you generated using the CompileGrammar tool. This allows the hosted speech recognizer to do the preparation of the grammar dynamically. For hosted IVR applications, grammars outside of the hosted platform should always be in source format (for example, GRXML) or optimized to CFG format.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prepare Grammar Command-Line Syntax

[image]

Prepare Grammar Command-Line Syntax
Send Feedback

The command-line syntax for PrepareGrammar.exe has the following format.

PrepareGrammar /In <input file name> /Out <output file name> /RecoConfig <configuration file name>

The following table describes the command-line option names and values for Prepare Grammar.

Option Name | Description
/In | Required. The file name and extension of a compiled grammar file, for example "MyGrammar.cfg".
/Out | Required. The file name and extension of the prepared grammar file, for example "MyGrammar.cfgpp". Files of the CFGPP format are optimized for a specific instance of a speech engine.
/RecoConfig | Optional. The name of the configuration file to use for the speech recognition engine. If not specified, the tool will look for a default configuration file named "RecoConfig.xml" in the current working directory and in the directory that contains PrepareGrammar.exe. The tool will generate an error if you do not supply it with a configuration file.
/? | Optional. Displays a list of acceptable option/value pairs.
Note Note

  • Command-line options and values are not case-sensitive.

  • Command-line options can be preceded by a forward slash (0x002F), a dash (0x002d), an en dash (0x2013), an em dash (0x2014), or a horizontal bar (0x2015).

  • You can enter option/value pairs in any sequence.

Caution note Caution

If an existing file has the same name as the file name specified by the /Out option, it will be overwritten. The tool does not warn that a file will be overwritten.

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" either in the current directory (the directory for the command line) or in the directory that contains PrepareGrammar.exe. Use the configuration file to specify a speech recognition engine to use, to configure the parameters for connecting to it, and to configure its behavior. For more information, see Setting Up the Grammar Development Tools.

Example

The following is an example command-line entry for PrepareGrammar.exe.

PrepareGrammar -In InputFile.cfg -Out OutputFile.cfgpp -RecoConfig ConfigFile.xml

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prepare Grammar Input and Output File Format

[image]

Prepare Grammar Input and Output File Format
Send Feedback

Prepare Grammar converts grammar files with the ".cfg" file extension to grammar files with the ".cfgpp" extension (prepared grammar file).

Input File Format

The input file for Prepare Grammar is a binary grammar file with the ".cfg" extension, as produced by the Compile Grammar tool. You must use both the Compile Grammar and Prepare Grammar operations to produce a file with the ".cfgpp" extension from an XML-format grammar file. It is an accepted convention to use the ".grxml" file extension for XML-based grammar documents that conform to the SRGS specification.

Output File Format

The output of the Prepare Grammar is a binary file with the ".cfgpp" extension. Files with the ".cfgpp" extension contain information that optimizes them for use with a specific instance of a speech recognition engine.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prepare Grammar Error Messages and Format

[image]

Prepare Grammar Error Messages and Format
Send Feedback

Prepare Grammar displays error messages and execution summaries in the console. The tool halts execution and displays an error message when it encounters an error that prevents successful completion of a command. The tool returns EXIT_FAILURE (1) when it encounters an error and returns EXIT_SUCCESS (0) when it completes a command successfully. Whether or not a command completes successfully, the tool displays an execution summary after attempting to process a command.

Errors for PrepareGrammar typically will not be for the input file, since it is a binary file that was generated by Compile Grammar. However, Prepare Grammar generates errors for incorrect syntax on the command line and in the speech recognition engine configuration file (see Setting Up the Grammar Development Tools). Execution summaries for Prepare Grammar include the list of properties attributes from the configuration file that were processed successfully.

Remarks

You must either specify a recognition engine configuration file using the /RecoConfig option, or create a default configuration file named "RecoConfig.xml" in the current directory (the directory for the command line), or in the directory that contains PrepareGrammar.exe. The tool will generate an error if you do not supply it with a configuration file.

Example Errors

PrepareGrammar.exe: Error creating reco config object : 'speedvsaccuracy' is an unexpected token. Expecting white space. Line 6, position 22.

Unexpected error occurred when preparing the grammar: Could not find file 'C:\ProgramFiles (x86)\Microsoft Speech Platform SDK\Tools\colpiletest.cfg'.

Example Execution Summaries

PrepareGrammar: preparation for 'preparetest.cfgpp' failed: 3 warnings, 1 errors

Property timeout not yet supported.
Processing completetimeout=0.250000s
Processing incompletetimeout=3s
Processing confidencelevel=0.5
Property sensitivity not yet supported.
Property speedvsaccuracy not yet supported.
Processing requesttimeout=15s
Processing enginerequiredattributes=Language=409;Vendor=Microsoft
Processing engineoptionalattributes=CommandAndControl
PrepareGrammar: 'preparetest.cfgpp' successfully created

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Special Rules Support

[image]

Special Rules Support
Send Feedback

The Speech Recognition Grammar Specification (SRGS) Version 1.0 defines special rules named NULL, VOID, and GARBAGE. SRGS also prescribes the behavior for speech engines when they encounter the special rules. These special rules are implemented in grammars by means of a rule reference, where the rule name becomes the value of the special attribute of a ruleref element. Here is a summary of the functionality that each of the special rules provides:

  • NULL. Defines a rule that is automatically matched in the absence of any audio input.

  • GARBAGE. Defines a rule that may match any speech up until the next rule match, the next token, or until the end of spoken input.

  • VOID. Defines a rule whose contents will not be recognized. Inserting a ruleref element with its special attribute set to VOID into a rule means that the speech recognition engine will not recognize the contents of the rule.

The Microsoft Grammar Development Tools provide support for special rule references used both within other rules and when used as stand-alone rules. The following table summarizes the behavior of each of the Grammar Development Tools with respect to special rule references.

Tool | NULL | GARBAGE | VOID
GrammarValidator | Validates for correct syntax. | Validates for correct syntax. | Validates for correct syntax.
PhraseGenerator | Outputs an empty string. | Emits "…" (three periods) in place of any words that were recognized. Emits two phrases when GARBAGE is used within a rule that contains other content. | If used in rules containing words or phrases, does not emit a phrase.
CheckPhrase | Emits a warning that the (empty) phrase is being skipped. | Emulates and matches the GARBAGE rule. | Not included in output.
Confusabilty | Emits a warning that the (empty) phrase is being skipped. | Emulates and matches the GARBAGE rule. | Not included in output.
Simulator | Emits a warning that the (empty) phrase is being skipped. | Emulates and matches the GARBAGE rule. | Not included in output.
Simulator ResultsAnalyzer | Emits a warning that the (empty) phrase is being skipped. | Preserves "…" in the RecoResultText. | Not included in output.
GrammarCompiler | Preserves behavior in compiled file. | Preserves behavior in compiled file. | Preserves behavior in compiled file.
PrepareGrammar | Preserves behavior in compiled file. | Preserves behavior in compiled file. | Preserves behavior in compiled file.
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Custom Pronunciations Support

[image]

Custom Pronunciations Support
Send Feedback

Your application may use specialized vocabulary, such as proper names, fictitious names or words, or other custom terminology that the speech recognition engine does not interpret as well as expected. Typically, Microsoft speech recognition engines are quite adept at creating pronunciations for words that are uncommon in a language. However, you may find that creating custom pronunciations improves the accuracy of speech recognition for words in your application that have unusual spellings or that do not follow the typical pronunciation rules for the orthography of a language. It is important to test custom pronunciations that you create to verify that they provide an enhanced speech recognition experience for the intended audience of your application.

The Microsoft Grammar Development Tools provide support for custom pronunciations included inline in speech recognition grammars, and custom pronunciations listed in lexicons that are referenced by grammars.

The following table summarizes the support for custom pronunciations provided by each of the Grammar Development Tools.

Tool | Custom Pronunciation Context | Tool Behavior
GrammarValidator | Custom pronunciations inline in a grammar or in a linked lexicon. | Verifies syntax of inline pronunciations both in terms of schema and content.
PhraseGenerator | Custom pronunciations inline in a grammar or in a linked lexicon. | Does not include pronunciations in the output, by design.
Confusabilty | Custom pronunciations inline in a grammar, or in a linked lexicon, or in a list of phrases used as input to the /PhraseFile option. | Does NOT use the custom pronunciation (if specified) to create a pronunciation for a word. DOES use custom pronunciations (if specified) when searching for confusable phrases for pronunciations it created. Does not use custom pronunciations in a list of phrases used as input to the /PhraseFile option.
CheckPhrase | Custom pronunciations inline in a grammar or in a linked lexicon. | Returns the set of custom pronunciations associated with an emulated phrase, if matched.
Simulator | Custom pronunciations inline in a grammar or in a linked lexicon passed in with the utterances. | Uses custom pronunciations for recognition.
Simulator Results Analyzer | Only relevant if there is a pass through of the custom pronunciations. | Outputs custom pronunciations in the RecoResultPronunciation element.
GrammarCompiler | Custom pronunciations inline in a grammar or in a linked lexicon. | Compiles grammars that contain custom pronunciations.
PrepareGrammar | Custom pronunciations inline in a grammar or in a linked lexicon. | Compiles grammars that contain custom pronunciations.

When deciding which pronunciation to use for a word or phrase during speech recognition, a speech recognition engine looks for pronunciations at the following locations in order:

  • Inline in grammar documents

  • In lexicon files linked from a grammar document

  • In the speech recognition engine's internal lexicon

If there are custom pronunciations specified for the same word both inline in a grammar and in a linked lexicon, the speech recognition engine uses only the inline pronunciations. Similarly, if there are custom pronunciations specified in a lexicon linked from a grammar, the speech recognition engine uses those pronunciations instead of, not in addition to, the pronunciations given in the engine's internal lexicon.

The Simulator tool detects custom pronunciations inline in grammars and in lexicons linked from grammars. The table below describes how Simulator selects custom pronunciations in a range of scenarios.

Scenario | Behavior of Simulator
Phrase X is in the grammar and has NO custom pronunciations OR Phrase X is not in the grammar. | If no custom pronunciations are found, uses the pronunciation from the engine's lexicon.
Phase X is in the grammar and has ONE custom pronunciation specified inline in the grammar OR ONE custom pronunciation specified in a linked lexicon. | Uses the custom pronunciation instead of the pronunciation from the engine's lexicon.
Phase X is in the grammar and has ONE custom pronunciation specified inline in the grammar AND ONE custom pronunciation specified in a linked lexicon. | Uses the inline custom pronunciation instead of the pronunciation in the linked lexicon or any pronunciations from the engine's lexicon.
Phrase X is the grammar and has MULTIPLE custom pronunciations inline in the grammar OR MULTIPLE custom pronunciations in a linked lexicon. | Uses the custom pronunciations for Simulation instead of any pronunciations from the engine's lexicon.
Phrase X is the grammar and has MULTIPLE custom pronunciations inline in the grammar AND MULTIPLE pronunciations in a linked lexicon. | Uses the inline custom pronunciations instead of the pronunciations in the linked lexicon or any pronunciations from the engine's lexicon.

When deciding whether to implement custom pronunciations inline in a grammar or in a linked lexicon, consider the following:

  • Custom pronunciations specified inline in grammars apply only to the single occurrence of a word in the grammar.

  • Custom pronunciations specified in lexicons apply to all occurrences of a word in a grammar.

  • A lexicon linked from a grammar is only active while the grammar is active for recognition.

For information about how to incorporate custom pronunciations in your application, see Using Custom Pronunciations.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Using Custom Pronunciations

[image]

Using Custom Pronunciations
See Also Send Feedback

There may be some scenarios in which you can improve the performance of speech recognition in your applications by specifying custom pronunciations for words in your application's vocabulary that are uncommon or whose pronunciation is unusual. Unusual words for which you may want to create custom pronunciations include proper names, place names, fictional words, slang, or words that are specific to an educational or medical discipline. Using the information and examples in this topic, you can create custom pronunciations for the specialized vocabulary in your application.

When to Create Custom Pronunciations

You create custom pronunciations to improve the accuracy of speech recognition for vocabulary in your application that the speech recognition engine does not interpret as well as expected. Typically, you will only need to create custom pronunciations for words that are not common to a language and that do not follow the typical pronunciation rules for the orthography of a language. The Microsoft speech recognition engine is well equipped with tools that enable it to determine the correct pronunciation of words it is familiar with, as well as for words it has never encountered.

Speech recognition engines include a default lexicon that specifies which words can be recognized, and how each word must be pronounced to be recognized. The scope of a speech recognition engine's lexicon is typically a single language, and the lexicon contains a large number of words that the speech recognition engine can recognize in that language. This provides the speech recognition engine with a substantial native vocabulary.

In addition to its lexicon, a speech recognition engine also has an acoustic model that describes the sounds of a language, and a language model that describes how the sounds of a language can be combined into meaningful phrases. This gives the speech recognition engine an understanding of its language that transcends the words in its lexicon. The speech recognition engine uses this understanding to create pronunciations for words it encounters that are not in its lexicon, and it does this almost instantaneously.

However, if your application includes words that feature unusual spelling or atypical pronunciation of familiar spellings, then the speech recognition engine may not create the pronunciation that works best for your application. In these cases, you can specify a custom pronunciation that may improve the recognition accuracy for the specialized vocabulary in your application. It is important to test the performance of your custom pronunciations to confirm that they provide an improved speech recognition experience for your intended audience.

Methods of Incorporation

You can create custom pronunciations either inline in a grammar, or in a lexicon file that a grammar references. A lexicon is a list of words together with their pronunciations. When deciding whether to implement custom pronunciations inline in a grammar or in a linked lexicon, consider the following:

  • Custom pronunciations specified inline in grammars apply only to the single occurrence of a word in the grammar.

  • Custom pronunciations specified in lexicons apply to all occurrences of a word in a grammar.

  • A lexicon linked from a grammar is only active while the grammar is active for recognition.

When deciding which pronunciation to use for a word or phrase during speech recognition, a speech recognition engine looks for pronunciations at the following locations in order:

  1. Inline in grammar documents

  2. In lexicon files linked from a grammar document

  3. In the speech recognition engine's internal lexicon

If there are custom pronunciations specified for the same word both inline in a grammar and in a linked lexicon, the speech recognition engine uses only the inline pronunciations. Similarly, if there are custom pronunciations specified in a lexicon linked from a grammar, the speech recognition engine uses those pronunciations instead of, not in addition to, the pronunciations given in the engine's internal lexicon.

If the speech recognition engine does not find a pronunciation for a word, either in grammars or lexicons to which it currently has access, it will create a pronunciation using the rules of its language model and acoustic model.

You can determine the pronunciation that the speech recognition engine associates with a phrase using the Check Phrase tool. See Check Phrase Reference Manual. You pass in the phrase and a grammar containing the phrase, and the tool generates a result that includes the pronunciation associated with the phrase. This can help you to decide whether or not to provide a custom pronunciation for a phrase.

You specify custom pronunciations using characters from a phonetic alphabet. A phonetic alphabet contains combinations of letters, numbers, and characters which are known as "phones". Phones describe the sounds of speech for a particular language. Similar to those used in dictionaries, phonetic spellings describe how words should be pronounced for successful speech recognition in a specified language.

Creating Inline Custom Pronunciations

You can create custom pronunciations inline in XML-format grammars that are based on the Speech Recognition Grammar Specification (SRGS) Version 1.0. To add custom pronunciations inline in a grammar document, you use special attributes that were created by Microsoft for the grammar Element (Microsoft.Speech) and the token Element (Microsoft.Speech). Remember that inline custom pronunciations apply only to a single occurrence of a word. Use the following steps to create custom pronunciations inline in a grammar document:

Create Inline Custom Pronunciations

  1. Add the following declarations to the grammar element:

    • sapi:alphabet="x-microsoft-ups". This informs the grammar that you will use Microsoft's Universal Phone Set (UPS) to specify pronunciations. You will typically use UPS to specify pronunciations in US English. This attribute is case-sensitive.

    • xmlns:sapi=http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions. This provides a link to the namespace that defines Microsoft's custom attributes for the grammar and token elements.

  2. Create a token element that encloses the word for which you want to specify a custom pronunciation. Add an empty sapi:pron attribute.

    • <token sapi:pron=""> habanera </token>

  3. Using the phone tables below, look up the phones that correspond to the sound of each syllable in your word. Use the Sample Pronunciations below to understand how to combine phones to describe the sound of a syllable.

  4. In the sapi:pron attribute, enter the phones that describe the word's pronunciation. Phones are case-sensitive and must be space-delimited. Optionally use markers for syllable emphasis (S1, S2) and for separating syllables (.) to further refine the pronunciation. See Suprasegmentals later in this topic.

Here is an example of a grammar that specifies custom pronunciations inline.

XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>

<grammar
  version="1.0" mode="voice" root="sauce"
  xml:lang="en-US" tag-format="semantics/1.0"
  sapi:alphabet="x-microsoft-ups"
  xml:base="http://www.contoso.com/"
  xmlns="http://www.w3.org/2001/06/grammar"
  xmlns:sapi="http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions">

  <rule id="sauce" scope="public">
    <item> Please bring more </item>
      <one-of>
        <item><token sapi:display="habanero" sapi:pron="H AE . B AX . S1 N EH lng . R O"> habanera </token></item>
        <item><token sapi:display="habanera" sapi:pron="H AE . B AX . S1 N EH lng . R AX"> habanera </token></item>
      </one-of>
    <item> sauce. </item>
  </rule>

</grammar>
Note Note

You can use the sapi:display attribute of the token element to specify the form of the word that will display in a user interface. The display form of a word is often the same as its lexical form, which is the content of the token element. However, in some languages, such as Japanese, the application may choose to have a display form that is different than the lexical form, as in the following example:
XML Copy image Copy Code
  <item>
    <token sapi:display="ストップ" sapi:pron="ストップ"> すとっぷ </token>
    <tag>cancel</tag>
  </item>

Creating Custom Pronunciations Using a PLS Lexicon

If your application uses specialized words repeatedly across multiple grammars, or if you are generating pronunciations separately from the grammar generation, you can create a lexicon that contains the words and their pronunciations. A lexicon is a separate document that you can link to one or more grammars. If the speech recognition engine loads a grammar that is linked to a lexicon, it uses the pronunciations that the lexicon contained when the grammar was loaded. Any pronunciations inline in a grammar still take precedence over pronunciations in a linked lexicon.

You author lexicons as XML documents that follow the format of the Pronunciation Lexicon Specification (PLS) Version 1.0. Use the following steps to author a PLS lexicon:

Create a Lexicon

  1. Start with a new, blank XML document.

  2. Enter the XML declaration: <?xml version="1.0" encoding="UTF-8"?>.

  3. Enter the opening tag of the lexicon element. This must declare the single language-culture of the words in the lexicon, and the phonetic alphabet used to construct the pronunciations. Here is an example of the opening tag of a lexicon element:

    XML Copy image Copy Code
    <lexicon version="1.0"
  xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
  http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
  alphabet="x-microsoft-ups" xml:lang="en-US">

  4. Add a lexeme element for each word for which you want to define one or more pronunciations:

    • <lexeme></lexeme>. The parent element for defining words and their pronunciations.

  5. Within the lexeme element, add a grapheme element and a phoneme element.

    • <grapheme></grapheme>. Contains the written form of a word.

    • <phoneme></phoneme>. Contains phones that describe the pronunciation of a word.

  6. In the grapheme element, enter the word for which you want to specify a pronunciation.

  7. Using the phone tables below, look up the phones that correspond to the sound of each syllable in your word. Use the Sample Pronunciations below to understand how to combine phones to describe the sound of a syllable.

  8. In the phoneme element, enter the phones that describe the word's pronunciation. Phones are case-sensitive and must be space-delimited. Optionally include markers for syllable emphasis (S1, S2) and for separating syllables (.) to further refine the pronunciation. See Suprasegmentals later in this topic.

  9. If you want to specify multiple pronunciations for the same word, add more phoneme elements within the lexeme element. When specifying multiple pronunciations for a word, you can designate one pronunciation as preferred by adding the attribute/value pair prefer="true" to the phoneme element, for example: <phoneme prefer="true">1 l eh d </phoneme>.

  10. Continue adding lexeme elements for each word whose pronunciation you want to specify.

  11. Add the closing lexicon tag: </lexicon>, and save the document with a .pls extension.

You can optionally include an <example></example> element within the lexeme element that contains a sample usage of the grapheme.

Here is an example of a completed lexicon document that specifies pronunciations for fictional names:

XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>

<lexicon version="1.0"
  xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
  http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
  alphabet="x-microsoft-ups" xml:lang="en-US">

  <lexeme>
    <grapheme> Klhtr </grapheme>
    <phoneme> K L EH . S1 T AA R </phoneme>
  </lexeme>

  <lexeme>
    <grapheme> Eanor </grapheme>
    <phoneme> S1 I . AX . N O R </phoneme>
  </lexeme>

  <lexeme>
    <grapheme> Puntahrik </grapheme>
    <phoneme> P UH N . S1 T AA . R IH K</phoneme>
  </lexeme>

</lexicon>

Link the Lexicon to the Grammar

Now that you have created your lexicon, you must link to it from your grammar, using the following steps.

Link a Lexicon to a Grammar

  1. After the opening tag of the grammar element, and before the first rule element, enter a lexicon element: <lexicon />

  2. Add a uri attribute to the lexicon element and enter the path and name of the lexicon file. For example: <lexicon uri="c:\MyLexicon.pls" /> OR <lexicon uri= "http://contoso.com/lexiconstore/MyLexicon.pls"/>

The following is an example of a grammar that references the lexicon of fictional names shown above:

Copy image Copy Code
<?xml version="1.0" encoding="UTF-8"?>

<grammar
  version="1.0" mode="voice" root="warriors"
  xml:lang="en-US" tag-format="semantics/1.0"
  sapi:alphabet="x-microsoft-ups"
  xml:base="http://www.contoso.com/"
  xmlns="http://www.w3.org/2001/06/grammar"
  xmlns:sapi="http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions">

  <lexicon uri="c:\test\Warriors.pls" />

  <rule id="warriors" scope="public">
    <item> The warrior's name is </item>
    <one-of>
      <item> Klhtr </item>
      <item> Eanor </item>
      <item> Puntahrik </item>
    </one-of>
  </rule>

</grammar>

UPS Phone Tables

The following tables contain the most commonly used phones for US English from Microsoft's Universal Phone Set (UPS).

Note Note

UPS phones are case-sensitive.

Consonants

The following table lists the most commonly used consonant phones for US English from Microsoft's Universal Phone Set (UPS).

UPS Phone | Example
B | big
CH | chin
D | dig
DH | then
DX | butter
F | fork
G | gut
H | help
JH | joy
K | cut
L | lid
M | mat
N | no
NG | sing
P | put
R | red
S | sit
SH | she
T | talk
TH | thin
V | vat
W | with
J | yard
Z | zap
ZH | pleasure

Vowels

The following table lists the most commonly used vowel phones for US English from Microsoft's Universal Phone Set (UPS).

UPS Phone | Example
AA | father
AE | cat
AH | cut
AO | dog
AOX | four
AU | foul
AX | ago
AX rho | minor
AI | bite
EH | pet
EHX | stairs
ER | fur
ER rho | urban
EI | ate
IH | fill
I | feel
O | go
OI | toy
OWX | boa
Q | hot
UH | book
U | too, blue
UWX | lure

Suprasegmentals

Suprasegmentals are optional markers that indicate the division of a word into syllables, identify which syllables receive emphasis (stress), and specify the length of syllables. The following suprasegmental markers of the UPS are commonly used to create pronunciations for words in US English:

UPS Phone | Description | Example
S1 | Indicates that the following syllable receives primary emphasis. | F AX . S1 N EH S (finesse)
S2 | Indicates that the following syllable receives secondary emphasis. | K AX N . S1 S ER rho . V AX . S2 T R I (conservatory)
. | Indicates a break between syllables. | S1 K O . K O (cocoa)
lng | Extends the length of the preceding syllable. | B I . S1 W EH lng R (beware)

Sample Pronunciations

The following table contains a sampling of words in US English and their phonetic spellings (pronunciations) using UPS phones. Use this table to understand which phones represent sounds in US English with which you are already familiar, and as a guide to combining phones to create syllables and words.

Note Note

  • The words in this table are not words that require custom pronunciations.

  • The phones used in pronunciations are case-sensitive and must be space-delimited.

  • The use of the suprasegmental markers (S1, S2, .) is optional.

  • UPS provides a compounding or tying symbol "+" that can be used to describe composite sounds from any two phones. For more information, see Compound Tying Symbol (Microsoft.Speech).

Word | Pronunciation | Word | Pronunciation
action | S1 AE K . SH IH N | junkyard | S1 JH AH NG . K J AA R D
adverse | S1 AE D . V ER rho S | king | S1 K IH NG
analog | S1 AE . N AX . L AA G | lady | S1 L E + I . D I
around | AX . S1 R A + UH N D | leave | S1 L I V
avail | AX . S1 V E + I L | left | S1 L EH F T
beauty | S1 B J U . DX I | lion | S1 L A + I . AX N
believe | B AX . S1 L I V | little | S1 L IH . DX AX L
beware | B I . S1 W EH lng R | luscious | S1 L AH . SH AX S
bittersweet | S1 B IH . DX AX rho . S W I T | magic | S1 M AE . JH IH K
blood | S1 B L AH D | Mary | S1 M EH lng . R I
burrito | B AX . S1 R I . T O | minor | S1 M A + I . N AX rho
cell-phone | S1 S EH L _& S1 F O N | name | S1 N E + I M
champagne | SH AE M . S1 P E + I N | Olympics | AX . S1 L IH M . P IH K S
cocoa | S1 K O . K O | orchestras | S1 AO R . K IH . S T R AX Z
coconuts | S1 K O . K AX . N AH T S | outdoors | S1 A + UH T . D AO R Z
collect | K AX . S1 L EH K T | Pisces | S1 P A + I . S I Z
comets | S1 K AA . M IH T S | quick | S1 K W IH K
conformity | K AX N . S1 F AO R . M IH . DX I | raindrop | S1 R E + I N . D R AA P
conservatory | K AX N . S1 S ER rho . V AX . S2 T R I | refreshments | R AX . S1 F R EH SH . M AX N T S
contemporary | S2 K AX N . S1 T EH M . P AX . R AX . R I | refused | R AX . S1 F J U Z D
creations | S1 K R I . E + I . SH AX N Z | revolution | R EH . V AX . S1 L U . SH AX N
cross | S1 K R AA S | rolling | S1 R O . L IH NG
deed | S1 D I D | round | S1 R A + UH N D
dog | S1 D AO G | saffron | S1 S AE . F R AA N
duckling | S1 D AH . K L IH NG | short | S1 SH AO R T
enthusiast | EH N . S1 TH U . Z I . AE S T | snow | S1 S N O
excerpt | S1 EH K . S AX rho P T | song | S1 S AO NG
facile | S1 F AE . S A + I L | sponge | S1 S P AH N JH
falling | S1 F AO L . L IH NG | strawberries | S1 S T R AO . B EH . R I Z
far | S1 F AA R | strollers | S1 S T R AO . L AX rho Z
fastball | S1 F AE S T . B AO L | subway | S1 S AH B . W E + I
finesse | F AX . S1 N EH S | tribe | S1 T R A + I B
friends | S1 F R EH N Z | thrill | S1 TH R IH L
furnaces | S1 F ER rho . N IH . S IH Z | toasters | S1 T O . S T AX rho Z
garden | S1 G AA R . D IH N | toothpaste | S1 T U TH . P E + I S T
great | S1 G R E + I T | towering | S1 T A + UH . AX . R IH NG
head | S1 H EH D | toy | S1 T AO +I
hothouse | S1 H AO T . H A + UH S | tractors | S1 T R AE K . T AX rho Z
howlers | S1 H A + UH . L AX rho Z | tragically | S1 T R AE . JH IH . K L I
hunchback | S1 H AH N CH . B AE K | undertakers | S1 AH N . D AX rho . T E + I . K AX rho Z
hygienist | H A + I . S1 JH EH . N IH S T | unrest | S1 AH N . R EH S T
impossible | IH M . S1 P AA . S IH . B AX L | urban | S1 ER rho . B AX N
informant | IH N . S1 F AO R . M AX N T | vagabonds | S1 V AE . G AX . B AA N D Z
instruction | IH N . S1 S T R AH K . SH AX N | vanished | S1 V AE . N IH SH T
intruders | IH N . S1 T R U . D AX rho Z | velvet | S1 V EH L . V IH T
islanders | S1 A + I . L AX N . D AX rho Z | why | S1 H W A + I
journal | S1 JH ER rho . N AX L | why | S1 W A + I
jungle | S1 JH AH NG . G AX L | zippers | S1 Z IH . P AX rho Z

See Also

Concepts

Custom Pronunciations Support
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Microsoft.Speech Managed Code Class Library

[image]

Microsoft.Speech Managed Code Class Library
Send Feedback

This section contains the managed-code reference for the Microsoft.Speech namespaces.

In This Section

You will find documentation for the following Microsoft.Speech namespaces in this section:

Reference

  • Microsoft.Speech

  • Microsoft.Speech.AudioFormat

  • Microsoft.Speech.Recognition

  • Microsoft.Speech.Recognition.SrgsGrammar

  • Microsoft.Speech.Synthesis

  • Microsoft.Speech.Text

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Microsoft.Speech Namespace

[image]

Microsoft.Speech Namespace
Send Feedback

Gives applications control over loading resources.

Interfaces

 | Interface | Description
Public interface | ISpeechResourceLoader | Gives applications control over loading resources.
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ISpeechResourceLoader Interface

[image]

ISpeechResourceLoader Interface
Members See Also Send Feedback

Gives applications control over loading resources.

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

Syntax

Visual Basic (Declaration)
Public Interface ISpeechResourceLoader
Visual Basic (Usage)
Dim instance As ISpeechResourceLoader
C#
public interface ISpeechResourceLoader

Remarks

For example, application authors may want to cache remote resources, enforce custom security policies, or redirect resources to other locations.

See Also

Reference

ISpeechResourceLoader Members
Microsoft.Speech Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ISpeechResourceLoader Members

[image] [image]

ISpeechResourceLoader Members
ISpeechResourceLoader Interface Methods See Also Send Feedback

Gives applications control over loading resources.

The ISpeechResourceLoader type exposes the following members.

Methods

 | Name | Description
Public method | GetLocalCopy | Gets a local copy of the specified speech resource.
Public method | ReleaseLocalCopy | Releases the local copy of the specified speech resource.
Top

See Also

Reference

ISpeechResourceLoader Interface
Microsoft.Speech Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ISpeechResourceLoader Methods

[image] [image]

ISpeechResourceLoader Methods
ISpeechResourceLoader Interface See Also Send Feedback

The ISpeechResourceLoader type exposes the following members.

Methods

 | Name | Description
Public method | GetLocalCopy | Gets a local copy of the specified speech resource.
Public method | ReleaseLocalCopy | Releases the local copy of the specified speech resource.
Top

See Also

Reference

ISpeechResourceLoader Interface
Microsoft.Speech Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetLocalCopy Method

[image]

ISpeechResourceLoader..::..GetLocalCopy Method
ISpeechResourceLoader Interface See Also Send Feedback

Gets a local copy of the specified speech resource.

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

Syntax

Visual Basic (Declaration)
Function GetLocalCopy ( _
    resourcePath As Uri, _
    <OutAttribute> ByRef mimeType As String, _
    <OutAttribute> ByRef redirectUrl As Uri _
) As String
Visual Basic (Usage)
Dim instance As ISpeechResourceLoader
Dim resourcePath As Uri
Dim mimeType As String
Dim redirectUrl As Uri
Dim returnValue As String

returnValue = instance.GetLocalCopy(resourcePath, _
    mimeType, redirectUrl)
C#
string GetLocalCopy(
    Uri resourcePath,
    out string mimeType,
    out Uri redirectUrl
)

Parameters

resourcePath
Type: System..::..Uri
mimeType
Type: System..::..String %
redirectUrl
Type: System..::..Uri %

Return Value

Type: System..::..String

Remarks

The local file must reside on the machine on which the Speech process is running.

See Also

Reference

ISpeechResourceLoader Interface
ISpeechResourceLoader Members
Microsoft.Speech Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ReleaseLocalCopy Method

[image]

ISpeechResourceLoader..::..ReleaseLocalCopy Method
ISpeechResourceLoader Interface See Also Send Feedback

Releases the local copy of the specified speech resource.

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

Syntax

Visual Basic (Declaration)
Sub ReleaseLocalCopy ( _
    path As String _
)
Visual Basic (Usage)
Dim instance As ISpeechResourceLoader
Dim path As String

instance.ReleaseLocalCopy(path)
C#
void ReleaseLocalCopy(
    string path
)

Parameters

path
Type: System..::..String

See Also

Reference

ISpeechResourceLoader Interface
ISpeechResourceLoader Members
Microsoft.Speech Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Microsoft.Speech.AudioFormat Namespace

[image]

Microsoft.Speech.AudioFormat Namespace
See Also Send Feedback

The Microsoft.Speech.AudioFormat namespace consists of a single class, SpeechAudioFormatInfo, which contains information about the format of the audio that is being input to the speech recognition engine, or being output from the speech synthesis engine.

You can use the properties of SpeechAudioFormatInfo to obtain information about specific characteristics of an audio format. These properties are read-only, except for BlockAlign, which you can use to set the block alignment of incoming audio. To get all the properties of the incoming audio format, use the FormatSpecificData()()()() method.

Using the constructors on the SpeechAudioFormatInfo class, you can specify any of the properties of the audio format when you initialize the object.

Classes

 | Class | Description
Public class | SpeechAudioFormatInfo | Represents information about an audio format.

Enumerations

 | Enumeration | Description
Public enumeration | AudioBitsPerSample | Enumerates values that describe the bits-per-sample characteristic of an audio format.
Public enumeration | AudioChannel | Enumerates values that indicate the number of channels in the audio format.
Public enumeration | EncodingFormat | Enumerates values that describe the encoding format of audio.

See Also

Reference

Microsoft.Speech.Recognition
Microsoft.Speech.Recognition.SrgsGrammar
Microsoft.Speech.Synthesis
Microsoft.Speech.Text
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioBitsPerSample Enumeration

[image]

AudioBitsPerSample Enumeration
See Also Send Feedback

Enumerates values that describe the bits-per-sample characteristic of an audio format.

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

Syntax

Visual Basic (Declaration)
Public Enumeration AudioBitsPerSample
Visual Basic (Usage)
Dim instance As AudioBitsPerSample
C#
public enum AudioBitsPerSample

Members

Member name | Description
Eight | The audio format has 8 bits per sample.
Sixteen | The audio format has 16 bits per sample.

Remarks

The BitsPerSample property gets a member of AudioBitsPerSample that indicates the bits-per-sample of an audio format.

See Also

Reference

Microsoft.Speech.AudioFormat Namespace
SpeechAudioFormatInfo
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioChannel Enumeration

[image]

AudioChannel Enumeration
See Also Send Feedback

Enumerates values that indicate the number of channels in the audio format.

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

Syntax

Visual Basic (Declaration)
Public Enumeration AudioChannel
Visual Basic (Usage)
Dim instance As AudioChannel
C#
public enum AudioChannel

Members

Member name | Description
Mono | The audio format has one channel.
Stereo | The audio format has two channels.

Remarks

The ChannelCount property gets a member of AudioChannel that indicates the number of channels for the audio format.

See Also

Reference

Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EncodingFormat Enumeration

[image]

EncodingFormat Enumeration
See Also Send Feedback

Enumerates values that describe the encoding format of audio.

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

Syntax

Visual Basic (Declaration)
Public Enumeration EncodingFormat
Visual Basic (Usage)
Dim instance As EncodingFormat
C#
public enum EncodingFormat

Members

Member name | Description
Pcm | The encoding format of the audio is Pulse Code Modulation (PCM).
ALaw | The encoding format of the audio is ALaw.
ULaw | The encoding format of the audio is ULaw.

Remarks

The EncodingFormat property gets a member of EncodingFormat that indicates the encoding format of audio.

See Also

Reference

Microsoft.Speech.AudioFormat Namespace
SpeechAudioFormatInfo
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechAudioFormatInfo Class

[image]

SpeechAudioFormatInfo Class
Members See Also Send Feedback

Represents information about an audio format.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.AudioFormat..::..SpeechAudioFormatInfo

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class SpeechAudioFormatInfo
Visual Basic (Usage)
Dim instance As SpeechAudioFormatInfo
C#
[SerializableAttribute]
public class SpeechAudioFormatInfo

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SpeechAudioFormatInfo Members
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechAudioFormatInfo Members

[image] [image]

SpeechAudioFormatInfo Members
SpeechAudioFormatInfo Class Constructors Methods Properties See Also Send Feedback

Represents information about an audio format.

The SpeechAudioFormatInfo type exposes the following members.

Constructors

 | Name | Description
Public method | SpeechAudioFormatInfo(Int32, AudioBitsPerSample, AudioChannel) | Initializes a new instance of the SpeechAudioFormatInfo class and specifies the samples per second, bits per sample, and the number of channels.
Public method | SpeechAudioFormatInfo(EncodingFormat, Int32, Int32, Int32, Int32, Int32, array<Byte>[]()[][]) | Initializes a new instance of the SpeechAudioFormatInfo class and specifies the encoding format, samples per second, bits per sample, number of channels, average bytes per second, block alignment value, and an array containing format-specific data.
Top

Properties

 | Name | Description
Public property | AverageBytesPerSecond | Gets the average bytes per second of the audio.
Public property | BitsPerSample | Gets the bits per sample of the audio.
Public property | BlockAlign | Gets and sets the block alignment in bytes.
Public property | ChannelCount | Gets the channel count of the audio.
Public property | EncodingFormat | Gets the encoding format of the audio.
Public property | SamplesPerSecond | Gets the samples per second of the audio.
Top

Methods

 | Name | Description
Public method | Equals | Returns whether a given object is an instance of SpeechAudioFormatInfo and equal to the current instance of SpeechAudioFormatInfo. (Overrides Object..::..Equals(Object).)
Protected method | Finalize | (Inherited from Object.)
Public method | FormatSpecificData | Returns the format-specific data of the audio format.
Public method | GetHashCode | Returns the hash code of the audio format. (Overrides Object..::..GetHashCode()()()().)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeechAudioFormatInfo Class
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechAudioFormatInfo Constructor

[image] [image]

SpeechAudioFormatInfo Constructor
SpeechAudioFormatInfo Class See Also Send Feedback

Initializes a new instance of the SpeechAudioFormatInfo class.

Overload List

 | Name | Description
Public method | SpeechAudioFormatInfo(Int32, AudioBitsPerSample, AudioChannel) | Initializes a new instance of the SpeechAudioFormatInfo class and specifies the samples per second, bits per sample, and the number of channels.
Public method | SpeechAudioFormatInfo(EncodingFormat, Int32, Int32, Int32, Int32, Int32, array<Byte>[]()[][]) | Initializes a new instance of the SpeechAudioFormatInfo class and specifies the encoding format, samples per second, bits per sample, number of channels, average bytes per second, block alignment value, and an array containing format-specific data.
Top

See Also

Reference

SpeechAudioFormatInfo Class
SpeechAudioFormatInfo Members
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechAudioFormatInfo Constructor (Int32, AudioBitsPerSample, AudioChannel)

[image]

SpeechAudioFormatInfo Constructor (Int32, AudioBitsPerSample, AudioChannel)
SpeechAudioFormatInfo Class See Also Send Feedback

Initializes a new instance of the SpeechAudioFormatInfo class and specifies the samples per second, bits per sample, and the number of channels.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    samplesPerSecond As Integer, _
    bitsPerSample As AudioBitsPerSample, _
    channel As AudioChannel _
)
Visual Basic (Usage)
Dim samplesPerSecond As Integer
Dim bitsPerSample As AudioBitsPerSample
Dim channel As AudioChannel

Dim instance As New SpeechAudioFormatInfo(samplesPerSecond, _
    bitsPerSample, channel)
C#
public SpeechAudioFormatInfo(
    int samplesPerSecond,
    AudioBitsPerSample bitsPerSample,
    AudioChannel channel
)

Parameters

samplesPerSecond
Type: System..::..Int32

An int containing the samples per second value.

bitsPerSample
Type: Microsoft.Speech.AudioFormat..::..AudioBitsPerSample

An int containing the bits per sample value.

channel
Type: Microsoft.Speech.AudioFormat..::..AudioChannel

A member of the AudioChannel enumeration (ie., Mono or Stereo).

See Also

Reference

SpeechAudioFormatInfo Class
SpeechAudioFormatInfo Members
SpeechAudioFormatInfo Overload
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechAudioFormatInfo Constructor (EncodingFormat, Int32, Int32, Int32, Int32, Int32, Byte[])

[image]

SpeechAudioFormatInfo Constructor (EncodingFormat, Int32, Int32, Int32, Int32, Int32, array<Byte>[]()[][])
SpeechAudioFormatInfo Class See Also Send Feedback

Initializes a new instance of the SpeechAudioFormatInfo class and specifies the encoding format, samples per second, bits per sample, number of channels, average bytes per second, block alignment value, and an array containing format-specific data.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    encodingFormat As EncodingFormat, _
    samplesPerSecond As Integer, _
    bitsPerSample As Integer, _
    channelCount As Integer, _
    averageBytesPerSecond As Integer, _
    blockAlign As Integer, _
    formatSpecificData As Byte() _
)
Visual Basic (Usage)
Dim encodingFormat As EncodingFormat
Dim samplesPerSecond As Integer
Dim bitsPerSample As Integer
Dim channelCount As Integer
Dim averageBytesPerSecond As Integer
Dim blockAlign As Integer
Dim formatSpecificData As Byte()

Dim instance As New SpeechAudioFormatInfo(encodingFormat, _
    samplesPerSecond, bitsPerSample, _
    channelCount, averageBytesPerSecond, _
    blockAlign, formatSpecificData)
C#
public SpeechAudioFormatInfo(
    EncodingFormat encodingFormat,
    int samplesPerSecond,
    int bitsPerSample,
    int channelCount,
    int averageBytesPerSecond,
    int blockAlign,
    byte[] formatSpecificData
)

Parameters

encodingFormat
Type: Microsoft.Speech.AudioFormat..::..EncodingFormat

An EncodingFormat object.

samplesPerSecond
Type: System..::..Int32

An int containing the samples per second value.

bitsPerSample
Type: System..::..Int32

An int containing the bits per sample value.

channelCount
Type: System..::..Int32

An int containing the channel count value.

averageBytesPerSecond
Type: System..::..Int32

An int containing the average bytes per second value.

blockAlign
Type: System..::..Int32

An int containing the BlockAlign value.

formatSpecificData
Type: array< System..::..Byte >[]()[][]

A byte array containing the format-specific data.

See Also

Reference

SpeechAudioFormatInfo Class
SpeechAudioFormatInfo Members
SpeechAudioFormatInfo Overload
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechAudioFormatInfo Methods

[image] [image]

SpeechAudioFormatInfo Methods
SpeechAudioFormatInfo Class See Also Send Feedback

The SpeechAudioFormatInfo type exposes the following members.

Methods

 | Name | Description
Public method | Equals | Returns whether a given object is an instance of SpeechAudioFormatInfo and equal to the current instance of SpeechAudioFormatInfo. (Overrides Object..::..Equals(Object).)
Protected method | Finalize | (Inherited from Object.)
Public method | FormatSpecificData | Returns the format-specific data of the audio format.
Public method | GetHashCode | Returns the hash code of the audio format. (Overrides Object..::..GetHashCode()()()().)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeechAudioFormatInfo Class
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Equals Method

[image]

SpeechAudioFormatInfo..::..Equals Method
SpeechAudioFormatInfo Class See Also Send Feedback

Returns whether a given object is an instance of SpeechAudioFormatInfo and equal to the current instance of SpeechAudioFormatInfo.

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

Syntax

Visual Basic (Declaration)
Public Overrides Function Equals ( _
    obj As Object _
) As Boolean
Visual Basic (Usage)
Dim instance As SpeechAudioFormatInfo
Dim obj As Object
Dim returnValue As Boolean

returnValue = instance.Equals(obj)
C#
public override bool Equals(
    Object obj
)

Parameters

obj
Type: System..::..Object

The object to be compared.

Return Value

Type: System..::..Boolean

Returns true if the current instance of SpeechAudioFormatInfo and that obtained from the obj argument are equal, otherwise returns false.

Remarks

The method returns false if the Object provided by the obj argument cannot be cast to SpeechAudioFormatInfo.

See Also

Reference

SpeechAudioFormatInfo Class
SpeechAudioFormatInfo Members
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


FormatSpecificData Method

[image]

SpeechAudioFormatInfo..::..FormatSpecificData Method
SpeechAudioFormatInfo Class See Also Send Feedback

Returns the format-specific data of the audio format.

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

Syntax

Visual Basic (Declaration)
Public Function FormatSpecificData As Byte()
Visual Basic (Usage)
Dim instance As SpeechAudioFormatInfo
Dim returnValue As Byte()

returnValue = instance.FormatSpecificData()
C#
public byte[] FormatSpecificData()

Return Value

Type: array< System..::..Byte >[]()[][]

A byte array containing the format-specific data.

See Also

Reference

SpeechAudioFormatInfo Class
SpeechAudioFormatInfo Members
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetHashCode Method

[image]

SpeechAudioFormatInfo..::..GetHashCode Method
SpeechAudioFormatInfo Class See Also Send Feedback

Returns the hash code of the audio format.

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

Syntax

Visual Basic (Declaration)
Public Overrides Function GetHashCode As Integer
Visual Basic (Usage)
Dim instance As SpeechAudioFormatInfo
Dim returnValue As Integer

returnValue = instance.GetHashCode()
C#
public override int GetHashCode()

Return Value

Type: System..::..Int32

An int containing the hash code.

See Also

Reference

SpeechAudioFormatInfo Class
SpeechAudioFormatInfo Members
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechAudioFormatInfo Properties

[image] [image]

SpeechAudioFormatInfo Properties
SpeechAudioFormatInfo Class See Also Send Feedback

The SpeechAudioFormatInfo type exposes the following members.

Properties

 | Name | Description
Public property | AverageBytesPerSecond | Gets the average bytes per second of the audio.
Public property | BitsPerSample | Gets the bits per sample of the audio.
Public property | BlockAlign | Gets and sets the block alignment in bytes.
Public property | ChannelCount | Gets the channel count of the audio.
Public property | EncodingFormat | Gets the encoding format of the audio.
Public property | SamplesPerSecond | Gets the samples per second of the audio.
Top

See Also

Reference

SpeechAudioFormatInfo Class
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AverageBytesPerSecond Property

[image]

SpeechAudioFormatInfo..::..AverageBytesPerSecond Property
SpeechAudioFormatInfo Class See Also Send Feedback

Gets the average bytes per second of the audio.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AverageBytesPerSecond As Integer
    Get
Visual Basic (Usage)
Dim instance As SpeechAudioFormatInfo
Dim value As Integer

value = instance.AverageBytesPerSecond
C#
public int AverageBytesPerSecond { get; }

Property Value

Type: System..::..Int32

An int containing the average bytes per second value.

See Also

Reference

SpeechAudioFormatInfo Class
SpeechAudioFormatInfo Members
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


BitsPerSample Property

[image]

SpeechAudioFormatInfo..::..BitsPerSample Property
SpeechAudioFormatInfo Class See Also Send Feedback

Gets the bits per sample of the audio.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property BitsPerSample As Integer
    Get
Visual Basic (Usage)
Dim instance As SpeechAudioFormatInfo
Dim value As Integer

value = instance.BitsPerSample
C#
public int BitsPerSample { get; }

Property Value

Type: System..::..Int32

An int containing the bits per sample value.

See Also

Reference

SpeechAudioFormatInfo Class
SpeechAudioFormatInfo Members
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


BlockAlign Property

[image]

SpeechAudioFormatInfo..::..BlockAlign Property
SpeechAudioFormatInfo Class See Also Send Feedback

Gets and sets the block alignment in bytes.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property BlockAlign As Integer
    Get
Visual Basic (Usage)
Dim instance As SpeechAudioFormatInfo
Dim value As Integer

value = instance.BlockAlign
C#
public int BlockAlign { get; }

Property Value

Type: System..::..Int32

An int containing the block alignment value.

Remarks

Playback and record software handles audio data in blocks. The sizes of these blocks are multiples of the value of the BlockAlign property. Block alignment value is the number of bytes in an atomic unit (that is, a block) of audio for a particular format. For Pulse Code Modulation (PCM) formats, the formula for calculating block alignment is as follows:

  • Block Alignment = Bytes per Sample x Number of Channels

For example, the block alignment value for 16-bit PCM format mono audio is 2 (2 bytes per sample x 1 channel). For 16-bit PCM format stereo audio, the block alignment value is 4.

Data written and read from a device must always start at the beginning of a block. For example, it is illegal to start playback of PCM data in the middle of a sample (meaning on a boundary that is not block-aligned).

See Also

Reference

SpeechAudioFormatInfo Class
SpeechAudioFormatInfo Members
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ChannelCount Property

[image]

SpeechAudioFormatInfo..::..ChannelCount Property
SpeechAudioFormatInfo Class See Also Send Feedback

Gets the channel count of the audio.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property ChannelCount As Integer
    Get
Visual Basic (Usage)
Dim instance As SpeechAudioFormatInfo
Dim value As Integer

value = instance.ChannelCount
C#
public int ChannelCount { get; }

Property Value

Type: System..::..Int32

An int containing the channel count value.

See Also

Reference

SpeechAudioFormatInfo Class
SpeechAudioFormatInfo Members
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EncodingFormat Property

[image]

SpeechAudioFormatInfo..::..EncodingFormat Property
SpeechAudioFormatInfo Class See Also Send Feedback

Gets the encoding format of the audio.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property EncodingFormat As EncodingFormat
    Get
Visual Basic (Usage)
Dim instance As SpeechAudioFormatInfo
Dim value As EncodingFormat

value = instance.EncodingFormat
C#
public EncodingFormat EncodingFormat { get; }

Property Value

Type: Microsoft.Speech.AudioFormat..::..EncodingFormat

The encoding format of the audio.

See Also

Reference

SpeechAudioFormatInfo Class
SpeechAudioFormatInfo Members
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SamplesPerSecond Property

[image]

SpeechAudioFormatInfo..::..SamplesPerSecond Property
SpeechAudioFormatInfo Class See Also Send Feedback

Gets the samples per second of the audio.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property SamplesPerSecond As Integer
    Get
Visual Basic (Usage)
Dim instance As SpeechAudioFormatInfo
Dim value As Integer

value = instance.SamplesPerSecond
C#
public int SamplesPerSecond { get; }

Property Value

Type: System..::..Int32

An int containing the samples per second value.

See Also

Reference

SpeechAudioFormatInfo Class
SpeechAudioFormatInfo Members
Microsoft.Speech.AudioFormat Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Microsoft.Speech.Recognition Namespace

[image]

Microsoft.Speech.Recognition Namespace
Send Feedback

Contains types for implementing recognition of speech and Dual-Tone Multi-Frequency (DTMF) tones for applications running on Windows Server.

The Microsoft Speech Platform SDK 11 offers a basic speech recognition infrastructure that digitizes acoustical signals, and recovers words, speech elements from audio input, and also processes DTMF tones.

Applications use the Microsoft.Speech.Recognition namespace to access and extend this basic speech recognition technology by defining algorithms for identifying and acting on specific phrases or word patterns, and by managing the runtime behavior of this speech infrastructure.

Create Grammars

You create grammars, which consist of a set of rules or constraints, to define words and phrases that your application will recognize as meaningful input. Using a constructor for the Grammar class, you can create a grammar object at runtime from GrammarBuilder or SrgsDocument instances, or from a file, a string, or a stream that contains a definition of a grammar.

Using the GrammarBuilder and Choices classes, you can build grammar documents programmatically that do not depend on or conform to the Speech Recognition Grammar Specification 1.0 (SRGS). To create SRGS-compliant grammars programmatically, use the types and members of the Microsoft.Speech.Recognition.SrgsGrammar name space.

See Create Grammars (Microsoft.Speech) in the Microsoft Speech Programming Guide for more information and examples.

Manage Speech Recognition Engines

Instances of SpeechRecognitionEngine supplied with Grammar objects provide the primary access to and control over the speech recognition engines (Server Runtime Languages) installed on the system. The Microsoft Speech Platform Runtime 11 and Speech Platform SDK 11 do not include any engines for speech recognition in a specific language. You must download a language pack (an engine for speech recognition in a specific language) for each language on which you want to perform speech recognition.

You can use SpeechRecognitionEngine to select an installed speech recognition engine, to start, pause, or stop recognition, to load and unload grammars, to configure parameters for recognition, to configure the input to recognition, and to monitor the incoming audio signal.

See Initialize and Manage a Speech Recognition Engine (Microsoft.Speech) in the Microsoft Speech Programming Guide for more information.

The DtmfRecognitionEngine class provides control over engines that recognize DTMF tones.

Respond to Events

SpeechRecognitionEngine objects generate events in response to audio input to the speech recognition engine. The AudioLevelUpdated, AudioSignalProblemOccurred, AudioStateChanged events are raised in response to changes in the incoming signal. The SpeechDetected event is raised when the speech recognition engine identifies incoming audio as speech. The speech recognition engine raises the SpeechRecognized event when it matches speech input to one of its loaded grammars, and raises the SpeechRecognitionRejected when speech input does not match any of its loaded grammars.

Other types of events include the LoadGrammarCompleted event which a speech recognition engine raises when it has loaded a grammar.

The DtmfRecognitionEngine generates a similar set of events, but in response to receiving DTMF tones, rather than speech, as input.

You can register to be notified for events that the speech recognition engine raises and create handlers using the EventsArgs classes associated with each of these events to program your application's behavior when an event is raised.

See Use Speech Recognition Events (Microsoft.Speech)in the Microsoft Speech Programming Guide for more information.

Classes

 | Class | Description
Public class | AudioLevelUpdatedEventArgs | Provides data for the AudioLevelUpdated event.
Public class | AudioSignalProblemOccurredEventArgs | Provides data for the AudioSignalProblemOccurred event.
Public class | AudioStateChangedEventArgs | Provides data for the AudioStateChanged event of the SpeechRecognitionEngine class.
Public class | Choices | Represents a list of alternative items to make up an element in a grammar.
Public class | DtmfHypothesizedEventArgs | Provides data for the DtmfHypothesized event.
Public class | DtmfRecognitionEngine | Provides access to DTMF recognition services.
Public class | DtmfRecognitionRejectedEventArgs | Provides data for the DtmfRecognitionRejected event.
Public class | DtmfRecognizeCompletedEventArgs | Returns information from the RecognizeCompleted event.
Public class | DtmfRecognizedEventArgs | Provides data for the DtmfRecognized event.
Public class | EmulateRecognizeCompletedEventArgs | Provides data for the EmulateRecognizeCompleted event.
Public class | Grammar | A runtime object that references a speech recognition grammar, which an application can use to define the constraints for speech recognition.
Public class | GrammarBuilder | Provides a mechanism for programmatically building the constraints for a speech recognition grammar.
Public class | GrammarInfo | Represents an object that contains static information about a speech recognition grammar. In contrast, a Grammar object contains information about a speech recognition grammar that is loaded into a speech recognizer at run time.
Public class | GrammarInfoPartsCollection | Represents a collection of speech recognition engine parts.
Public class | InvalidCultureException | Thrown on an attempt to use a grammar with an unrecognized CultureInfo setting.
Public class | LoadGrammarCompletedEventArgs | Provides data for the LoadGrammarCompleted event.
Public class | RecognitionEventArgs | Provides information about speech recognition events.
Public class | RecognitionResult | Contains detailed information about input that was recognized by instances of SpeechRecognitionEngine or DtmfRecognitionEngine.
Public class | RecognizeCompletedEventArgs | Provides data for the RecognizeCompleted event.
Public class | RecognizedAudio | Represents audio input that is associated with a RecognitionResult.
Public class | RecognizedPhrase | Contains detailed information, generated by the speech recognition engine, about the recognized input.
Public class | RecognizedWordUnit | Provides the atomic unit of recognized speech.
Public class | RecognizerInfo | Represents information about a SpeechRecognitionEngine object.
Public class | RecognizerUpdateReachedEventArgs | Provides data for the RecognizerUpdateReached event.
Public class | ReplacementText | Contains information about a speech normalization procedure that has been performed on recognition results.
Public class | SemanticResultKey | Associates a key string with SemanticResultValue values to define the SemanticValue objects.
Public class | SemanticResultValue | Represents a semantic value and optionally associates the value with a component of a speech recognition grammar.
Public class | SemanticValue | Represents the semantic organization of a recognized phrase.
Public class | SpeechDetectedEventArgs | Provides data for the SpeechDetected event.
Public class | SpeechHypothesizedEventArgs | Infrastructure. Provides data for the SpeechHypothesized event.
Public class | SpeechRecognitionEngine | Provides the means to access and manage a speech recognition engine.
Public class | SpeechRecognitionRejectedEventArgs | Provides information for the SpeechRecognitionRejected event.
Public class | SpeechRecognizedEventArgs | Provides information for the Grammar..::..SpeechRecognized and SpeechRecognitionEngine..::..SpeechRecognized events.

Enumerations

 | Enumeration | Description
Public enumeration | AudioSignalProblem | Contains a list of possible problems in the audio signal coming in to a speech recognition engine.
Public enumeration | AudioState | Contains a list of possible states for the audio input to a speech recognition engine.
Public enumeration | DisplayAttributes | Lists the options that the SpeechRecognitionEngine object can use to specify white space for the display of a word or punctuation mark.
Public enumeration | DtmfTone | Enumerates values of the first 16 DTMF tones.
Public enumeration | EmulateOptions | Specifies the type of recognition operation that is performed by EmulateRecognize()()()() and EmulateRecognizeAsync()()()() methods that take this object as a parameter.
Public enumeration | Pronounceable | Lists values that represent whether the SpeechRecognitionEngine can pronounce a word and whether the pronunciation is defined in a lexicon.
Public enumeration | RecognizeMode | Enumerates values of the recognition mode.
Public enumeration | SubsetMatchingMode | Enumerates values of subset matching mode.
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioLevelUpdatedEventArgs Class

[image]

AudioLevelUpdatedEventArgs Class
Members Example See Also Send Feedback

Provides data for the AudioLevelUpdated event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Recognition..::..AudioLevelUpdatedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class AudioLevelUpdatedEventArgs _
    Inherits EventArgs
Visual Basic (Usage)
Dim instance As AudioLevelUpdatedEventArgs
C#
public class AudioLevelUpdatedEventArgs : EventArgs

Remarks

An instance of AudioLevelUpdatedEventArgs is created when the SpeechRecognitionEngine object raises the SpeechRecognitionEngine..::..AudioLevelUpdated event. To obtain the new level of audio input, access the AudioLevel property in the handler for the event.

You can obtain the current level of the input to the SpeechRecognitionEngine at any time using the AudioLevel property.

Examples

The following example adds an event handler to a SpeechRecognitionEngine object. The handler outputs the new audio level to the console.

AudioLevelUpdatedEventArgs derives from EventArgs.

C# Copy image Copy Code
private SpeechRecognitionEngine sre;

// Initialize the SpeechRecognitionEngine object.
private void Initialize()
{
  sre = new SpeechRecognitionEngine();

  // Add an event handler for the AudioLevelUpdated event.
  sre.AudioLevelUpdated += new EventHandler<AudioLevelUpdatedEventArgs>(sre_AudioLevelUpdated);

  // Add other initialization code here.
}

// Write the audio level to the console when the AudioLevelUpdated event is raised.
void sre_AudioLevelUpdated(object sender, AudioLevelUpdatedEventArgs e)
{
  Console.WriteLine("The audio level is now: {0}.", e.AudioLevel);
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

AudioLevelUpdatedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioLevelUpdatedEventArgs Members

[image] [image]

AudioLevelUpdatedEventArgs Members
AudioLevelUpdatedEventArgs Class Methods Properties See Also Send Feedback

Provides data for the AudioLevelUpdated event.

The AudioLevelUpdatedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioLevel | Gets the new level of audio input after the SpeechRecognitionEngine..::..AudioLevelUpdated event is raised.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

AudioLevelUpdatedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioLevelUpdatedEventArgs Methods

[image] [image]

AudioLevelUpdatedEventArgs Methods
AudioLevelUpdatedEventArgs Class See Also Send Feedback

The AudioLevelUpdatedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

AudioLevelUpdatedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioLevelUpdatedEventArgs Properties

[image] [image]

AudioLevelUpdatedEventArgs Properties
AudioLevelUpdatedEventArgs Class See Also Send Feedback

The AudioLevelUpdatedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioLevel | Gets the new level of audio input after the SpeechRecognitionEngine..::..AudioLevelUpdated event is raised.
Top

See Also

Reference

AudioLevelUpdatedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioLevel Property

[image]

AudioLevelUpdatedEventArgs..::..AudioLevel Property
AudioLevelUpdatedEventArgs Class See Also Send Feedback

Gets the new level of audio input after the SpeechRecognitionEngine..::..AudioLevelUpdated event is raised.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioLevel As Integer
    Get
Visual Basic (Usage)
Dim instance As AudioLevelUpdatedEventArgs
Dim value As Integer

value = instance.AudioLevel
C#
public int AudioLevel { get; }

Property Value

Type: System..::..Int32

The new level of audio input.

See Also

Reference

AudioLevelUpdatedEventArgs Class
AudioLevelUpdatedEventArgs Members
Microsoft.Speech.Recognition Namespace
AudioLevelUpdatedEventArgs
SpeechRecognitionEngine..::..AudioLevel
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioSignalProblem Enumeration

[image]

AudioSignalProblem Enumeration
Example See Also Send Feedback

Contains a list of possible problems in the audio signal coming in to a speech recognition engine.

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

Syntax

Visual Basic (Declaration)
Public Enumeration AudioSignalProblem
Visual Basic (Usage)
Dim instance As AudioSignalProblem
C#
public enum AudioSignalProblem

Members

Member name | Description
None | No problems with audio input.
TooNoisy | Audio input has too much background noise.
NoSignal | Audio input is not detected.
TooLoud | Audio input is too loud.
TooSoft | Audio input is too quiet.
TooFast | Audio input is too fast.
TooSlow | Audio input is too slow.

Remarks

The AudioSignalProblem property of the AudioSignalProblemOccurredEventArgs class gets a member of this enumeration when the SpeechRecognitionEngine raises the AudioSignalProblemOccurred event.

Examples

The following example defines an event handler that gathers information about an AudioSignalProblemOccurred event.

C# Copy image Copy Code
private SpeechRecognitionEngine sre;

// Initialize the speech recognition engine.
private void Initialize()
{
  sre = new SpeechRecognitionEngine();

  // Add a handler for the AudioSignalProblemOccurred event.
  sre.AudioSignalProblemOccurred += new EventHandler<AudioSignalProblemOccurredEventArgs>(sre_AudioSignalProblemOccurred);
}

// Gather information when the AudioSignalProblemOccurred event is raised.
void sre_AudioSignalProblemOccurred(object sender, AudioSignalProblemOccurredEventArgs e)
{
  StringBuilder details = new StringBuilder();

  details.AppendLine("Audio signal problem information:");
  details.AppendFormat(
    " Audio level:               {0}" + Environment.NewLine +
    " Audio position:            {1}" + Environment.NewLine +
    " Audio signal problem:      {2}" + Environment.NewLine +
    " Recognition engine audio position: {3}" + Environment.NewLine,
    e.AudioLevel, e.AudioPosition, e.AudioSignalProblem,
    e.recoEngineAudioPosition);

  // Insert additional event handler code here.
}

See Also

Reference

Microsoft.Speech.Recognition Namespace
AudioSignalProblem
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioSignalProblemOccurredEventArgs Class

[image]

AudioSignalProblemOccurredEventArgs Class
Members Example See Also Send Feedback

Provides data for the AudioSignalProblemOccurred event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Recognition..::..AudioSignalProblemOccurredEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class AudioSignalProblemOccurredEventArgs _
    Inherits EventArgs
Visual Basic (Usage)
Dim instance As AudioSignalProblemOccurredEventArgs
C#
public class AudioSignalProblemOccurredEventArgs : EventArgs

Remarks

An instance of AudioSignalProblemOccurredEventArgs is created when the SpeechRecognitionEngine object raises the AudioSignalProblemOccurred event. To obtain information related to the AudioSignalProblemOccurred event, access the following properties in the handler for the event:

  • AudioLevel

  • AudioPosition

  • AudioSignalProblem

  • RecognizerAudioPosition

The AudioPosition property references the input device's position in its generated audio stream. By contrast, the RecognizerAudioPosition property references the recognizer's position within its audio input. These positions can be different. For more information, see Use Speech Recognition Events (Microsoft.Speech).

The AudioSignalProblem property indicates which problem occurred.

AudioSignalProblemOccurredEventArgs derives from EventArgs.

Examples

The following example defines an event handler that gathers information about an AudioSignalProblemOccurred event.

C# Copy image Copy Code
private SpeechRecognitionEngine sre;

// Initialize the speech recognition engine.
private void Initialize()
{
  sre = new SpeechRecognitionEngine();

  // Add a handler for the AudioSignalProblemOccurred event.
  sre.AudioSignalProblemOccurred += new EventHandler<AudioSignalProblemOccurredEventArgs>(sre_AudioSignalProblemOccurred);
}

// Gather information when the AudioSignalProblemOccurred event is raised.
void sre_AudioSignalProblemOccurred(object sender, AudioSignalProblemOccurredEventArgs e)
{
  StringBuilder details = new StringBuilder();

  details.AppendLine("Audio signal problem information:");
  details.AppendFormat(
    " Audio level:               {0}" + Environment.NewLine +
    " Audio position:            {1}" + Environment.NewLine +
    " Audio signal problem:      {2}" + Environment.NewLine +
    " Recognition engine audio position: {3}" + Environment.NewLine,
    e.AudioLevel, e.AudioPosition,  e.AudioSignalProblem,
    e.RecognizerAudioPosition);

  // Insert additional event handler code here.
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

AudioSignalProblemOccurredEventArgs Members
Microsoft.Speech.Recognition Namespace
AudioSignalProblem
SpeechRecognitionEngine..::..AudioSignalProblemOccurred
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioSignalProblemOccurredEventArgs Members

[image] [image]

AudioSignalProblemOccurredEventArgs Members
AudioSignalProblemOccurredEventArgs Class Methods Properties See Also Send Feedback

Provides data for the AudioSignalProblemOccurred event.

The AudioSignalProblemOccurredEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioLevel | Gets the audio level associated with the event.
Public property | AudioPosition | Gets the position in the input device's audio stream that indicates where the problem occurred.
Public property | AudioSignalProblem | Gets the audio signal problem.
Public property | RecognizerAudioPosition | Gets the recognizer audio position associated with the event.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

AudioSignalProblemOccurredEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioSignalProblemOccurredEventArgs Methods

[image] [image]

AudioSignalProblemOccurredEventArgs Methods
AudioSignalProblemOccurredEventArgs Class See Also Send Feedback

The AudioSignalProblemOccurredEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

AudioSignalProblemOccurredEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioSignalProblemOccurredEventArgs Properties

[image] [image]

AudioSignalProblemOccurredEventArgs Properties
AudioSignalProblemOccurredEventArgs Class See Also Send Feedback

The AudioSignalProblemOccurredEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioLevel | Gets the audio level associated with the event.
Public property | AudioPosition | Gets the position in the input device's audio stream that indicates where the problem occurred.
Public property | AudioSignalProblem | Gets the audio signal problem.
Public property | RecognizerAudioPosition | Gets the recognizer audio position associated with the event.
Top

See Also

Reference

AudioSignalProblemOccurredEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioLevel Property

[image]

AudioSignalProblemOccurredEventArgs..::..AudioLevel Property
AudioSignalProblemOccurredEventArgs Class See Also Send Feedback

Gets the audio level associated with the event.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioLevel As Integer
    Get
Visual Basic (Usage)
Dim instance As AudioSignalProblemOccurredEventArgs
Dim value As Integer

value = instance.AudioLevel
C#
public int AudioLevel { get; }

Property Value

Type: System..::..Int32

The level of audio input when the AudioSignalProblemOccurred event was raised.

See Also

Reference

AudioSignalProblemOccurredEventArgs Class
AudioSignalProblemOccurredEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioPosition Property

[image]

AudioSignalProblemOccurredEventArgs..::..AudioPosition Property
AudioSignalProblemOccurredEventArgs Class See Also Send Feedback

Gets the position in the input device's audio stream that indicates where the problem occurred.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioPosition As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As AudioSignalProblemOccurredEventArgs
Dim value As TimeSpan

value = instance.AudioPosition
C#
public TimeSpan AudioPosition { get; }

Property Value

Type: System..::..TimeSpan

The location in the audio input stream when the AudioSignalProblemOccurred event was raised.

Remarks

The AudioPosition property references the input device's position in its generated audio stream. By contrast, the RecognizerAudioPosition property references the recognizer's position within its audio input. These positions can be different. For more information, see Use Speech Recognition Events (Microsoft.Speech).

See Also

Reference

AudioSignalProblemOccurredEventArgs Class
AudioSignalProblemOccurredEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioSignalProblem Property

[image]

AudioSignalProblemOccurredEventArgs..::..AudioSignalProblem Property
AudioSignalProblemOccurredEventArgs Class See Also Send Feedback

Gets the audio signal problem.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioSignalProblem As AudioSignalProblem
    Get
Visual Basic (Usage)
Dim instance As AudioSignalProblemOccurredEventArgs
Dim value As AudioSignalProblem

value = instance.AudioSignalProblem
C#
public AudioSignalProblem AudioSignalProblem { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..AudioSignalProblem

The audio signal problem that caused the AudioSignalProblemOccurred event to be raised.

See Also

Reference

AudioSignalProblemOccurredEventArgs Class
AudioSignalProblemOccurredEventArgs Members
Microsoft.Speech.Recognition Namespace
AudioState
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizerAudioPosition Property

[image]

AudioSignalProblemOccurredEventArgs..::..RecognizerAudioPosition Property
AudioSignalProblemOccurredEventArgs Class See Also Send Feedback

Gets the recognizer audio position associated with the event.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property RecognizerAudioPosition As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As AudioSignalProblemOccurredEventArgs
Dim value As TimeSpan

value = instance.RecognizerAudioPosition
C#
public TimeSpan RecognizerAudioPosition { get; }

Property Value

Type: System..::..TimeSpan

The position in the audio input that the recognizer has received when the AudioSignalProblemOccurred event was raised.

Remarks

The AudioPosition property references the input device's position in its generated audio stream. By contrast, the RecognizerAudioPosition property references the recognizer's position within its audio input. These positions can be different. For more information, see Use Speech Recognition Events (Microsoft.Speech).

See Also

Reference

AudioSignalProblemOccurredEventArgs Class
AudioSignalProblemOccurredEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioState Enumeration

[image]

AudioState Enumeration
Example See Also Send Feedback

Contains a list of possible states for the audio input to a speech recognition engine.

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

Syntax

Visual Basic (Declaration)
Public Enumeration AudioState
Visual Basic (Usage)
Dim instance As AudioState
C#
public enum AudioState

Members

Member name | Description
Stopped | Not processing audio input.
Silence | Receiving silence or non-speech background noise.
Speech | Receiving speech input.

Remarks

An AudioStateChanged event is generated whenever the recognition engine's AudioState changes. When the AudioStateChanged event is raised, the AudioState property gets a member of the AudioState enumeration to describe the state of the audio input to the speech recognition engine.

You can obtain the state of the audio input to the speech recognition engine at any time using the SpeechRecognitionEngine..::..AudioState property.

Examples

The following example demonstrates an event handler that handles the changing audio state of a speech recognizer.

C# Copy image Copy Code
private SpeechRecognitionEngine sre;

// Initializes the speech recognition engine.
private void Initialize()
{
  sre = new SpeechRecognitionEngine();

  // Add a handler for the AudioStateChanged event.
  sre.AudioStateChanged += new EventHandler<AudioStateChangedEventArgs>(sre_AudioStateChanged);

  // Add other initialization code here.
}

  // Handle the AudioStateChanged event.
  void sre_AudioStateChanged(object sender, AudioStateChangedEventArgs e)
{
  AudioState newState = e.AudioState;

  // Handle event here.
}

See Also

Reference

Microsoft.Speech.Recognition Namespace
AudioState
AudioStateChanged
AudioStateChangedEventArgs
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioStateChangedEventArgs Class

[image]

AudioStateChangedEventArgs Class
Members Example See Also Send Feedback

Provides data for the AudioStateChanged event of the SpeechRecognitionEngine class.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Recognition..::..AudioStateChangedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class AudioStateChangedEventArgs _
    Inherits EventArgs
Visual Basic (Usage)
Dim instance As AudioStateChangedEventArgs
C#
public class AudioStateChangedEventArgs : EventArgs

Remarks

An instance of AudioStateChangedEventArgs is created when the SpeechRecognitionEngine object raises the AudioStateChanged event. To obtain the new state of audio input, access the AudioState property in the handler for the event.

You can obtain the current state of the audio input to the SpeechRecognitionEngine at any time using the AudioState property.

Examples

The following example demonstrates an event handler for handling the changing audio state of a speech recognition engine.

C# Copy image Copy Code
private SpeechRecognitionEngine sre;

// Initialize the SpeechRecognitionEngine object.
private void Initialize()
{
  sre = new SpeechRecognitionEngine();

  // Add a handler for the AudioStateChanged event.
  sre.AudioStateChanged += new EventHandler<AudioStateChangedEventArgs>(sre_AudioStateChanged);

  // Add other initialization code here.
}

// Handle the AudioStateChanged event.
void sre_AudioStateChanged(object sender, AudioStateChangedEventArgs e)
{
  AudioState newState = e.AudioState;

  // Handle event here.
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

AudioStateChangedEventArgs Members
Microsoft.Speech.Recognition Namespace
AudioState
AudioStateChanged
AudioState
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioStateChangedEventArgs Members

[image] [image]

AudioStateChangedEventArgs Members
AudioStateChangedEventArgs Class Methods Properties See Also Send Feedback

Provides data for the AudioStateChanged event of the SpeechRecognitionEngine class.

The AudioStateChangedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioState | Gets the new state of audio input to the SpeechRecognitionEngine.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

AudioStateChangedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioStateChangedEventArgs Methods

[image] [image]

AudioStateChangedEventArgs Methods
AudioStateChangedEventArgs Class See Also Send Feedback

The AudioStateChangedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

AudioStateChangedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioStateChangedEventArgs Properties

[image] [image]

AudioStateChangedEventArgs Properties
AudioStateChangedEventArgs Class See Also Send Feedback

The AudioStateChangedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioState | Gets the new state of audio input to the SpeechRecognitionEngine.
Top

See Also

Reference

AudioStateChangedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioState Property

[image]

AudioStateChangedEventArgs..::..AudioState Property
AudioStateChangedEventArgs Class See Also Send Feedback

Gets the new state of audio input to the SpeechRecognitionEngine.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioState As AudioState
    Get
Visual Basic (Usage)
Dim instance As AudioStateChangedEventArgs
Dim value As AudioState

value = instance.AudioState
C#
public AudioState AudioState { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..AudioState

The state of the audio input signal after the AudioStateChanged event was raised.

Remarks

The AudioState property contains one of three values from the AudioState enumeration.

See Also

Reference

AudioStateChangedEventArgs Class
AudioStateChangedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Choices Class

[image]

Choices Class
Members Example See Also Send Feedback

Represents a list of alternative items to make up an element in a grammar.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..Choices

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

Syntax

Visual Basic (Declaration)
Public Class Choices
Visual Basic (Usage)
Dim instance As Choices
C#
public class Choices

Remarks

A Choices object represents a component of a phrase that can have one of several values. Use this class when creating a speech recognition grammar from a GrammarBuilder object.

For example, a Choices object could represent the component colorChoice in the phrase, "Change the color to colorChoice", where acceptable values for colorChoice are "red", or "green", or "blue".

Note Note

To use a Choices object as an optional component in a phrase, create the Choices object and add it to a GrammarBuilder..::..GrammarBuilder(GrammarBuilder, Int32, Int32) object with minRepeat and maxRepeat set to 0 and 1, respectively. Phrases containing optional components can be recognized whether or not the optional component is spoken.

The Choices class serves the same function as the one-of XML element defined by the Speech Recognition Grammar Specification (SRGS) Version 1.0, and is similar to the SrgsOneOf class in the Microsoft.Speech.Recognition.SrgsGrammar namespace.

Examples

The following example creates a speech recognition grammar for the phrase, "Set background to colorChoice", where colorChoice can be one of the defined colors. The GrammarBuilder is used to define the constraints for the grammar.

Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a Choices object that contains a set of alternative colors.
  Choices colorChoice = new Choices(new string[] {"red", "green", "blue"});
  colorChoice.Add(new string[] {"cyan", "yellow", "magenta"});

  // Construct the phrase.
  GrammarBuilder builder = new GrammarBuilder("Set background to");
  builder.Append(colorChoice);

  // Create a grammar for the phrase.
  Grammar colorGrammar = new Grammar(builder);
  colorGrammar.Name = "SetBackground";

  return colorGrammar;
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

Choices Members
Microsoft.Speech.Recognition Namespace
Microsoft.Speech.Recognition.SrgsGrammar
GrammarBuilder
Grammar

Other Resources

Speech
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Choices Members

[image] [image]

Choices Members
Choices Class Constructors Methods See Also Send Feedback

Represents a list of alternative items to make up an element in a grammar.

The Choices type exposes the following members.

Constructors

 | Name | Description
Public method | Choices()()()() | Initializes a new instance of the Choices class that contains an empty set of alternatives.
Public method | Choices(array<String>[]()[][]) | Initializes a new instance of the Choices class from an array containing one or more String objects.
Public method | Choices(array<GrammarBuilder>[]()[][]) | Initializes a new instance of the Choices class from an array containing one or more GrammarBuilder objects.
Top

Methods

 | Name | Description
Public method | Add(array<String>[]()[][]) | Adds an array containing one or more String objects to the set of alternatives.
Public method | Add(array<GrammarBuilder>[]()[][]) | Adds an array containing one or more GrammarBuilder objects to the set of alternatives.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToGrammarBuilder | Returns a GrammarBuilder object from this Choices object.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

Choices Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Choices Constructor

[image] [image]

Choices Constructor
Choices Class Example See Also Send Feedback

Initializes a new instance of the Choices class that contains an empty set of alternatives.

Overload List

 | Name | Description
Public method | Choices()()()() | Initializes a new instance of the Choices class that contains an empty set of alternatives.
Public method | Choices(array<String>[]()[][]) | Initializes a new instance of the Choices class from an array containing one or more String objects.
Public method | Choices(array<GrammarBuilder>[]()[][]) | Initializes a new instance of the Choices class from an array containing one or more GrammarBuilder objects.
Top

Remarks

You can construct a Choices object using a default constructor (which returns an empty object), from a group of String objects, or a from set of GrammarBuilder objects.

Because the GrammarBuilder object supports implicit conversion from SemanticResultValue and SemanticResultKey, a Choices can be constructed from an array of these objects using a cast.

Examples

The following example uses Choices objects to create two lists of alternatives.

The first Choices object is constructed from an array of String objects. The other Choices object is constructed from an array of GrammarBuilder objects which have been implicitly converted by a cast.

The example uses a GrammarBuilder object to assemble a phrase, using the Choices objects and two additional strings, that can be used to recognize speech input in the form of "Call [contactlList] on [phoneType] phone" , for example "Call Jane on cell phone".

Copy image Copy Code
public GrammarBuilder ChoicesContructor2 ()
{
    GrammarBuilder gb = new GrammarBuilder ();
    Choices phoneType = new Choices (new string[] {"cell", "home", "work"});
    Choices contactList = new Choices (new GrammarBuilder[] {(GrammarBuilder) "Mark", (GrammarBuilder) "Jane", (GrammarBuilder) "Frank"});
    gb.Append ("Call");
    gb.Append (contactList);
    gb.Append ("on");
    gb.Append (phoneType);
    gb.Append ("phone");
    return gb;
}

See Also

Reference

Choices Class
Choices Members
Microsoft.Speech.Recognition Namespace
GrammarBuilder
Grammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Choices Constructor

[image]

Choices Constructor
Choices Class Example See Also Send Feedback

Initializes a new instance of the Choices class that contains an empty set of alternatives.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New Choices()
C#
public Choices()

Remarks

This constructor returns a valid, empty set of alternatives. You can add alternatives using any of the Add methods.

Examples

The following example uses Choices and GrammarBuilder objects to create a phrase that can be used to recognize speech input such as "Call Anne on her cell" and "Call James on his work phone". The example uses implicit casts from Choices and String to GrammarBuilder.

Copy image Copy Code
public Grammar CreatePhonePhrase()
{

  // Create alternatives for female names and add a phrase.
  GrammarBuilder females = new Choices(new string[] { "Anne", "Mary" });
  females.Append("on her");

  // Create alternatives for male names and add a phrase.
  GrammarBuilder males = new Choices(new string[] { "James", "Sam" });
  males.Append("on his");

  // Create a Choices object that contains an array of alternative
  // GrammarBuilder objects.
  Choices people = new Choices();
  people.Add(new Choices(new GrammarBuilder[] {females, males}));

  // Create a Choices object that contains a set of alternative phone types.
  Choices phoneType = new Choices();
  phoneType.Add(new string[] { "cell", "home", "work" });

  // Construct the phrase.
  GrammarBuilder gb = new GrammarBuilder();
  gb.Append("call");
  gb.Append(people);
  gb.Append(phoneType);
  gb.Append(new GrammarBuilder("phone"), 0, 1);

  return new Grammar(gb);
}

See Also

Reference

Choices Class
Choices Members
Choices Overload
Microsoft.Speech.Recognition Namespace
GrammarBuilder
Grammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Choices Constructor (String[])

[image]

Choices Constructor (array<String>[]()[][])
Choices Class Example See Also Send Feedback

Initializes a new instance of the Choices class from an array containing one or more String objects.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    ParamArray phrases As String() _
)
Visual Basic (Usage)
Dim phrases As String()

Dim instance As New Choices(phrases)
C#
public Choices(
    params string[] phrases
)

Parameters

phrases
Type: array< System..::..String >[]()[][]

An array containing the set of alternatives.

Remarks

Each String in phrases defines one alternative. The speech recognition engine can use any one of the items in the string array to match speech input. If phrases is an empty array, the constructor returns an empty set of alternatives. You can add alternatives using any of the Add methods.

The constructor throws an ArgumentNullException when phrases is nullNothingnullptrunita null reference (Nothing in Visual Basic) or any of the array elements are nullNothingnullptrunita null reference (Nothing in Visual Basic). The constructor throws an ArgumentException if any element in the array is an empty string ("").

Examples

The following example uses Choices and GrammarBuilder objects to create a phrase that can be used to recognize speech input such as "Call Anne on her cell" and "Call James on his work phone". The example uses implicit casts from Choices and String to GrammarBuilder.

Copy image Copy Code
public Grammar CreatePhonePhrase()
{

  // Create alternatives for female names and add a phrase.
  GrammarBuilder females = new Choices(new string[] { "Anne", "Mary" });
  females.Append("on her");

  // Create alternatives for male names and add a phrase.
  GrammarBuilder males = new Choices(new string[] { "James", "Sam" });
  males.Append("on his");

  // Create a Choices object that contains an array of alternative
  // GrammarBuilder objects.
  Choices people = new Choices();
  people.Add(new Choices(new GrammarBuilder[] {females, males}));

  // Create a Choices object that contains a set of alternative phone types.
  Choices phoneType = new Choices();
  phoneType.Add(new string[] { "cell", "home", "work" });

  // Construct the phrase.
  GrammarBuilder gb = new GrammarBuilder();
  gb.Append("call");
  gb.Append(people);
  gb.Append(phoneType);
  gb.Append(new GrammarBuilder("phone"), 0, 1);

  return new Grammar(gb);
}

See Also

Reference

Choices Class
Choices Members
Choices Overload
Microsoft.Speech.Recognition Namespace
GrammarBuilder
Grammar
SemanticResultValue
SemanticResultKey
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Choices Constructor (GrammarBuilder[])

[image]

Choices Constructor (array<GrammarBuilder>[]()[][])
Choices Class Example See Also Send Feedback

Initializes a new instance of the Choices class from an array containing one or more GrammarBuilder objects.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    ParamArray alternateChoices As GrammarBuilder() _
)
Visual Basic (Usage)
Dim alternateChoices As GrammarBuilder()

Dim instance As New Choices(alternateChoices)
C#
public Choices(
    params GrammarBuilder[] alternateChoices
)

Parameters

alternateChoices
Type: array< Microsoft.Speech.Recognition..::..GrammarBuilder >[]()[][]

An array containing the set of alternatives.

Remarks

Each GrammarBuilder in alternateChoices defines one alternative. If alternateChoices is an empty array, the constructor returns an empty set of alternatives. You can add alternatives using any of the Add methods.

The constructor throws an ArgumentNullException when alternateChoices is nullNothingnullptrunita null reference (Nothing in Visual Basic) or when any of the array elements are nullNothingnullptrunita null reference (Nothing in Visual Basic).

Because the GrammarBuilder class provides support for implicit conversion of Choices, SemanticResultValue, and SemanticResultKey objects to GrammarBuilder instances, by properly using casts, this constructor can also be used to create a Choices object from a list of any combination of these objects.

Examples

The following example uses Choices and GrammarBuilder objects to create a phrase that can be used to recognize speech input such as "Call Anne on her cell" and "Call James on his work phone". The example uses implicit casts from Choices and String to GrammarBuilder.

Copy image Copy Code
public Grammar CreatePhonePhrase()
{

  // Create alternatives for female names and add a phrase.
  GrammarBuilder females = new Choices(new string[] { "Anne", "Mary" });
  females.Append("on her");

  // Create alternatives for male names and add a phrase.
  GrammarBuilder males = new Choices(new string[] { "James", "Sam" });
  males.Append("on his");

  // Create a Choices object that contains an array of alternative
  // GrammarBuilder objects.
  Choices people = new Choices();
  people.Add(new Choices(new GrammarBuilder[] {females, males}));

  // Create a Choices object that contains a set of alternative phone types.
  Choices phoneType = new Choices();
  phoneType.Add(new string[] { "cell", "home", "work" });

  // Construct the phrase.
  GrammarBuilder gb = new GrammarBuilder();
  gb.Append("call");
  gb.Append(people);
  gb.Append(phoneType);
  gb.Append(new GrammarBuilder("phone"), 0, 1);

  return new Grammar(gb);
}

See Also

Reference

Choices Class
Choices Members
Choices Overload
Microsoft.Speech.Recognition Namespace
GrammarBuilder
Grammar
SemanticResultValue
SemanticResultKey
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Choices Methods

[image] [image]

Choices Methods
Choices Class See Also Send Feedback

The Choices type exposes the following members.

Methods

 | Name | Description
Public method | Add(array<String>[]()[][]) | Adds an array containing one or more String objects to the set of alternatives.
Public method | Add(array<GrammarBuilder>[]()[][]) | Adds an array containing one or more GrammarBuilder objects to the set of alternatives.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToGrammarBuilder | Returns a GrammarBuilder object from this Choices object.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

Choices Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method

[image] [image]

Choices..::..Add Method
Choices Class See Also Send Feedback

Overload List

 | Name | Description
Public method | Add(array<String>[]()[][]) | Adds an array containing one or more String objects to the set of alternatives.
Public method | Add(array<GrammarBuilder>[]()[][]) | Adds an array containing one or more GrammarBuilder objects to the set of alternatives.
Top

See Also

Reference

Choices Class
Choices Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method (String[])

[image]

Choices..::..Add Method (array<String>[]()[][])
Choices Class Example See Also Send Feedback

Adds an array containing one or more String objects to the set of alternatives.

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

Syntax

Visual Basic (Declaration)
Public Sub Add ( _
    ParamArray phrases As String() _
)
Visual Basic (Usage)
Dim instance As Choices
Dim phrases As String()

instance.Add(phrases)
C#
public void Add(
    params string[] phrases
)

Parameters

phrases
Type: array< System..::..String >[]()[][]

The strings to add to this Choices object.

Remarks

Applications can use both Add(array<String>[]()[][]) and Add(array<GrammarBuilder>[]()[][]) to add alternatives to a Choices object.

If phrases is an empty array, this method does not update the set of alternates.

This method throws an ArgumentNullException when phrases is nullNothingnullptrunita null reference (Nothing in Visual Basic) or any of the array elements are nullNothingnullptrunita null reference (Nothing in Visual Basic). This method throws an ArgumentException if any element in the array is the empty string ("").

Examples

The following example creates a speech recognition grammar for phrases similar to "Call Anne on her cell" and "Call James on his work phone". The example uses both overloads of the Add method to build the grammar.

Copy image Copy Code
public Grammar CreatePhonePhrase()
{

  // Create alternatives for female names and add a phrase.
  GrammarBuilder females = new Choices(new string[] { "Anne", "Mary" });
  females.Append("on her");

  // Create alternatives for male names and add a phrase.
  GrammarBuilder males = new Choices(new string[] { "James", "Sam" });
  males.Append("on his");

  // Create a Choices object that contains an array of alternative
  // GrammarBuilder objects.
  Choices people = new Choices();
  people.Add(new Choices(new GrammarBuilder[] {females, males}));

  // Create a Choices object that contains a set of alternative phone types.
  Choices phoneType = new Choices();
  phoneType.Add(new string[] { "cell", "home", "work" });

  // Construct the phrase.
  GrammarBuilder gb = new GrammarBuilder();
  gb.Append("call");
  gb.Append(people);
  gb.Append(phoneType);
  gb.Append(new GrammarBuilder("phone"), 0, 1);

  return new Grammar(gb);
}

See Also

Reference

Choices Class
Choices Members
Add Overload
Microsoft.Speech.Recognition Namespace
GrammarBuilder
Grammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method (GrammarBuilder[])

[image]

Choices..::..Add Method (array<GrammarBuilder>[]()[][])
Choices Class Example See Also Send Feedback

Adds an array containing one or more GrammarBuilder objects to the set of alternatives.

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

Syntax

Visual Basic (Declaration)
Public Sub Add ( _
    ParamArray alternateChoices As GrammarBuilder() _
)
Visual Basic (Usage)
Dim instance As Choices
Dim alternateChoices As GrammarBuilder()

instance.Add(alternateChoices)
C#
public void Add(
    params GrammarBuilder[] alternateChoices
)

Parameters

alternateChoices
Type: array< Microsoft.Speech.Recognition..::..GrammarBuilder >[]()[][]

The GrammarBuilder objects to add to this Choices object.

Remarks

Because of support for implicit conversion from Choices, SemanticResultKey, and SemanticResultValue objects to GrammarBuilder, these three classes may be added to a Choices instance as well.

If alternateChoices is an empty array, this method does not update the set of alternatives.

Applications can use both Add(array<String>[]()[][]) and Add(array<GrammarBuilder>[]()[][]) to add alternatives to a Choices object.

This method throws an ArgumentNullException when alternateChoices is nullNothingnullptrunita null reference (Nothing in Visual Basic) or any of the array elements are nullNothingnullptrunita null reference (Nothing in Visual Basic).

Examples

The following example creates a speech recognition grammar for phrases such as "Call Anne on her cell" and "Call James on his work phone". The example uses both overloads of the Add method to build the grammar.

Copy image Copy Code
public Grammar CreatePhonePhrase()
{

  // Create alternatives for female names and add a phrase.
  GrammarBuilder females = new Choices(new string[] { "Anne", "Mary" });
  females.Append("on her");

  // Create alternatives for male names and add a phrase.
  GrammarBuilder males = new Choices(new string[] { "James", "Sam" });
  males.Append("on his");

  // Create a Choices object that contains an array of alternative
  // GrammarBuilder objects.
  Choices people = new Choices();
  people.Add(new Choices(new GrammarBuilder[] {females, males}));

  // Create a Choices object that contains a set of alternative phone types.
  Choices phoneType = new Choices();
  phoneType.Add(new string[] { "cell", "home", "work" });

  // Construct the phrase.
  GrammarBuilder gb = new GrammarBuilder();
  gb.Append("call");
  gb.Append(people);
  gb.Append(phoneType);
  gb.Append(new GrammarBuilder("phone"), 0, 1);

  return new Grammar(gb);
}

See Also

Reference

Choices Class
Choices Members
Add Overload
Microsoft.Speech.Recognition Namespace
GrammarBuilder
Grammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ToGrammarBuilder Method

[image]

Choices..::..ToGrammarBuilder Method
Choices Class Example See Also Send Feedback

Returns a GrammarBuilder object from this Choices object.

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

Syntax

Visual Basic (Declaration)
Public Function ToGrammarBuilder As GrammarBuilder
Visual Basic (Usage)
Dim instance As Choices
Dim returnValue As GrammarBuilder

returnValue = instance.ToGrammarBuilder()
C#
public GrammarBuilder ToGrammarBuilder()

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

A GrammarBuilder that matches this Choices object.

Remarks

The GrammarBuilder returned by this method is equivalent to one returned by either of the following.

  • Calling the #ctor(Choices) constructor with this object as the parameter.

  • Using the implicit or explicit cast of this object to a GrammarBuilder.

Examples

The following example creates a speech recognition grammar for changing the background color.

Copy image Copy Code
private Grammar CreateColorChoice()
{

  // Create a Choices object that contains a set of alternative colors.
  Choices colorChoice = new Choices(new string[] {"red", "green", "blue"});

  // Construct the phrase.
  GrammarBuilder gb = new GrammarBuilder();
  gb.Append(new Choices(new string[] {"Set", "Change"}));
  gb.Append("background to");
  gb.Append(colorChoice.ToGrammarBuilder());

  Grammar grammar = new Grammar(gb);
  grammar.Name = "modify background color";

  return grammar;
}

See Also

Reference

Choices Class
Choices Members
Microsoft.Speech.Recognition Namespace
GrammarBuilder
Grammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DisplayAttributes Enumeration

[image]

DisplayAttributes Enumeration
Example See Also Send Feedback

Lists the options that the SpeechRecognitionEngine object can use to specify white space for the display of a word or punctuation mark.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

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

Syntax

Visual Basic (Declaration)
<FlagsAttribute> _
Public Enumeration DisplayAttributes
Visual Basic (Usage)
Dim instance As DisplayAttributes
C#
[FlagsAttribute]
public enum DisplayAttributes

Members

Member name | Description
None | The item does not specify how white space is handled.
ZeroTrailingSpaces | The item has no spaces following it.
OneTrailingSpace | The item has one space following it.
TwoTrailingSpaces | The item has two spaces following it.
ConsumeLeadingSpaces | The item has no spaces preceding it.

Remarks

The speech recognition engine returns recognized phrases as collections of RecognizedWordUnit or ReplacementText objects. Each object corresponds to a single word or punctuation mark. The DisplayAttributes property of a RecognizedWordUnit or ReplacementText object uses a member of the DisplayAttributes enumeration to describe how print spacing is handled around a given word or punctuation mark.

Two or more members of the DisplayAttributes enumeration may be combined by a bit-wise OR to specify how a particular word should be displayed.

Note Note

The display formatting that the speech recognizer uses is language specific.

For example, suppose the input phrase to a recognition engine is "Hello comma he said period".

Then the recognition engine will return a RecognizedPhrase containing five RecognizedWordUnit objects containing the following strings and values of DisplayAttributes.

"Hello" | OneTrailingSpace
"," | OneTrailingSpace | ConsumeLeadingSpaces
"he" | OneTrailingSpace
"said" | OneTrailingSpace
"." | OneTrailingSpace | ConsumeLeadingSpaces

The text returned for this recognized phrase would then be printed as: "Hello, he said."

Examples

The following example shows a utility method that returns a formatted phrase from a collection of RecognizedWordUnit objects returned by a recognition engine.

Copy image Copy Code
// Use the DisplayAttributes property to format speech as text.

static string GetDisplayText(List<RecognizedWordUnit> words)
{
  StringBuilder sb = new StringBuilder();

  // Concatenate the word units together. Use the DisplayAttributes
  // property of each word unit to add or remove white space around
  // the word unit.
  foreach (RecognizedWordUnit word in words)
  {
    if ((word.DisplayAttributes
      & DisplayAttributes.ConsumeLeadingSpaces) != 0))
    {
      sb = new StringBuilder(sb.ToString().TrimEnd());
    }

    sb.Append(word.Text);

    if ((word.DisplayAttributes
      & DisplayAttributes.OneTrailingSpace) != 0)
    {
      sb.Append(" ");
    }
    else if ((word.DisplayAttributes
      & DisplayAttributes.TwoTrailingSpaces) != 0)
    {
      sb.Append("  ");
    }
  }

  return sb.ToString();
}

See Also

Reference

Microsoft.Speech.Recognition Namespace
RecognizedPhrase
RecognitionResult
RecognizedWordUnit
ReplacementText
RecognizedWordUnit..::..DisplayAttributes
ReplacementText..::..DisplayAttributes
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfHypothesizedEventArgs Class

[image]

DtmfHypothesizedEventArgs Class
Members See Also Send Feedback

Provides data for the DtmfHypothesized event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Recognition..::..RecognitionEventArgs
Microsoft.Speech.Recognition..::..DtmfHypothesizedEventArgs

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class DtmfHypothesizedEventArgs _
    Inherits RecognitionEventArgs
Visual Basic (Usage)
Dim instance As DtmfHypothesizedEventArgs
C#
[SerializableAttribute]
public class DtmfHypothesizedEventArgs : RecognitionEventArgs

Remarks

An instance of DtmfHypothesizedEventArgs is created when the DtmfRecognitionEngine object raises the DtmfHypothesized event.

DtmfHypothesizedEventArgs derives from RecognitionEventArgs.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

DtmfHypothesizedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfHypothesizedEventArgs Members

[image] [image]

DtmfHypothesizedEventArgs Members
DtmfHypothesizedEventArgs Class Methods Properties See Also Send Feedback

Provides data for the DtmfHypothesized event.

The DtmfHypothesizedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Result | Gets the results of the speech or DTMF recognition operation. (Inherited from RecognitionEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

DtmfHypothesizedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfHypothesizedEventArgs Methods

[image] [image]

DtmfHypothesizedEventArgs Methods
DtmfHypothesizedEventArgs Class See Also Send Feedback

The DtmfHypothesizedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

DtmfHypothesizedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfHypothesizedEventArgs Properties

[image] [image]

DtmfHypothesizedEventArgs Properties
DtmfHypothesizedEventArgs Class See Also Send Feedback

The DtmfHypothesizedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Result | Gets the results of the speech or DTMF recognition operation. (Inherited from RecognitionEventArgs.)
Top

See Also

Reference

DtmfHypothesizedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognitionEngine Class

[image]

DtmfRecognitionEngine Class
Members See Also Send Feedback

Provides access to DTMF recognition services.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..DtmfRecognitionEngine

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

Syntax

Visual Basic (Declaration)
Public Class DtmfRecognitionEngine _
    Implements IDisposable
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
C#
public class DtmfRecognitionEngine : IDisposable

Remarks

Dual-Tone Multi-Frequency (DTMF) tones are generated by pressing the keys on a telephone. The DtmfRecognitionEngine class supports the use of speech recognition grammars to analyze DTMF input emitted by telephones. The members of DtmfRecognitionEngine are similar to those of the SpeechRecognitionEngine class. However, the input for recognition consists of a series of DTMF tones instead of an audio stream.

The DtmfRecognitionEngine works by performing a series of emulated recognitions. It maintains a buffer with a list of tones that have been received. Every time a new tone is received, it appends the new tone to the list and emulates recognition of the whole list. This process continues until emulation produces a definitive result, or one of the timeouts is reached.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognitionEngine Members

[image] [image]

DtmfRecognitionEngine Members
DtmfRecognitionEngine Class Constructors Methods Properties Events See Also Send Feedback

Provides access to DTMF recognition services.

The DtmfRecognitionEngine type exposes the following members.

Constructors

 | Name | Description
Public method | DtmfRecognitionEngine | Initializes a new instance of the DtmfRecognitionEngine class.
Top

Properties

 | Name | Description
Public property | EndSilenceTimeoutAmbiguous | Gets or sets the interval of time to wait after an ambiguous recognition.
Public property | Grammars | Gets a list of Grammar objects loaded into the current instance of DtmfRecognitionEngine.
Public property | InitialSilenceTimeout | Gets or sets the interval of silence that can precede DTMF input before recognition fails.
Public property | InterToneTimeout | Gets or sets the time interval to wait between tones before terminating recognition.
Top

Methods

 | Name | Description
Public method | AddTone(Byte) | Adds a tone to the buffer for recognition against the loaded Grammar objects.
Public method | AddTone(DtmfTone) | Adds a tone to the buffer for recognition against the loaded Grammar objects.
Public method | Dispose | Disposes the DtmfRecognitionEngine object.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | FlushToneBuffer | Clears the tone buffer.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetTerminationTones | Gets the collection of DTMF tones that terminate recognition.
Public method | GetType | (Inherited from Object.)
Public method | LoadGrammar | Synchronously loads the specified Grammar object into the DtmfRecognitionEngine instance.
Public method | LoadGrammarAsync | Asynchronously loads the specified Grammar object into the DtmfRecognitionEngine instance.
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | RecognizeAsync()()()() | Begins asynchronous recognition.
Public method | RecognizeAsync(Boolean) | Begins asynchronous recognition.
Public method | RecognizeAsyncCancel | Terminates asynchronous recognition without waiting for the current recognition operation to complete.
Public method | SetTerminationTone | Sets a DTMF tone that will terminate DTMF recognition immediately.
Public method | SetTerminationTones | Sets a collection of DTMF tones that will terminate DTMF recognition immediately.
Public method | ToString | (Inherited from Object.)
Public method | UnloadAllGrammars | Unloads all Grammar objects from the DtmfRecognitionEngine instance.
Public method | UnloadGrammar | Unloads the specified Grammar object from the DtmfRecognitionEngine instance.
Top

Events

 | Name | Description
Public event | DtmfHypothesized | Raised when DTMF input has been detected and recognized.
Public event | DtmfRecognitionRejected | Raised when DTMF input has been detected, but cannot be recognized from current grammars.
Public event | DtmfRecognized | Raised when DTMF input has been detected and recognized.
Public event | LoadGrammarCompleted | Raised on completion of the asynchronous load of a Grammar object.
Public event | RecognizeCompleted | Raised on completion of an asynchronous recognition.
Top

See Also

Reference

DtmfRecognitionEngine Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognitionEngine Constructor

[image]

DtmfRecognitionEngine Constructor
DtmfRecognitionEngine Class See Also Send Feedback

Initializes a new instance of the DtmfRecognitionEngine class.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New DtmfRecognitionEngine()
C#
public DtmfRecognitionEngine()

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognitionEngine Methods

[image] [image]

DtmfRecognitionEngine Methods
DtmfRecognitionEngine Class See Also Send Feedback

The DtmfRecognitionEngine type exposes the following members.

Methods

 | Name | Description
Public method | AddTone(Byte) | Adds a tone to the buffer for recognition against the loaded Grammar objects.
Public method | AddTone(DtmfTone) | Adds a tone to the buffer for recognition against the loaded Grammar objects.
Public method | Dispose | Disposes the DtmfRecognitionEngine object.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | FlushToneBuffer | Clears the tone buffer.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetTerminationTones | Gets the collection of DTMF tones that terminate recognition.
Public method | GetType | (Inherited from Object.)
Public method | LoadGrammar | Synchronously loads the specified Grammar object into the DtmfRecognitionEngine instance.
Public method | LoadGrammarAsync | Asynchronously loads the specified Grammar object into the DtmfRecognitionEngine instance.
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | RecognizeAsync()()()() | Begins asynchronous recognition.
Public method | RecognizeAsync(Boolean) | Begins asynchronous recognition.
Public method | RecognizeAsyncCancel | Terminates asynchronous recognition without waiting for the current recognition operation to complete.
Public method | SetTerminationTone | Sets a DTMF tone that will terminate DTMF recognition immediately.
Public method | SetTerminationTones | Sets a collection of DTMF tones that will terminate DTMF recognition immediately.
Public method | ToString | (Inherited from Object.)
Public method | UnloadAllGrammars | Unloads all Grammar objects from the DtmfRecognitionEngine instance.
Public method | UnloadGrammar | Unloads the specified Grammar object from the DtmfRecognitionEngine instance.
Top

See Also

Reference

DtmfRecognitionEngine Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AddTone Method

[image] [image]

DtmfRecognitionEngine..::..AddTone Method
DtmfRecognitionEngine Class See Also Send Feedback

Adds a tone to the buffer for recognition against the loaded grammars.

Overload List

 | Name | Description
Public method | AddTone(Byte) | Adds a tone to the buffer for recognition against the loaded Grammar objects.
Public method | AddTone(DtmfTone) | Adds a tone to the buffer for recognition against the loaded Grammar objects.
Top

Remarks

Caution note Caution

It is possible for a caller to send many simultaneous tones to a DTMF recognition engine which can cause it to take time to process. This processing time can cause the computer that is running the DTMF recognition engine to stop responding in a timely manner, much like a denial of service attack. It is recommended that the application put a limit on the total number of tones sent to a given instance of the DtmfRecognitionEngine class.

Copy image Copy Code
// Initialize an instance of the DtmfRecognitionEngine class.
DtmfRecognitionEngine dtmfRecognizer = new DtmfRecognitionEngine();

// Create a Grammar object from a file and load it.
Grammar grammar = new Grammar("C:\\SampleGrammar.xml");
dtmfRecognizer.LoadGrammar(grammar);

// Add some tones.
dtmfRecognizer.AddTone(1);
dtmfRecognizer.AddTone(2);

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AddTone Method (Byte)

[image]

DtmfRecognitionEngine..::..AddTone Method (Byte)
DtmfRecognitionEngine Class See Also Send Feedback

Adds a tone to the buffer for recognition against the loaded Grammar objects.

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

Syntax

Visual Basic (Declaration)
Public Sub AddTone ( _
    toneId As Byte _
)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim toneId As Byte

instance.AddTone(toneId)
C#
public void AddTone(
    byte toneId
)

Parameters

toneId
Type: System..::..Byte

Remarks

The DTMF tones are defined in the DtmfTone enumeration, but other tone values are possible and legitimate.

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
AddTone Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AddTone Method (DtmfTone)

[image]

DtmfRecognitionEngine..::..AddTone Method (DtmfTone)
DtmfRecognitionEngine Class See Also Send Feedback

Adds a tone to the buffer for recognition against the loaded Grammar objects.

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

Syntax

Visual Basic (Declaration)
Public Sub AddTone ( _
    tone As DtmfTone _
)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim tone As DtmfTone

instance.AddTone(tone)
C#
public void AddTone(
    DtmfTone tone
)

Parameters

tone
Type: Microsoft.Speech.Recognition..::..DtmfTone

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
AddTone Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Dispose Method

[image]

DtmfRecognitionEngine..::..Dispose Method
DtmfRecognitionEngine Class See Also Send Feedback

Disposes the DtmfRecognitionEngine object.

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

Syntax

Visual Basic (Declaration)
Public Sub Dispose
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine

instance.Dispose()
C#
public void Dispose()

Implements

IDisposable..::..Dispose()()()()

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


FlushToneBuffer Method

[image]

DtmfRecognitionEngine..::..FlushToneBuffer Method
DtmfRecognitionEngine Class See Also Send Feedback

Clears the tone buffer.

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

Syntax

Visual Basic (Declaration)
Public Sub FlushToneBuffer
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine

instance.FlushToneBuffer()
C#
public void FlushToneBuffer()

Remarks

An InvalidOperationException is thrown if the DtmfRecognitionEngine instance is currently running.

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetTerminationTones Method

[image]

DtmfRecognitionEngine..::..GetTerminationTones Method
DtmfRecognitionEngine Class See Also Send Feedback

Gets the collection of DTMF tones that terminate recognition.

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

Syntax

Visual Basic (Declaration)
Public Function GetTerminationTones As ReadOnlyCollection(Of DtmfTone)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim returnValue As ReadOnlyCollection(Of DtmfTone)

returnValue = instance.GetTerminationTones()
C#
public ReadOnlyCollection<DtmfTone> GetTerminationTones()

Return Value

Type: System.Collections.ObjectModel..::..ReadOnlyCollection <(Of <(<' DtmfTone >)>)>

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


LoadGrammar Method

[image]

DtmfRecognitionEngine..::..LoadGrammar Method
DtmfRecognitionEngine Class See Also Send Feedback

Synchronously loads the specified Grammar object into the DtmfRecognitionEngine instance.

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

Syntax

Visual Basic (Declaration)
Public Sub LoadGrammar ( _
    grammar As Grammar _
)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim grammar As Grammar

instance.LoadGrammar(grammar)
C#
public void LoadGrammar(
    Grammar grammar
)

Parameters

grammar
Type: Microsoft.Speech.Recognition..::..Grammar

Remarks

The LoadGrammar(Grammar) method will block execution while the Grammar is being loaded. For instant return, use the LoadGrammarAsync(Grammar) method.

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


LoadGrammarAsync Method

[image]

DtmfRecognitionEngine..::..LoadGrammarAsync Method
DtmfRecognitionEngine Class See Also Send Feedback

Asynchronously loads the specified Grammar object into the DtmfRecognitionEngine instance.

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

Syntax

Visual Basic (Declaration)
Public Sub LoadGrammarAsync ( _
    grammar As Grammar _
)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim grammar As Grammar

instance.LoadGrammarAsync(grammar)
C#
public void LoadGrammarAsync(
    Grammar grammar
)

Parameters

grammar
Type: Microsoft.Speech.Recognition..::..Grammar

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeAsync Method

[image] [image]

DtmfRecognitionEngine..::..RecognizeAsync Method
DtmfRecognitionEngine Class See Also Send Feedback

Begins asynchronous recognition.

Overload List

 | Name | Description
Public method | RecognizeAsync()()()() | Begins asynchronous recognition.
Public method | RecognizeAsync(Boolean) | Begins asynchronous recognition.
Top

Remarks

Recognition will end automatically after a single result is reported.

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeAsync Method

[image]

DtmfRecognitionEngine..::..RecognizeAsync Method
DtmfRecognitionEngine Class See Also Send Feedback

Begins asynchronous recognition.

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

Syntax

Visual Basic (Declaration)
Public Sub RecognizeAsync
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine

instance.RecognizeAsync()
C#
public void RecognizeAsync()

Remarks

Recognition will end automatically after a single result is reported.

An InvalidOperationException will be thrown if the DtmfRecognitionEngine has no Grammar objects loaded, or if it is already active.

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
RecognizeAsync Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeAsync Method (Boolean)

[image]

DtmfRecognitionEngine..::..RecognizeAsync Method (Boolean)
DtmfRecognitionEngine Class See Also Send Feedback

Begins asynchronous recognition.

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

Syntax

Visual Basic (Declaration)
Public Sub RecognizeAsync ( _
    flushToneBuffer As Boolean _
)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim flushToneBuffer As Boolean

instance.RecognizeAsync(flushToneBuffer)
C#
public void RecognizeAsync(
    bool flushToneBuffer
)

Parameters

flushToneBuffer
Type: System..::..Boolean

Remarks

Recognition will end automatically after a single result is reported.

An InvalidOperationException will be thrown if the DtmfRecognitionEngine has no Grammar objects loaded, or if it is already active.

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
RecognizeAsync Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeAsyncCancel Method

[image]

DtmfRecognitionEngine..::..RecognizeAsyncCancel Method
DtmfRecognitionEngine Class See Also Send Feedback

Terminates asynchronous recognition without waiting for the current recognition operation to complete.

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

Syntax

Visual Basic (Declaration)
Public Sub RecognizeAsyncCancel
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine

instance.RecognizeAsyncCancel()
C#
public void RecognizeAsyncCancel()

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetTerminationTone Method

[image]

DtmfRecognitionEngine..::..SetTerminationTone Method
DtmfRecognitionEngine Class See Also Send Feedback

Sets a DTMF tone that will terminate DTMF recognition immediately.

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

Syntax

Visual Basic (Declaration)
Public Sub SetTerminationTone ( _
    tone As DtmfTone _
)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim tone As DtmfTone

instance.SetTerminationTone(tone)
C#
public void SetTerminationTone(
    DtmfTone tone
)

Parameters

tone
Type: Microsoft.Speech.Recognition..::..DtmfTone

Remarks

A typical use of SetTerminationTone(DtmfTone) would set Hash (the symbol #, also known as the pound sign) as the termination tone. Using this setting, an application could issue the prompt "Please enter your PIN, followed by the pound sign".

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetTerminationTones Method

[image]

DtmfRecognitionEngine..::..SetTerminationTones Method
DtmfRecognitionEngine Class See Also Send Feedback

Sets a collection of DTMF tones that will terminate DTMF recognition immediately.

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

Syntax

Visual Basic (Declaration)
Public Sub SetTerminationTones ( _
    tones As ICollection(Of DtmfTone) _
)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim tones As ICollection(Of DtmfTone)

instance.SetTerminationTones(tones)
C#
public void SetTerminationTones(
    ICollection<DtmfTone> tones
)

Parameters

tones
Type: System.Collections.Generic..::..ICollection <(Of <(<' DtmfTone >)>)>

Remarks

A typical use of SetTerminationTone(DtmfTone) would set Hash (the symbol #, also known as the pound sign) as the termination tone. Using this setting, an application could issue the prompt "Please enter your PIN, followed by the pound sign".

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


UnloadAllGrammars Method

[image]

DtmfRecognitionEngine..::..UnloadAllGrammars Method
DtmfRecognitionEngine Class See Also Send Feedback

Unloads all Grammar objects from the DtmfRecognitionEngine instance.

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

Syntax

Visual Basic (Declaration)
Public Sub UnloadAllGrammars
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine

instance.UnloadAllGrammars()
C#
public void UnloadAllGrammars()

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


UnloadGrammar Method

[image]

DtmfRecognitionEngine..::..UnloadGrammar Method
DtmfRecognitionEngine Class See Also Send Feedback

Unloads the specified Grammar object from the DtmfRecognitionEngine instance.

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

Syntax

Visual Basic (Declaration)
Public Sub UnloadGrammar ( _
    grammar As Grammar _
)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim grammar As Grammar

instance.UnloadGrammar(grammar)
C#
public void UnloadGrammar(
    Grammar grammar
)

Parameters

grammar
Type: Microsoft.Speech.Recognition..::..Grammar

Remarks

An ArgumentException is thrown if the specified Grammar object is not currently loaded in the DtmfRecognitionEngine instance.

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognitionEngine Properties

[image] [image]

DtmfRecognitionEngine Properties
DtmfRecognitionEngine Class See Also Send Feedback

The DtmfRecognitionEngine type exposes the following members.

Properties

 | Name | Description
Public property | EndSilenceTimeoutAmbiguous | Gets or sets the interval of time to wait after an ambiguous recognition.
Public property | Grammars | Gets a list of Grammar objects loaded into the current instance of DtmfRecognitionEngine.
Public property | InitialSilenceTimeout | Gets or sets the interval of silence that can precede DTMF input before recognition fails.
Public property | InterToneTimeout | Gets or sets the time interval to wait between tones before terminating recognition.
Top

See Also

Reference

DtmfRecognitionEngine Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EndSilenceTimeoutAmbiguous Property

[image]

DtmfRecognitionEngine..::..EndSilenceTimeoutAmbiguous Property
DtmfRecognitionEngine Class See Also Send Feedback

Gets or sets the interval of time to wait after an ambiguous recognition.

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

Syntax

Visual Basic (Declaration)
Public Property EndSilenceTimeoutAmbiguous As TimeSpan
    Get
    Set
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim value As TimeSpan

value = instance.EndSilenceTimeoutAmbiguous

instance.EndSilenceTimeoutAmbiguous = value
C#
public TimeSpan EndSilenceTimeoutAmbiguous { get; set; }

Property Value

Type: System..::..TimeSpan

Remarks

The EndSilenceTimeoutAmbiguous property can be used in the following circumstances:

  • The tones received have been successfully recognized, but additional tones might create a different recognition. For example, the user has entered "123" and the grammar allows both "123" and "1234".

  • The tones received have been successfully recognized, but a TerminationTone has not been entered by the user.

In both cases, the interval specified by EndSilenceTimeoutAmbiguous can give users time to enter additional tones.

See SetTerminationTone(DtmfTone) for how to set the TerminationTone.

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammars Property

[image]

DtmfRecognitionEngine..::..Grammars Property
DtmfRecognitionEngine Class See Also Send Feedback

Gets a list of Grammar objects loaded into the current instance of DtmfRecognitionEngine.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Grammars As ReadOnlyCollection(Of Grammar)
    Get
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim value As ReadOnlyCollection(Of Grammar)

value = instance.Grammars
C#
public ReadOnlyCollection<Grammar> Grammars { get; }

Property Value

Type: System.Collections.ObjectModel..::..ReadOnlyCollection <(Of <(<' Grammar >)>)>

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InitialSilenceTimeout Property

[image]

DtmfRecognitionEngine..::..InitialSilenceTimeout Property
DtmfRecognitionEngine Class See Also Send Feedback

Gets or sets the interval of silence that can precede DTMF input before recognition fails.

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

Syntax

Visual Basic (Declaration)
Public Property InitialSilenceTimeout As TimeSpan
    Get
    Set
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim value As TimeSpan

value = instance.InitialSilenceTimeout

instance.InitialSilenceTimeout = value
C#
public TimeSpan InitialSilenceTimeout { get; set; }

Property Value

Type: System..::..TimeSpan

Remarks

If InitialSilenceTimeout expires, the engine will raise the DtmfRecognitionRejected event.

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InterToneTimeout Property

[image]

DtmfRecognitionEngine..::..InterToneTimeout Property
DtmfRecognitionEngine Class See Also Send Feedback

Gets or sets the time interval to wait between tones before terminating recognition.

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

Syntax

Visual Basic (Declaration)
Public Property InterToneTimeout As TimeSpan
    Get
    Set
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim value As TimeSpan

value = instance.InterToneTimeout

instance.InterToneTimeout = value
C#
public TimeSpan InterToneTimeout { get; set; }

Property Value

Type: System..::..TimeSpan

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognitionEngine Events

[image] [image]

DtmfRecognitionEngine Events
DtmfRecognitionEngine Class See Also Send Feedback

The DtmfRecognitionEngine type exposes the following members.

Events

 | Name | Description
Public event | DtmfHypothesized | Raised when DTMF input has been detected and recognized.
Public event | DtmfRecognitionRejected | Raised when DTMF input has been detected, but cannot be recognized from current grammars.
Public event | DtmfRecognized | Raised when DTMF input has been detected and recognized.
Public event | LoadGrammarCompleted | Raised on completion of the asynchronous load of a Grammar object.
Public event | RecognizeCompleted | Raised on completion of an asynchronous recognition.
Top

See Also

Reference

DtmfRecognitionEngine Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfHypothesized Event

[image]

DtmfRecognitionEngine..::..DtmfHypothesized Event
DtmfRecognitionEngine Class See Also Send Feedback

Raised when DTMF input has been detected and recognized.

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

Syntax

Visual Basic (Declaration)
Public Event DtmfHypothesized As EventHandler(Of DtmfHypothesizedEventArgs)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim handler As EventHandler(Of DtmfHypothesizedEventArgs)

AddHandler instance.DtmfHypothesized, handler
C#
public event EventHandler<DtmfHypothesizedEventArgs> DtmfHypothesized

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognitionRejected Event

[image]

DtmfRecognitionEngine..::..DtmfRecognitionRejected Event
DtmfRecognitionEngine Class See Also Send Feedback

Raised when DTMF input has been detected, but cannot be recognized from current grammars.

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

Syntax

Visual Basic (Declaration)
Public Event DtmfRecognitionRejected As EventHandler(Of DtmfRecognitionRejectedEventArgs)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim handler As EventHandler(Of DtmfRecognitionRejectedEventArgs)

AddHandler instance.DtmfRecognitionRejected, handler
C#
public event EventHandler<DtmfRecognitionRejectedEventArgs> DtmfRecognitionRejected

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognized Event

[image]

DtmfRecognitionEngine..::..DtmfRecognized Event
DtmfRecognitionEngine Class See Also Send Feedback

Raised when DTMF input has been detected and recognized.

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

Syntax

Visual Basic (Declaration)
Public Event DtmfRecognized As EventHandler(Of DtmfRecognizedEventArgs)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim handler As EventHandler(Of DtmfRecognizedEventArgs)

AddHandler instance.DtmfRecognized, handler
C#
public event EventHandler<DtmfRecognizedEventArgs> DtmfRecognized

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


LoadGrammarCompleted Event

[image]

DtmfRecognitionEngine..::..LoadGrammarCompleted Event
DtmfRecognitionEngine Class See Also Send Feedback

Raised on completion of the asynchronous load of a Grammar object.

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

Syntax

Visual Basic (Declaration)
Public Event LoadGrammarCompleted As EventHandler(Of LoadGrammarCompletedEventArgs)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim handler As EventHandler(Of LoadGrammarCompletedEventArgs)

AddHandler instance.LoadGrammarCompleted, handler
C#
public event EventHandler<LoadGrammarCompletedEventArgs> LoadGrammarCompleted

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeCompleted Event

[image]

DtmfRecognitionEngine..::..RecognizeCompleted Event
DtmfRecognitionEngine Class See Also Send Feedback

Raised on completion of an asynchronous recognition.

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

Syntax

Visual Basic (Declaration)
Public Event RecognizeCompleted As EventHandler(Of DtmfRecognizeCompletedEventArgs)
Visual Basic (Usage)
Dim instance As DtmfRecognitionEngine
Dim handler As EventHandler(Of DtmfRecognizeCompletedEventArgs)

AddHandler instance.RecognizeCompleted, handler
C#
public event EventHandler<DtmfRecognizeCompletedEventArgs> RecognizeCompleted

See Also

Reference

DtmfRecognitionEngine Class
DtmfRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognitionRejectedEventArgs Class

[image]

DtmfRecognitionRejectedEventArgs Class
Members See Also Send Feedback

Provides data for the DtmfRecognitionRejected event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Recognition..::..RecognitionEventArgs
Microsoft.Speech.Recognition..::..DtmfRecognitionRejectedEventArgs

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class DtmfRecognitionRejectedEventArgs _
    Inherits RecognitionEventArgs
Visual Basic (Usage)
Dim instance As DtmfRecognitionRejectedEventArgs
C#
[SerializableAttribute]
public class DtmfRecognitionRejectedEventArgs : RecognitionEventArgs

Remarks

An instance of DtmfRecognitionRejectedEventArgs is created when the DtmfRecognitionEngine object raises the DtmfRecognitionRejected event. To obtain the information about the tone that caused the event to be raised, access the TerminationTone property in the handler for the event.

DtmfRecognitionRejectedEventArgs derives from RecognitionEventArgs.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

DtmfRecognitionRejectedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognitionRejectedEventArgs Members

[image] [image]

DtmfRecognitionRejectedEventArgs Members
DtmfRecognitionRejectedEventArgs Class Methods Properties See Also Send Feedback

Provides data for the DtmfRecognitionRejected event.

The DtmfRecognitionRejectedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Result | Gets the results of the speech or DTMF recognition operation. (Inherited from RecognitionEventArgs.)
Public property | TerminationTone | Gets the DTMF tone that ended the recognition.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

DtmfRecognitionRejectedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognitionRejectedEventArgs Methods

[image] [image]

DtmfRecognitionRejectedEventArgs Methods
DtmfRecognitionRejectedEventArgs Class See Also Send Feedback

The DtmfRecognitionRejectedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

DtmfRecognitionRejectedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognitionRejectedEventArgs Properties

[image] [image]

DtmfRecognitionRejectedEventArgs Properties
DtmfRecognitionRejectedEventArgs Class See Also Send Feedback

The DtmfRecognitionRejectedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Result | Gets the results of the speech or DTMF recognition operation. (Inherited from RecognitionEventArgs.)
Public property | TerminationTone | Gets the DTMF tone that ended the recognition.
Top

See Also

Reference

DtmfRecognitionRejectedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


TerminationTone Property

[image]

DtmfRecognitionRejectedEventArgs..::..TerminationTone Property
DtmfRecognitionRejectedEventArgs Class See Also Send Feedback

Gets the DTMF tone that ended the recognition.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property TerminationTone As Nullable(Of DtmfTone)
    Get
Visual Basic (Usage)
Dim instance As DtmfRecognitionRejectedEventArgs
Dim value As Nullable(Of DtmfTone)

value = instance.TerminationTone
C#
public Nullable<DtmfTone> TerminationTone { get; }

Property Value

Type: System..::..Nullable <(Of <(<' DtmfTone >)>)>

The tone that caused the DtmfRecognitionRejected event to be raised.

See Also

Reference

DtmfRecognitionRejectedEventArgs Class
DtmfRecognitionRejectedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognizeCompletedEventArgs Class

[image]

DtmfRecognizeCompletedEventArgs Class
Members See Also Send Feedback

Returns information from the RecognizeCompleted event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
System.ComponentModel..::..AsyncCompletedEventArgs
Microsoft.Speech.Recognition..::..DtmfRecognizeCompletedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class DtmfRecognizeCompletedEventArgs _
    Inherits AsyncCompletedEventArgs
Visual Basic (Usage)
Dim instance As DtmfRecognizeCompletedEventArgs
C#
public class DtmfRecognizeCompletedEventArgs : AsyncCompletedEventArgs

Remarks

An instance of DtmfRecognizeCompletedEventArgs is created when the DtmfRecognitionEngine object raises the RecognizeCompleted event. To obtain information related to the RecognizeCompleted event, access the following properties in the handler for the event:

  • InitialSilenceTimeout

  • InterToneTimeout

  • Result

  • TerminationTone

DtmfRecognizeCompletedEventArgs is derived from RecognitionEventArgs.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

DtmfRecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognizeCompletedEventArgs Members

[image] [image]

DtmfRecognizeCompletedEventArgs Members
DtmfRecognizeCompletedEventArgs Class Methods Properties See Also Send Feedback

Returns information from the RecognizeCompleted event.

The DtmfRecognizeCompletedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | InitialSilenceTimeout | Gets whether recognition was terminated because the InitialSilenceTimeout interval expired.
Public property | InterToneTimeout | Gets whether recognition was terminated because the InterToneTimeout interval expired.
Public property | Result | Gets the recognition result.
Public property | TerminationTone | Gets the DTMF tone that ended the recognition.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

DtmfRecognizeCompletedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognizeCompletedEventArgs Methods

[image] [image]

DtmfRecognizeCompletedEventArgs Methods
DtmfRecognizeCompletedEventArgs Class See Also Send Feedback

The DtmfRecognizeCompletedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

DtmfRecognizeCompletedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognizeCompletedEventArgs Properties

[image] [image]

DtmfRecognizeCompletedEventArgs Properties
DtmfRecognizeCompletedEventArgs Class See Also Send Feedback

The DtmfRecognizeCompletedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | InitialSilenceTimeout | Gets whether recognition was terminated because the InitialSilenceTimeout interval expired.
Public property | InterToneTimeout | Gets whether recognition was terminated because the InterToneTimeout interval expired.
Public property | Result | Gets the recognition result.
Public property | TerminationTone | Gets the DTMF tone that ended the recognition.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

See Also

Reference

DtmfRecognizeCompletedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InitialSilenceTimeout Property

[image]

DtmfRecognizeCompletedEventArgs..::..InitialSilenceTimeout Property
DtmfRecognizeCompletedEventArgs Class See Also Send Feedback

Gets whether recognition was terminated because the InitialSilenceTimeout interval expired.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property InitialSilenceTimeout As Boolean
    Get
Visual Basic (Usage)
Dim instance As DtmfRecognizeCompletedEventArgs
Dim value As Boolean

value = instance.InitialSilenceTimeout
C#
public bool InitialSilenceTimeout { get; }

Property Value

Type: System..::..Boolean

true if recognition was terminated because the InitialSilenceTimeout interval expired; otherwise false.

See Also

Reference

DtmfRecognizeCompletedEventArgs Class
DtmfRecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InterToneTimeout Property

[image]

DtmfRecognizeCompletedEventArgs..::..InterToneTimeout Property
DtmfRecognizeCompletedEventArgs Class See Also Send Feedback

Gets whether recognition was terminated because the InterToneTimeout interval expired.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property InterToneTimeout As Boolean
    Get
Visual Basic (Usage)
Dim instance As DtmfRecognizeCompletedEventArgs
Dim value As Boolean

value = instance.InterToneTimeout
C#
public bool InterToneTimeout { get; }

Property Value

Type: System..::..Boolean

true if recognition was terminated because the InterToneTimeout interval expired; otherwise false.

See Also

Reference

DtmfRecognizeCompletedEventArgs Class
DtmfRecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Result Property

[image]

DtmfRecognizeCompletedEventArgs..::..Result Property
DtmfRecognizeCompletedEventArgs Class See Also Send Feedback

Gets the recognition result.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Result As RecognitionResult
    Get
Visual Basic (Usage)
Dim instance As DtmfRecognizeCompletedEventArgs
Dim value As RecognitionResult

value = instance.Result
C#
public RecognitionResult Result { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

The results of the recognition.

Remarks

If recognition timed out, or if the sequence of DTMF tones did not match any of the loaded Grammar objects, Result will be null.

See Also

Reference

DtmfRecognizeCompletedEventArgs Class
DtmfRecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


TerminationTone Property

[image]

DtmfRecognizeCompletedEventArgs..::..TerminationTone Property
DtmfRecognizeCompletedEventArgs Class See Also Send Feedback

Gets the DTMF tone that ended the recognition.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property TerminationTone As Nullable(Of DtmfTone)
    Get
Visual Basic (Usage)
Dim instance As DtmfRecognizeCompletedEventArgs
Dim value As Nullable(Of DtmfTone)

value = instance.TerminationTone
C#
public Nullable<DtmfTone> TerminationTone { get; }

Property Value

Type: System..::..Nullable <(Of <(<' DtmfTone >)>)>

The tone that ended the recognition, or null if no TerminationTones are set.

See Also

Reference

DtmfRecognizeCompletedEventArgs Class
DtmfRecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognizedEventArgs Class

[image]

DtmfRecognizedEventArgs Class
Members See Also Send Feedback

Provides data for the DtmfRecognized event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Recognition..::..RecognitionEventArgs
Microsoft.Speech.Recognition..::..DtmfRecognizedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class DtmfRecognizedEventArgs _
    Inherits RecognitionEventArgs
Visual Basic (Usage)
Dim instance As DtmfRecognizedEventArgs
C#
public class DtmfRecognizedEventArgs : RecognitionEventArgs

Remarks

An instance of DtmfRecognizedEventArgs is created when the DtmfRecognitionEngine object raises the DtmfRecognized event. To obtain the information about the tone that caused the event to be raised, access the TerminationTone property in the handler for the event.

DtmfRecognizedEventArgs is derived from RecognitionEventArgs.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

DtmfRecognizedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognizedEventArgs Members

[image] [image]

DtmfRecognizedEventArgs Members
DtmfRecognizedEventArgs Class Methods Properties See Also Send Feedback

Provides data for the DtmfRecognized event.

The DtmfRecognizedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Result | Gets the results of the speech or DTMF recognition operation. (Inherited from RecognitionEventArgs.)
Public property | TerminationTone | Gets the DTMF tone that terminated the recognition.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

DtmfRecognizedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognizedEventArgs Methods

[image] [image]

DtmfRecognizedEventArgs Methods
DtmfRecognizedEventArgs Class See Also Send Feedback

The DtmfRecognizedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

DtmfRecognizedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfRecognizedEventArgs Properties

[image] [image]

DtmfRecognizedEventArgs Properties
DtmfRecognizedEventArgs Class See Also Send Feedback

The DtmfRecognizedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Result | Gets the results of the speech or DTMF recognition operation. (Inherited from RecognitionEventArgs.)
Public property | TerminationTone | Gets the DTMF tone that terminated the recognition.
Top

See Also

Reference

DtmfRecognizedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


TerminationTone Property

[image]

DtmfRecognizedEventArgs..::..TerminationTone Property
DtmfRecognizedEventArgs Class See Also Send Feedback

Gets the DTMF tone that terminated the recognition.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property TerminationTone As Nullable(Of DtmfTone)
    Get
Visual Basic (Usage)
Dim instance As DtmfRecognizedEventArgs
Dim value As Nullable(Of DtmfTone)

value = instance.TerminationTone
C#
public Nullable<DtmfTone> TerminationTone { get; }

Property Value

Type: System..::..Nullable <(Of <(<' DtmfTone >)>)>

The tone that terminated the recognition.

See Also

Reference

DtmfRecognizedEventArgs Class
DtmfRecognizedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DtmfTone Enumeration

[image]

DtmfTone Enumeration
See Also Send Feedback

Enumerates values of the first 16 DTMF tones.

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

Syntax

Visual Basic (Declaration)
Public Enumeration DtmfTone
Visual Basic (Usage)
Dim instance As DtmfTone
C#
public enum DtmfTone

Members

Member name | Description
Zero | 0
One | 1
Two | 2
Three | 3
Four | 4
Five | 5
Six | 6
Seven | 7
Eight | 8
Nine | 9
Star | 10
Hash | 11
A | 12
B | 13
C | 14
D | 15

See Also

Reference

Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateOptions Enumeration

[image]

EmulateOptions Enumeration
See Also Send Feedback

Specifies the type of recognition operation that is performed by EmulateRecognize()()()() and EmulateRecognizeAsync()()()() methods that take this object as a parameter.

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

Syntax

Visual Basic (Declaration)
Public Enumeration EmulateOptions
Visual Basic (Usage)
Dim instance As EmulateOptions
C#
public enum EmulateOptions

Members

Member name | Description
Emulation | For EmulateRecognize()()()() and EmulateRecognizeAsync()()()() methods that take this object as a parameter, specifies that the method performs emulation.
Simulation | For EmulateRecognize()()()() and EmulateRecognizeAsync()()()() methods that take this object as a parameter, specifies that the method performs simulation.
IdentifyConfusion | For EmulateRecognize()()()() and EmulateRecognizeAsync()()()() methods that take this object as a parameter, specifies that the method performs confusability analysis.

Remarks

Using this object, you can specify three types of recognition operations:

  • Emulation. Uses text instead of audio as input to the speech recognition engine to perform recognition. You can use emulation to determine whether a word is in a grammar and what semantics are returned when the word is recognized.

  • IdentifyConfusion. Identifies phrases in a grammar that may generate false acceptances on recognition because of similarity to other phrases in the grammar.

  • Simulation. Creates an 'idealized' audio representation of the input phrase (based on the speech recognition engine's lexicon and acoustic model), and then performs recognition on the idealized audio. You can use Simulation to find out which pronunciation the speech recognition will use for an input phrase.

See Also

Reference

Microsoft.Speech.Recognition Namespace
EmulateRecognize()()()()
EmulateRecognizeAsync()()()()

Other Resources

Microsoft Grammar Development Tools
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognizeCompletedEventArgs Class

[image]

EmulateRecognizeCompletedEventArgs Class
Members Example See Also Send Feedback

Provides data for the EmulateRecognizeCompleted event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
System.ComponentModel..::..AsyncCompletedEventArgs
Microsoft.Speech.Recognition..::..EmulateRecognizeCompletedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class EmulateRecognizeCompletedEventArgs _
    Inherits AsyncCompletedEventArgs
Visual Basic (Usage)
Dim instance As EmulateRecognizeCompletedEventArgs
C#
public class EmulateRecognizeCompletedEventArgs : AsyncCompletedEventArgs

Remarks

An instance of EmulateRecognizeCompletedEventArgs is created when the SpeechRecognitionEngine object raises the EmulateRecognizeCompleted event. To obtain information about the result of recognition, access the Result property in the handler for the event.

Emulation is a process that provides text, instead of audio, as the input to a speech recognition engine. To bypass the audio inputs for a SpeechRecognitionEngine object during emulation, use the SetInputToNull()()()() method.

If the speech recognition engine encounters an exception during the recognition operation, the Error property is set to the exception and the Result property is set to nullNothingnullptrunita null reference (Nothing in Visual Basic).

EmulateRecognizeCompletedEventArgs derives from AsyncCompletedEventArgs.

Examples

The following example adds an event handler for the EmulateRecognizeCompleted event to a SpeechRecognitionEngine. The handler gets the recognized text from the Result property.

C# Copy image Copy Code
private SpeechRecognitionEngine sre;

// Initialize the speech recognition engine.
private void Initialize()
{
  sre = new SpeechRecognitionEngine();

  // Add a handler for the EmulateRecognizeCompleted event.
  sre.EmulateRecognizeCompleted += new EventHandler<EmulateRecognizeCompletedEventArgs>(sre_EmulateRecognizeCompleted);

  // Add other initialization code here.
}

// Handle the EmulateRecognizeCompleted event.
void sre_EmulateRecognizeCompleted(object sender, EmulateRecognizeCompletedEventArgs e)
{
  if (e.Result == null) return;

  string phrase = e.Result.Text;

  // Add event handler code here.
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

EmulateRecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
Result
EmulateRecognizeCompleted
EmulateRecognize
EmulateRecognizeAsync
SpeechRecognitionEngine
AsyncCompletedEventArgs
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognizeCompletedEventArgs Members

[image] [image]

EmulateRecognizeCompletedEventArgs Members
EmulateRecognizeCompletedEventArgs Class Methods Properties See Also Send Feedback

Provides data for the EmulateRecognizeCompleted event.

The EmulateRecognizeCompletedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Result | Gets the results of emulated recognition.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

EmulateRecognizeCompletedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognizeCompletedEventArgs Methods

[image] [image]

EmulateRecognizeCompletedEventArgs Methods
EmulateRecognizeCompletedEventArgs Class See Also Send Feedback

The EmulateRecognizeCompletedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

EmulateRecognizeCompletedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognizeCompletedEventArgs Properties

[image] [image]

EmulateRecognizeCompletedEventArgs Properties
EmulateRecognizeCompletedEventArgs Class See Also Send Feedback

The EmulateRecognizeCompletedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Result | Gets the results of emulated recognition.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

See Also

Reference

EmulateRecognizeCompletedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Result Property

[image]

EmulateRecognizeCompletedEventArgs..::..Result Property
EmulateRecognizeCompletedEventArgs Class Example See Also Send Feedback

Gets the results of emulated recognition.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Result As RecognitionResult
    Get
Visual Basic (Usage)
Dim instance As EmulateRecognizeCompletedEventArgs
Dim value As RecognitionResult

value = instance.Result
C#
public RecognitionResult Result { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

Detailed information about the results of recognition, or nullNothingnullptrunita null reference (Nothing in Visual Basic) if an error occurred.

Remarks

The RecognitionResult object derives from RecognizedPhrase and contains full information about a phrase returned by a recognition operation. You can obtain a list off all the recognition candidates from the Alternates property.

If recognizer encounters an exception during the recognition operation, the Error property is set to the exception and the Result property is set to nullNothingnullptrunita null reference (Nothing in Visual Basic).

Examples

The example below shows the subscription of an anonymous method to the EmulateRecognizeCompleted event. The method provides a display of state information about the recognized phrase, obtained from the Result property on the instance of EmulateRecognizeCompletedEventArgs passed to the handler.

Copy image Copy Code
_recognizer.EmulateRecognizeCompleted += delegate(object sender, EmulateRecognizeCompletedEventArgs eventArgs) {
    _asyncEmulation = false;
    Utils.DisplayAudioInputFormat(_audioStateLabel, _recognizer);
    Utils.DisplayRecognizerState(_recognizerStateLabel, _recognizer.State);
    Utils.DisplayAudioInputStatus(_audioDeviceStatusLabel, _recognizer.AudioStatus);
    DisplayResult(eventArgs.Result);
};

See Also

Reference

EmulateRecognizeCompletedEventArgs Class
EmulateRecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
EmulateRecognizeCompletedEventArgs
EmulateRecognizeCompleted
EmulateRecognize(array<RecognizedWordUnit>[]()[][], CompareOptions)
EmulateRecognizeAsync
SpeechRecognitionEngine
AsyncCompletedEventArgs
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Class

[image]

Grammar Class
Members Example See Also Send Feedback

A runtime object that references a speech recognition grammar, which an application can use to define the constraints for speech recognition.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..Grammar

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

Syntax

Visual Basic (Declaration)
Public Class Grammar
Visual Basic (Usage)
Dim instance As Grammar
C#
public class Grammar

Remarks

A speech recognition grammar is a set of rules or constraints that define what a speech recognition engine can recognize as meaningful input. For more information about creating and using speech recognition grammars, see Speech Recognition (Microsoft.Speech), Create Grammars Using GrammarBuilder (Microsoft.Speech), Create Grammars Using SrgsGrammar (Microsoft.Speech), and Create Grammars Using SRGS XML (Microsoft.Speech).

After you author a grammar, you must build it into a Grammar object that a SpeechRecognitionEngine instance can load and that your application can use at runtime to manage speech recognition. You can use a Grammar constructor to create a Grammar instance from a GrammarBuilder or a SrgsDocument object, or from a file or a Stream that contains a description of a grammar in a supported format. Supported formats include the following:

  • XML-format files that conform to the W3C Speech Recognition Grammar Specification (SRGS) Version 1.0

  • Grammars that have been compiled to a binary file with a .cfg file extension

Grammar constructors that accept XML-format grammar files in their arguments compile the XML grammars to a binary format to optimize them for loading and consumption by a speech recognition engine. You can reduce the amount of time required to construct a Grammar object from an XML-format grammar by compiling the grammar in advance, using one of the Compile()()()() methods.

An application's speech recognition engine, as managed by a SpeechRecognitionEngine object, can load multiple speech recognition grammars. The application can independently enable or disable individual grammars by setting the Enabled property, and modify recognition behavior through Grammar properties, such as the Priority and Weight properties.

The grammar's SpeechRecognized event is raised when input matches a path through the grammar.

Note Note

It is a best practice to verify the safety of any URI or DLL used to build a Grammar object.

The Microsoft Speech Platform SDK 11 provides security for applications constructing a Grammar instance from a DLL or from a grammar that supports scripting.

Scripts in Grammar objects are always run as if downloaded from a web page in the Internet Zone. The Common Language Runtime (CLR) isolates any DLL loaded to obtain a grammar definition.

Examples

The following example generates a file dialog to open a grammar as a stream, selecting a specific grammar rule, and then loading that grammar into an instance of a recognition engine.

C# Copy image Copy Code
private void _grammarAddButton_Click(object sender, EventArgs eventArgs)
{
  // Create the Open Grammar dialog box.
  OpenFileDialog dialog = new OpenFileDialog();
  dialog.Filter = "SRGS files {*.xml;*.srgs}|*.xml;*.srgs|*.cfg|All files|*.*";
  dialog.Title = "Open Grammar";
  if (dialog.ShowDialog() == DialogResult.OK)
  {
    try
    {
      Uri baseURI = null;
      baseURI = new Uri("http://treyresearch.net/SRGS/");
      Stream stream = dialog.OpenFile();
      Uri uriTarget = new Uri(dialog.FileName);
      Grammar grammar = new Grammar(stream, "SetColorRule", baseURI, null);
      //;
      grammar.Name = String.Format("{0} ({1})",
                   grammar.RuleName, dialog.FileName);
      grammar.Enabled = true;
      _recognizer.LoadGrammar(grammar);

    }
    catch (Exception exp)
    {
      // Catch all exceptions while loading the grammar file.
      MessageBox.Show(String.Format("{0} failed to load.\nError Message:\n{1}",
                    dialog.FileName, exp.Message));
      return;
    }
  }
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

Grammar Members
Microsoft.Speech.Recognition Namespace
Microsoft.Speech.Recognition.SrgsGrammar
SrgsDocument
SrgsRule
GrammarBuilder

Other Resources

Speech Recognition Grammar Specification
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Members

[image] [image]

Grammar Members
Grammar Class Constructors Methods Properties Events See Also Send Feedback

A runtime object that references a speech recognition grammar, which an application can use to define the constraints for speech recognition.

The Grammar type exposes the following members.

Constructors

 | Name | Description
Public method | Grammar(Stream) | Initializes a new instance of the Grammar class from a Stream.
Public method | Grammar(String) | Initializes a new instance of the Grammar class from a file.
Public method | Grammar(GrammarBuilder) | Initializes a new instance of the Grammar class from a GrammarBuilder object.
Public method | Grammar(GrammarInfo) | Creates a new instance of the Grammar class from a GrammarInfo instance.
Public method | Grammar(SrgsDocument) | Initializes a new instance of the Grammar class from an SrgsDocument object.
Public method | Grammar(Stream, String) | Initializes a new instance of the Grammar class from a Stream and specifies a root rule.
Public method | Grammar(String, String) | Initializes a new instance of the Grammar class from a file and specifies a root rule.
Public method | Grammar(SrgsDocument, String) | Initializes a new instance of a Grammar class from an SrgsDocument object and specifies a root rule.
Public method | Grammar(Stream, String, Uri) | Initializes a new instance of the Grammar class from a stream, specifies a root rule, and defines a base Uniform Resource Identifier (URI) to resolve relative rule references.
Public method | Grammar(String, String, Uri) | Initializes a new instance of the Grammar class from a file, specifies a root rule, and defines a base Uniform Resource Identifier (URI) to resolve relative rule references.
Public method | Grammar(SrgsDocument, String, Uri) | Initializes a new instance of a Grammar class from an SrgsDocument object, specifies a root rule, and defines a base Uniform Resource Identifier (URI) to resolve relative rule references.
Top

Properties

 | Name | Description
Public property | Enabled | Gets or sets a value that controls whether a Grammar can be used by a recognition engine to perform recognition.
Public property | Loaded | Gets whether a Grammar has been loaded by a recognition engine.
Public property | Name | Gets or sets the name of a Grammar object.
Public property | Priority | Gets or sets the priority value of a Grammar object.
Public property | RuleName | Gets the identifier of the root rule or entry point rule of a Grammar instance.
Public property | Weight | Gets or sets the weight value of a Grammar object.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Public method | IsPronounceable | Gets whether the SpeechRecognitionEngine can pronounce the word and where the word's pronunciation is defined.
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

Events

 | Name | Description
Public event | SpeechRecognized | Raised when a SpeechRecognitionEngine instance performs recognition using the Grammar object.
Top

See Also

Reference

Grammar Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Constructor

[image] [image]

Grammar Constructor
Grammar Class See Also Send Feedback

Initializes a new instance of the Grammar class.

Overload List

 | Name | Description
Public method | Grammar(Stream) | Initializes a new instance of the Grammar class from a Stream.
Public method | Grammar(String) | Initializes a new instance of the Grammar class from a file.
Public method | Grammar(GrammarBuilder) | Initializes a new instance of the Grammar class from a GrammarBuilder object.
Public method | Grammar(GrammarInfo) | Creates a new instance of the Grammar class from a GrammarInfo instance.
Public method | Grammar(SrgsDocument) | Initializes a new instance of the Grammar class from an SrgsDocument object.
Public method | Grammar(Stream, String) | Initializes a new instance of the Grammar class from a Stream and specifies a root rule.
Public method | Grammar(String, String) | Initializes a new instance of the Grammar class from a file and specifies a root rule.
Public method | Grammar(SrgsDocument, String) | Initializes a new instance of a Grammar class from an SrgsDocument object and specifies a root rule.
Public method | Grammar(Stream, String, Uri) | Initializes a new instance of the Grammar class from a stream, specifies a root rule, and defines a base Uniform Resource Identifier (URI) to resolve relative rule references.
Public method | Grammar(String, String, Uri) | Initializes a new instance of the Grammar class from a file, specifies a root rule, and defines a base Uniform Resource Identifier (URI) to resolve relative rule references.
Public method | Grammar(SrgsDocument, String, Uri) | Initializes a new instance of a Grammar class from an SrgsDocument object, specifies a root rule, and defines a base Uniform Resource Identifier (URI) to resolve relative rule references.
Top

Remarks

You can use a Grammar constructor to create a Grammar instance from a GrammarBuilder or SrgsDocument object, or from a file or a Stream that contains a description of a grammar in a supported format. Supported formats include the following:

  • XML-format files that conform to the W3C Speech Recognition Grammar Specification (SRGS) Version 1.0

  • Grammars that have been compiled to a binary file with a .cfg file extension

Grammar constructors that accept XML-format grammar files in their arguments compile the XML grammars to a binary format to optimize them for loading and consumption by a speech recognition engine. You can reduce the amount of time required to construct a Grammar object from an XML-format grammar by compiling the grammar in advance, using one of the Compile()()()() methods.

A speech recognition grammar can define a root rule. To create a Grammar object that specifies which rule to use as its root rule, use a constructor that accepts the ruleName parameter.

To create a Grammar object that specifies a base URI to resolve relative rule references, use a constructor that takes the baseUri parameter.

Specification of parameters during construction is also provided to support the inclusion of scripts in loaded grammars.

Note Note

It is a best practice to verify the safety of any URI or DLL used to build a Grammar object.

The Microsoft Speech Platform SDK 11 provides security for applications constructing a Grammar instance from a DLL or from a grammar that supports scripting.

Scripts in Grammar objects are always run as if downloaded from a web page in the Internet Zone. The Common Language Runtime (CLR) isolates any DLL loaded to obtain a grammar definition.

See Also

Reference

Grammar Class
Grammar Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Constructor (Stream)

[image]

Grammar Constructor (Stream)
Grammar Class Example See Also Send Feedback

Initializes a new instance of the Grammar class from a Stream.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    stream As Stream _
)
Visual Basic (Usage)
Dim stream As Stream

Dim instance As New Grammar(stream)
C#
public Grammar(
    Stream stream
)

Parameters

stream
Type: System.IO..::..Stream

A stream that describes a speech recognition grammar in a supported format.

Exceptions

Exception | Condition
ArgumentException | Generated for invalid stream values. Generated if the stream is connected to a grammar which has no root rule defined, requires initialization parameters, or has a relative rule reference not resolvable by the default base System.Uri rule for grammars.

Remarks

The stream argument:

  • Can never be nullNothingnullptrunita null reference (Nothing in Visual Basic) and must be readable.

  • In general, the object a stream is connected to must be a grammar that conforms to the W3C Speech Recognition Grammar Specification (SRGS) Version 1.0.

    However:

    • If the input stream is connected to a Visual Studio Resource, the Resource can only contain grammars files in binary format with the .cfg extension.

    • If the input stream is connected to a DLL, that DLL must contain instances of Grammar.

Any object connected to stream must contain a grammar that defines a root rule. To create a Grammar object from a stream and specify a root rule, use the Grammar(Stream, String) or Grammar(Stream, String, Uri) constructor.

As there is no Base URI specified, any rule references must:

  • Use absolute URIs.

  • Target rules within the grammar being loaded.

  • Use any paths defined in the grammar object being loaded. If the stream was created from a file, this typically includes the directory where that file was located.

To create a Grammar object from a stream and specify a base URI to use to resolve relative rule references, use the Grammar(Stream, String, Uri) constructor.

Examples

The following example creates a speech recognition grammar from a local SRGS file (cities.xml) using a file stream. The content of the cities.xml file appears following C# example.

C# Copy image Copy Code
// Load a cities grammar from an I/O stream and
// return the new grammar.
private static Grammar CreateGrammarFromStream()
{
  string fileName = @"c:\temp\cities.xml";
  Grammar citiesGrammar =
    new Grammar(new FileStream(fileName, FileMode.Open));
  citiesGrammar.Name = "Stream Cities Grammar";
  return citiesGrammar;
}
XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8" ?>
<grammar version="1.0" xml:lang="en-US"
         xmlns="http://www.w3.org/2001/06/grammar"
         tag-format="semantics/1.0" root="Main">

  <!-- cities.xml:
    Defines an SRGS grammar for requesting a flight. This grammar includes
    a Cities rule that lists the cities that can be used for departures
    and destinations. -->

  <rule id="Main">
    <item>
      I would like to fly from <ruleref uri="#Cities"/>
      to <ruleref uri="#Cities"/>
    </item>
  </rule>

  <rule id="Cities" scope="public">
    <one-of>
      <item> Seattle </item>
      <item> Los Angeles </item>
      <item> New York </item>
      <item> Miami </item>
    </one-of>
  </rule>
</grammar>

See Also

Reference

Grammar Class
Grammar Members
Grammar Overload
Microsoft.Speech.Recognition Namespace
Microsoft.Speech.Recognition.SrgsGrammar
Grammar

Other Resources

Speech Recognition Grammar Specification Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Constructor (String)

[image]

Grammar Constructor (String)
Grammar Class Example See Also Send Feedback

Initializes a new instance of the Grammar class from a file.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    path As String _
)
Visual Basic (Usage)
Dim path As String

Dim instance As New Grammar(path)
C#
public Grammar(
    string path
)

Parameters

path
Type: System..::..String

The path of the file that describes a speech recognition grammar in a supported format.

Exceptions

Exception | Condition
ArgumentException | Generated for invalid path values. Generated if file does not contain a valid grammar, if the grammar is valid but does not specify a root rule, if the root rule initialization handler requires arguments, or if it has a relative rule reference not resolvable by the default base System.Uri rule for grammars.

Remarks

The path argument:

  • Must not be nullNothingnullptrunita null reference (Nothing in Visual Basic), or an empty string.

  • The file specified by path can be an ordinary file or a DLL.

    • The DLL must contain Grammar instances.

    • All other files must contain a grammar defined by W3C Speech Recognition Grammar Specification (SRGS) Version 1.0.

The grammar contained in the file specified by path must contain a root rule, as the constructor does not allow the specification of a particular rule to load. To create a Grammar object from a string and specify a root rule, use the Grammar(String, String) constructor.

As there is no Base URI specified, any rule references must:

  • Use absolute URIs.

  • Target rules within the grammar being loaded.

  • Use any paths defined in the grammar object being loaded.

To create a Grammar object that specifies a base URI to use to resolve relative rule references, open the file in a file stream and use the Grammar..::..Grammar(Stream, String, Uri) constructor.

Examples

The following example loads a speech recognition grammar from a local SRGS file to build a Grammar object. The content of the cities.xml file appears in the XML example that follows the C# example.

C# Copy image Copy Code
// Load a cities grammar from a local file and
// return the new grammar.
private static Grammar CreateGrammarFromFile()
{
  Grammar citiesGrammar = new Grammar(@"c:\temp\cities.xml");
  citiesGrammar.Name = "SRGS File Cities Grammar";
  return citiesGrammar;
}
XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8" ?>
<grammar version="1.0" xml:lang="en-US"
         xmlns="http://www.w3.org/2001/06/grammar"
         tag-format="semantics/1.0" root="Main">

  <!-- cities.xml:
    Defines an SRGS grammar for requesting a flight. This grammar includes
    a Cities rule that lists the cities that can be used for departures
    and destinations. -->

  <rule id="Main">
    <item>
      I would like to fly from <ruleref uri="#Cities"/>
      to <ruleref uri="#Cities"/>
    </item>
  </rule>

  <rule id="Cities" scope="public">
    <one-of>
      <item> Seattle </item>
      <item> Los Angeles </item>
      <item> New York </item>
      <item> Miami </item>
    </one-of>
  </rule>
</grammar>

See Also

Reference

Grammar Class
Grammar Members
Grammar Overload
Microsoft.Speech.Recognition Namespace
Microsoft.Speech.Recognition.SrgsGrammar
SrgsDocument
SpeechRecognitionEngine
Grammar

Other Resources

Speech Recognition Grammar Specification Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Constructor (GrammarBuilder)

[image]

Grammar Constructor (GrammarBuilder)
Grammar Class Example See Also Send Feedback

Initializes a new instance of the Grammar class from a GrammarBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    builder As GrammarBuilder _
)
Visual Basic (Usage)
Dim builder As GrammarBuilder

Dim instance As New Grammar(builder)
C#
public Grammar(
    GrammarBuilder builder
)

Parameters

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

An instance of GrammarBuilder that contains the constraints for the speech recognition grammar.

Examples

For more information about using the GrammarBuilder class to define a grammar, see Create Grammars Using GrammarBuilder (Microsoft.Speech).

The following example creates a speech recognition grammar using Choices and GrammarBuilder objects. The Grammar(GrammarBuilder) constructor creates a Grammar object from the completed GrammarBuilder object.

C# Copy image Copy Code
// Create a grammar using a GrammarBuilder and return the new grammar.
private static Grammar CreateGrammarBuilderGrammar()
{
  GrammarBuilder builder = new GrammarBuilder();

  Choices cityChoice = new Choices (new string[]
  {"Seattle", "New York", "Miami", "Los Angeles"});

  builder.Append("I would like to fly from");
  builder.Append(cityChoice);
  builder.Append(" to ");
  builder.Append(cityChoice);

  Grammar citiesGrammar = new Grammar(builder);
  citiesGrammar.Name = "GrammarBuilder Cities Grammar";

  return citiesGrammar;
}

See Also

Reference

Grammar Class
Grammar Members
Grammar Overload
Microsoft.Speech.Recognition Namespace
GrammarBuilder
Grammar

Other Resources

Speech Recognition Grammar Specification Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Constructor (GrammarInfo)

[image]

Grammar Constructor (GrammarInfo)
Grammar Class See Also Send Feedback

Creates a new instance of the Grammar class from a GrammarInfo instance.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    grammarInfo As GrammarInfo _
)
Visual Basic (Usage)
Dim grammarInfo As GrammarInfo

Dim instance As New Grammar(grammarInfo)
C#
public Grammar(
    GrammarInfo grammarInfo
)

Parameters

grammarInfo
Type: Microsoft.Speech.Recognition..::..GrammarInfo

The GrammarInfo instance with which to initialize the Grammar.

Exceptions

Exception | Condition
ArgumentNullException | Thrown when grammarInfo is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentNullException | Thrown when the grammar referred to by grammarInfo does not have a root rule.

See Also

Reference

Grammar Class
Grammar Members
Grammar Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Constructor (SrgsDocument)

[image]

Grammar Constructor (SrgsDocument)
Grammar Class Example See Also Send Feedback

Initializes a new instance of the Grammar class from an SrgsDocument object.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    srgsDocument As SrgsDocument _
)
Visual Basic (Usage)
Dim srgsDocument As SrgsDocument

Dim instance As New Grammar(srgsDocument)
C#
public Grammar(
    SrgsDocument srgsDocument
)

Parameters

srgsDocument
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsDocument

The constraints for the speech recognition grammar.

Exceptions

Exception | Condition
ArgumentException | Thrown when one or more values in srgsDocument are invalid. Thrown when the SrgsDocument specified by srgsDocument does not contain a root rule ruleName.

Remarks

The srgsDocument argument

  • Must never be nullNothingnullptrunita null reference (Nothing in Visual Basic).

  • Must contain a root rule.

To create a Grammar object from a SrgsDocument object and specify a root rule, use the Grammar(SrgsDocument, String) or Grammar(SrgsDocument, String, Uri) constructor.

As there is no Base URI specified, any rule references must:

  • Use absolute URIs.

  • Target rules within the grammar being loaded.

  • Use any paths defined in the grammar object being loaded.

To create a Grammar object from an SrgsDocument and specify a base URI to use to resolve relative rule references, use the Grammar(SrgsDocument, String, Uri) constructor.

Examples

The following example creates a speech recognition grammar in an SrgsDocument instance, which is then used to construct a Grammar object.

C# Copy image Copy Code
private static Grammar CreateSrgsDocumentGrammar()
{
  // Create the SrgsDocument.
  SrgsDocument document = new SrgsDocument();

  // Create the Cities rule and add it to the document.
  SrgsRule citiesRule = new SrgsRule("Cities");

  SrgsOneOf cityChoice = new SrgsOneOf();
  cityChoice.Add(new SrgsItem("Seattle"));
  cityChoice.Add(new SrgsItem("Los Angeles"));
  cityChoice.Add(new SrgsItem("New York"));
  cityChoice.Add(new SrgsItem("Miami"));

  citiesRule.Add(cityChoice);
  document.Rules.Add(citiesRule);

  // Create the Main rule and add it to the document.
  SrgsRule mainRule = new SrgsRule("Main");
  mainRule.Scope = SrgsRuleScope.Public;

  SrgsItem item = new SrgsItem("I would like to fly from");
  item.Add(new SrgsRuleRef(citiesRule));
  item.Add(new SrgsText(" to "));
  item.Add(new SrgsRuleRef(citiesRule));

  mainRule.Add(item);
  document.Rules.Add(mainRule);

  // Set the root rule.
  document.Root = mainRule;

  // Create the Grammar object.
  Grammar citiesGrammar = new Grammar(document);
  citiesGrammar.Name = "SrgsDocument Cities Grammar";

  return citiesGrammar;
}

See Also

Reference

Grammar Class
Grammar Members
Grammar Overload
Microsoft.Speech.Recognition Namespace
Microsoft.Speech.Recognition.SrgsGrammar
SrgsDocument
SpeechRecognitionEngine

Other Resources

Speech Recognition Grammar Specification Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Constructor (Stream, String)

[image]

Grammar Constructor (Stream, String)
Grammar Class Example See Also Send Feedback

Initializes a new instance of the Grammar class from a Stream and specifies a root rule.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    stream As Stream, _
    ruleName As String _
)
Visual Basic (Usage)
Dim stream As Stream
Dim ruleName As String

Dim instance As New Grammar(stream, _
    ruleName)
C#
public Grammar(
    Stream stream,
    string ruleName
)

Parameters

stream
Type: System.IO..::..Stream

A stream that describes a speech recognition grammar in a supported format.

ruleName
Type: System..::..String

The identifier of the rule to use as the entry point of the speech recognition grammar, or nullNothingnullptrunita null reference (Nothing in Visual Basic) to use the default root rule of the grammar description.

This parameter may be nullNothingnullptrunita null reference (Nothing in Visual Basic).

Exceptions

Exception | Condition
ArgumentException | Thrown when stream or ruleName have invalid values. Thrown when the stream is connected to a grammar that does not contain the rule ruleName, or requires initialization parameters, or has a relative rule reference not resolvable by the default base System.Uri rule for grammars.

Remarks

The stream argument:

  • Can never be nullNothingnullptrunita null reference (Nothing in Visual Basic) and must be readable.

  • In general, the object connected to a stream must be a grammar file that conforms to the W3C Speech Recognition Grammar Specification (SRGS) Version 1.0.

    However:

    • If the input stream is connected to a Visual Studio Resource, the Resource can only contain grammar files in binary format with the .cfg extension.

    • If the input stream is connected to a DLL, that DLL must contain instances of Grammar.

The ruleName argument:

  • May be nullNothingnullptrunita null reference (Nothing in Visual Basic) or Empty.

  • If ruleName is not nullNothingnullptrunita null reference (Nothing in Visual Basic) and the rule specified is not found in the grammar being loaded, an exception is generated.

  • If ruleName is nullNothingnullptrunita null reference (Nothing in Visual Basic), and the grammar contained in the file specified does not declare a root rule, an exception is generated.

As there is no Base URI specified, any rule references must:

  • Use absolute URIs.

  • Target rules within the grammar being loaded.

  • Use any paths defined in the grammar object being loaded. If the stream was created from a file, this typically includes the directory where that file was located.

    To create a Grammar object from a stream and specify a base URI to use to resolve relative rule references, use the Grammar(Stream, String, Uri) constructor.

Examples

The following example loads a local SRGS file (cities.xml) from a file stream and specifies a rule to use as the root of the grammar. The content of the cities.xml file appears in the XML example that follows the C# example.

C# Copy image Copy Code
// Load a cities grammar from an I/O stream, use a specific
// rule as the root of the grammar, and return the new grammar.
private static Grammar CreateGrammarFromStream2()
{
  FileInfo file = new FileInfo(@"c:\temp\cities.xml");
  Grammar citiesGrammar = new Grammar(file.OpenRead(), "Main");
  citiesGrammar.Name = "Stream Cities Grammar 2";
  return citiesGrammar;
}
XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8" ?>
<grammar version="1.0" xml:lang="en-US"
         xmlns="http://www.w3.org/2001/06/grammar"
         tag-format="semantics/1.0" root="Main">

  <!-- cities.xml:
    Defines an SRGS grammar for requesting a flight. This grammar includes
    a Cities rule that lists the cities that can be used for departures
    and destinations. -->

  <rule id="Main">
    <item>
      I would like to fly from <ruleref uri="#Cities"/>
      to <ruleref uri="#Cities"/>
    </item>
  </rule>

  <rule id="Cities" scope="public">
    <one-of>
      <item> Seattle </item>
      <item> Los Angeles </item>
      <item> New York </item>
      <item> Miami </item>
    </one-of>
  </rule>
</grammar>

See Also

Reference

Grammar Class
Grammar Members
Grammar Overload
Microsoft.Speech.Recognition Namespace
Microsoft.Speech.Recognition.SrgsGrammar
SrgsDocument
SpeechRecognitionEngine
Grammar

Other Resources

Speech Recognition Grammar Specification Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Constructor (String, String)

[image]

Grammar Constructor (String, String)
Grammar Class Example See Also Send Feedback

Initializes a new instance of the Grammar class from a file and specifies a root rule.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    path As String, _
    ruleName As String _
)
Visual Basic (Usage)
Dim path As String
Dim ruleName As String

Dim instance As New Grammar(path, ruleName)
C#
public Grammar(
    string path,
    string ruleName
)

Parameters

path
Type: System..::..String

Path to a file, including DLLs, containing a grammar specification.

ruleName
Type: System..::..String

The identifier of the rule to use as the entry point of the speech recognition grammar, or nullNothingnullptrunita null reference (Nothing in Visual Basic) to use the default root rule of the grammar description.

This parameter may be nullNothingnullptrunita null reference (Nothing in Visual Basic).

Exceptions

Exception | Condition
ArgumentException | Thrown when path or ruleName are invalid. Thrown when the file specified by path does not contain a valid grammar or the rule ruleName, if the root rule initialization handler requires arguments, or if it has a relative rule reference not resolvable by the default base System.Uri rule for grammars.

Remarks

The path argument:

  • Can never be nullNothingnullptrunita null reference (Nothing in Visual Basic), or Empty

  • The file specified by path can be an ordinary file or a DLL.

    • DLL must contain instances of Grammar.

  • All other files must contain a grammar defined by W3C Speech Recognition Grammar Specification (SRGS) Version 1.0.

The ruleName argument:

  • May be nullNothingnullptrunita null reference (Nothing in Visual Basic) or Empty.

  • If ruleName is not nullNothingnullptrunita null reference (Nothing in Visual Basic) and the rule specified is not found in the grammar being loaded, an exception is generated.

  • If ruleName is nullNothingnullptrunita null reference (Nothing in Visual Basic), and the grammar contained in the file specified does not declare a root rule, an exception is generated.

As there is no Base URI specified, any rule references must:

  • Use absolute URIs.

  • Target rules within the grammar being loaded.

  • Use any paths defined in the grammar object being loaded.

Examples

The following example loads a local SRGS file (cities.xml) from a file and specifies a rule to use as the root of the grammar. The content of the cities.xml file appears in the XML example that follows the C# example.

C# Copy image Copy Code
// Load a cities grammar from a local file, use a specific
// rule as the root of the grammar, and return the new grammar.
private static Grammar CreateGrammarFromFile2()
{
  Grammar citiesGrammar = new Grammar(@"c:\temp\cities.xml", "Main");
  citiesGrammar.Name = "SRGS File Cities Grammar 2";
  return citiesGrammar;
}
XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8" ?>
<grammar version="1.0" xml:lang="en-US"
         xmlns="http://www.w3.org/2001/06/grammar"
         tag-format="semantics/1.0" root="Main">

  <!-- cities.xml:
    Defines an SRGS grammar for requesting a flight. This grammar includes
    a Cities rule that lists the cities that can be used for departures
    and destinations. -->

  <rule id="Main">
    <item>
      I would like to fly from <ruleref uri="#Cities"/>
      to <ruleref uri="#Cities"/>
    </item>
  </rule>

  <rule id="Cities" scope="public">
    <one-of>
      <item> Seattle </item>
      <item> Los Angeles </item>
      <item> New York </item>
      <item> Miami </item>
    </one-of>
  </rule>
</grammar>

See Also

Reference

Grammar Class
Grammar Members
Grammar Overload
Microsoft.Speech.Recognition Namespace
Microsoft.Speech.Recognition.SrgsGrammar
SrgsDocument
SpeechRecognitionEngine
Grammar

Other Resources

Speech Recognition Grammar Specification
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Constructor (SrgsDocument, String)

[image]

Grammar Constructor (SrgsDocument, String)
Grammar Class Example See Also Send Feedback

Initializes a new instance of a Grammar class from an SrgsDocument object and specifies a root rule.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    srgsDocument As SrgsDocument, _
    ruleName As String _
)
Visual Basic (Usage)
Dim srgsDocument As SrgsDocument
Dim ruleName As String

Dim instance As New Grammar(srgsDocument, _
    ruleName)
C#
public Grammar(
    SrgsDocument srgsDocument,
    string ruleName
)

Parameters

srgsDocument
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsDocument

The constraints for the speech recognition grammar.

ruleName
Type: System..::..String

The identifier of the rule to use as the entry point of the speech recognition grammar, or nullNothingnullptrunita null reference (Nothing in Visual Basic) to use the default root rule of the SrgsDocument.

This parameter may be nullNothingnullptrunita null reference (Nothing in Visual Basic).

Exceptions

Exception | Condition
ArgumentException | Thrown when srgsDocument or ruleName are invalid. Thrown when the SrgsDocument specified by srgsDocument does not contain the rule ruleName, or when ruleName is nullNothingnullptrunita null reference (Nothing in Visual Basic) and srgsDocument does not have a root rule.

Remarks

The srgsDocument argument must:

  • Never be nullNothingnullptrunita null reference (Nothing in Visual Basic).

  • Contain the rule specified by ruleName, if ruleName is not nullNothingnullptrunita null reference (Nothing in Visual Basic), and a root rule if ruleName is nullNothingnullptrunita null reference (Nothing in Visual Basic).

The ruleName argument:

  • May be nullNothingnullptrunita null reference (Nothing in Visual Basic) or Empty.

  • If ruleName is not nullNothingnullptrunita null reference (Nothing in Visual Basic) and the rule specified is not found in the grammar being loaded, an exception is generated.

  • If ruleName is nullNothingnullptrunita null reference (Nothing in Visual Basic), and the grammar contained in the file specified does not declare a root rule, an exception is generated.

As there is no Base URI specified, any rule references must:

  • Use absolute URIs.

  • Target rules within the grammar being loaded.

  • Use any paths defined in the grammar object being loaded. If the stream was created from a file, this typically includes the directory where that file was located.

    To create a Grammar object from an SrgsDocument and specify a base URI to use to resolve relative rule references, use the Grammar(SrgsDocument, String, Uri) constructor.

Examples

The following example creates a speech recognition grammar in an SrgsDocument instance and specifies a rule to use as the root rule of the grammar. The example constructs a Grammar object from the SrgsDocument instance and loads it into the speech recognition engine.

C# Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;
using Microsoft.Speech.Recognition.SrgsGrammar;
using System.Xml;

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

    // Initialize an in-process speech recognition engine.
    {
      using (SpeechRecognitionEngine recognizer =
         new SpeechRecognitionEngine())
      {

        // Create the SrgsDocument.
        SrgsDocument document = new SrgsDocument();

        // Create the Cities rule and add it to the document.
        SrgsRule citiesRule = new SrgsRule("Cities");
        citiesRule.Scope = SrgsRuleScope.Public;

        SrgsOneOf cityChoice = new SrgsOneOf();
        cityChoice.Add(new SrgsItem("Seattle"));
        cityChoice.Add(new SrgsItem("Los Angeles"));
        cityChoice.Add(new SrgsItem("New York"));
        cityChoice.Add(new SrgsItem("Miami"));

        citiesRule.Add(cityChoice);
        document.Rules.Add(citiesRule);

        // Create the Main rule and add it to the document.
        SrgsRule mainRule = new SrgsRule("Main");
        mainRule.Scope = SrgsRuleScope.Public;

        mainRule.Add(new SrgsItem("I would like to fly from"));
        mainRule.Add(new SrgsRuleRef(citiesRule));
        mainRule.Add(new SrgsItem("to"));
        mainRule.Add(new SrgsRuleRef(citiesRule));

        document.Rules.Add(mainRule);

        // Set the root rule.
        document.Root = mainRule;

        // Create the grammar and specify which rule to use as the root.
        Grammar citiesGrammar = new Grammar(document, mainRule.Id);
        citiesGrammar.Name = "SrgsDocument Cities Grammar 2";

        // Attach event handlers.
        recognizer.LoadGrammarCompleted +=
          new EventHandler<LoadGrammarCompletedEventArgs>(recognizer_LoadGrammarCompleted);
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
        recognizer.SpeechHypothesized +=
          new EventHandler<SpeechHypothesizedEventArgs>(recognizer_SpeechHypothesized);

        // Load the grammar object to the recognizer.
        recognizer.LoadGrammarAsync(citiesGrammar);

        // Set the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

        // Start recognition.
        recognizer.RecognizeAsync();

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

    // Handle the SpeechHypothesized event.
    static void recognizer_SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
    {
      Console.WriteLine("Speech hypothesized: " + e.Result.Text);
    }

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

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

See Also

Reference

Grammar Class
Grammar Members
Grammar Overload
Microsoft.Speech.Recognition Namespace
Microsoft.Speech.Recognition.SrgsGrammar
SrgsDocument
SpeechRecognitionEngine
Grammar

Other Resources

Speech Recognition Grammar Specification Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Constructor (Stream, String, Uri)

[image]

Grammar Constructor (Stream, String, Uri)
Grammar Class Example See Also Send Feedback

Initializes a new instance of the Grammar class from a stream, specifies a root rule, and defines a base Uniform Resource Identifier (URI) to resolve relative rule references.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    stream As Stream, _
    ruleName As String, _
    baseUri As Uri _
)
Visual Basic (Usage)
Dim stream As Stream
Dim ruleName As String
Dim baseUri As Uri

Dim instance As New Grammar(stream, _
    ruleName, baseUri)
C#
public Grammar(
    Stream stream,
    string ruleName,
    Uri baseUri
)

Parameters

stream
Type: System.IO..::..Stream

A stream that describes a speech recognition grammar in a supported format.

ruleName
Type: System..::..String

The identifier of the rule to use as the entry point of the speech recognition grammar, or nullNothingnullptrunita null reference (Nothing in Visual Basic) to use the default root rule of the grammar description.

baseUri
Type: System..::..Uri

The base URI to use to resolve any relative rule reference in the grammar description, or nullNothingnullptrunita null reference (Nothing in Visual Basic).

Exceptions

Exception | Condition
ArgumentException | Thrown when stream, ruleName, or baseUri have invalid values. Thrown when the stream is connected to a grammar that does not contain the rule ruleName, or has a relative rule reference not resolvable using the baseUri.

Remarks

The stream argument:

  • Can never be nullNothingnullptrunita null reference (Nothing in Visual Basic) and must be readable.

  • In general, the object a stream is connected to must be a grammar file that conforms to the W3C Speech Recognition Grammar Specification (SRGS) Version 1.0.

    However:

    • If the input stream is connected to a Visual Studio Resource, the Resource can only contain grammar files in binary format with the .cfg extension.

    • If the input stream is connected to a DLL, that DLL must contain instances of Grammar.

The ruleName argument:

  • May be nullNothingnullptrunita null reference (Nothing in Visual Basic) or Empty.

  • If ruleName is not nullNothingnullptrunita null reference (Nothing in Visual Basic) and the rule specified is not found in the grammar being loaded, an exception is generated.

  • If ruleName is nullNothingnullptrunita null reference (Nothing in Visual Basic), and the grammar contained in the file specified does not declare a root rule, an exception is generated.

The baseUri argument:

  • The value of baseUri should be an absolute URI, and can be a path or a file.

  • If the value of baseUri is a path, be sure to append a trailing slash.

  • The URI provided by baseUri is not validated when the Grammar object is constructed.

    Instead, if the URI is invalid or any relative references are inaccessible, the SpeechRecognitionEngine generates and exception when it loads the grammar.

    The recognition engine performs the following checks on Grammar objects it is loading:

    • Resolves all references with absolute URIs.

    • Checks the XML of Grammar being loaded for correct syntax.

    • Resolves references with the value of baseUri if it is non-null.

Examples

The following example loads a local SRGS file (shuttle.xml) from a file stream. The file contains a relative rule reference to a rule in the cities.xml file, and specifies a base URI to use to resolve the rule reference. The content of the shuttle.xml and cities.xml files appears in the XML examples that follow the C# example.

C# Copy image Copy Code
private static Grammar CreateGrammarFromStream3()
{
  FileInfo file = new FileInfo(@".\shuttle.xml");
  Uri baseUri = new Uri(@"file://c:\temp\");
  Grammar citiesGrammar = new Grammar(file.OpenRead(), null, baseUri);
  citiesGrammar.Name = "Stream Cities Grammar 3";
  return citiesGrammar;
}
XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8" ?>
<grammar version="1.0" xml:lang="en-US"
         xmlns="http://www.w3.org/2001/06/grammar"
         tag-format="semantics/1.0" root="Main">

  <!-- shuttle.xml:
    Defines an SRGS grammar for asking about a shuttle service. This grammar
    references a Cities rule that is defined in the cities.xml grammar. -->

  <rule id="Main">
    <item>
      Can I get a shuttle in
      <ruleref uri="cities.xml#Cities"/>
    </item>
  </rule>
</grammar>

See Also

Reference

Grammar Class
Grammar Members
Grammar Overload
Microsoft.Speech.Recognition Namespace
Microsoft.Speech.Recognition.SrgsGrammar
SpeechRecognitionEngine
Grammar

Other Resources

Speech Recognition Grammar Specification Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Constructor (String, String, Uri)

[image]

Grammar Constructor (String, String, Uri)
Grammar Class See Also Send Feedback

Initializes a new instance of the Grammar class from a file, specifies a root rule, and defines a base Uniform Resource Identifier (URI) to resolve relative rule references.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    path As String, _
    ruleName As String, _
    baseUri As Uri _
)
Visual Basic (Usage)
Dim path As String
Dim ruleName As String
Dim baseUri As Uri

Dim instance As New Grammar(path, ruleName, _
    baseUri)
C#
public Grammar(
    string path,
    string ruleName,
    Uri baseUri
)

Parameters

path
Type: System..::..String

The path to the file that contains the grammar specification.

ruleName
Type: System..::..String

The identifier of the rule to use as the entry point of the speech recognition grammar, or nullNothingnullptrunita null reference (Nothing in Visual Basic) to use the default root rule of the grammar description.

baseUri
Type: System..::..Uri

The base URI to use to resolve any relative rule reference in the grammar description, or nullNothingnullptrunita null reference (Nothing in Visual Basic).

Exceptions

Exception | Condition
ArgumentException | Thrown when path or ruleName are invalid. Thrown when the file specified by path does not contain a valid grammar or the rule ruleName, if the root rule initialization handler requires arguments, or if it has a relative rule reference not resolvable by the default base Uri rule for grammars.

Remarks

The path argument:

  • Can never be nullNothingnullptrunita null reference (Nothing in Visual Basic), or Empty

  • The file specified by path can be an ordinary file or a DLL.

    • DLL must contain instances of Grammar.

  • All other files must contain a grammar defined by W3C Speech Recognition Grammar Specification (SRGS) Version 1.0.

The ruleName argument:

  • May be nullNothingnullptrunita null reference (Nothing in Visual Basic) or Empty.

  • If ruleName is not nullNothingnullptrunita null reference (Nothing in Visual Basic) and the rule specified is not found in the grammar being loaded, an exception is generated.

  • If ruleName is nullNothingnullptrunita null reference (Nothing in Visual Basic), and the grammar contained in the file specified does not declare a root rule, an exception is generated.

The baseUri argument:

  • The value of baseUri should be an absolute URI, and can be a path or a file.

  • If the value of baseUri is a path, be sure to append a trailing slash.

  • The URI provided by baseUri is not validated when the Grammar object is constructed.

    Instead, if the URI is invalid or any relative references are inaccessible, the SpeechRecognitionEngine generates and exception when it loads the grammar.

    The recognition engine performs the following checks on Grammar objects it is loading:

    • Resolves all references with absolute URIs.

    • Checks the XML of Grammar being loaded for correct syntax.

    • Resolves references with the value of baseUri if it is non-null.

See Also

Reference

Grammar Class
Grammar Members
Grammar Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Constructor (SrgsDocument, String, Uri)

[image]

Grammar Constructor (SrgsDocument, String, Uri)
Grammar Class Example See Also Send Feedback

Initializes a new instance of a Grammar class from an SrgsDocument object, specifies a root rule, and defines a base Uniform Resource Identifier (URI) to resolve relative rule references.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    srgsDocument As SrgsDocument, _
    ruleName As String, _
    baseUri As Uri _
)
Visual Basic (Usage)
Dim srgsDocument As SrgsDocument
Dim ruleName As String
Dim baseUri As Uri

Dim instance As New Grammar(srgsDocument, _
    ruleName, baseUri)
C#
public Grammar(
    SrgsDocument srgsDocument,
    string ruleName,
    Uri baseUri
)

Parameters

srgsDocument
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsDocument

The constraints for the speech recognition grammar.

ruleName
Type: System..::..String

The identifier of the rule to use as the entry point of the speech recognition grammar, or nullNothingnullptrunita null reference (Nothing in Visual Basic) to use the default root rule of the SrgsDocument.

This parameter may be nullNothingnullptrunita null reference (Nothing in Visual Basic).

baseUri
Type: System..::..Uri

[System.Uri] object defining base path that any relative rule references, for example to other grammars, within the grammar are resolved against.

This parameter may be nullNothingnullptrunita null reference (Nothing in Visual Basic).

Exceptions

Exception | Condition
ArgumentException | Generated for invalid srgsDocuments,ruleName, or baseUri values. Generated if the SrgsDocument specified by srgsDocument does not contain the rule ruleName, or has a relative rule reference not resolvable by the default base System.Uri rule for grammars or the Uri supplied by baseUri .

Remarks

The srgsDocument argument

  • Must never be nullNothingnullptrunita null reference (Nothing in Visual Basic).

  • Must contain the rule specified by ruleName, if ruleName is not nullNothingnullptrunita null reference (Nothing in Visual Basic), and a root rule if ruleName is nullNothingnullptrunita null reference (Nothing in Visual Basic).

The ruleName argument:

  • May be nullNothingnullptrunita null reference (Nothing in Visual Basic) or Empty.

  • If ruleName is not nullNothingnullptrunita null reference (Nothing in Visual Basic) and the rule specified is not found in the grammar being loaded, an exception is generated.

  • If ruleName is nullNothingnullptrunita null reference (Nothing in Visual Basic), and the grammar contained in the file specified does not declare a root rule, an exception is generated.

The baseUri argument:

  • The value of baseUri should be an absolute URI, and can be a path or a file.

  • If the value of baseUri is a path, be sure to append a trailing slash.

  • The URI provided by baseUri is not validated when the Grammar object is constructed.

    Instead, if the URI is invalid or any relative references are inaccessible, the SpeechRecognitionEngine generates and exception when it loads the grammar.

    The recognition engine performs the following checks on Grammar objects it is loading:

    • Resolves all references with absolute URIs.

    • Checks the XML of Grammar being loaded for correct syntax.

    • Resolves references used to create the instance of srgsDocument from which the Grammar was created. If the srgsDocument has been created from a file, this typically includes the directory where that file was located.

    • Resolves references with the value of baseUri if it is non-null.

Examples

The following example creates a speech recognition grammar in an SrgsDocument that contains a relative rule reference to the cities.xml file, and specifies a URI to use to resolve the rule reference. The content of the cities.xml file appears in the XML example that follows the C# example.

C# Copy image Copy Code
private static Grammar CreateSrgsDocumentGrammar3()
{
  // Create the SrgsDocument.
  SrgsDocument document = new SrgsDocument();

  // Create the Main rule and add it to the document.
  SrgsRule mainRule = new SrgsRule("Main");
  mainRule.Scope = SrgsRuleScope.Public;

  SrgsItem item = new SrgsItem(" Can I get a shuttle in ");

  // Create a relative URI for the cities rule.
  Uri ruleUri = new Uri("cities.xml#Cities", UriKind.Relative);

  item.Add(new SrgsRuleRef(ruleUri));

  mainRule.Add(item);
  document.Rules.Add(mainRule);

  // Set the root rule.
  document.Root = mainRule;

  // Create the grammar.
  Uri baseUri = new Uri(@"file://c:\temp\");
  Grammar citiesGrammar = new Grammar(document, null, baseUri);
  citiesGrammar.Name = "SrgsDocument Cities Grammar 3";

  return citiesGrammar;
}
XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8" ?>
<grammar version="1.0" xml:lang="en-US"
         xmlns="http://www.w3.org/2001/06/grammar"
         tag-format="semantics/1.0" root="Main">

  <!-- cities.xml:
    Defines an SRGS grammar for requesting a flight. This grammar includes
    a Cities rule that lists the cities that can be used for departures
    and destinations. -->

  <rule id="Main">
    <item>
      I would like to fly from <ruleref uri="#Cities"/>
      to <ruleref uri="#Cities"/>
    </item>
  </rule>

  <rule id="Cities" scope="public">
    <one-of>
      <item> Seattle </item>
      <item> Los Angeles </item>
      <item> New York </item>
      <item> Miami </item>
    </one-of>
  </rule>
</grammar>

See Also

Reference

Grammar Class
Grammar Members
Grammar Overload
Microsoft.Speech.Recognition Namespace
Microsoft.Speech.Recognition.SrgsGrammar
SrgsDocument
SpeechRecognitionEngine
#ctor(SrgsDocument)

Other Resources

Speech Recognition Grammar Specification Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Methods

[image] [image]

Grammar Methods
Grammar Class See Also Send Feedback

The Grammar type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Public method | IsPronounceable | Gets whether the SpeechRecognitionEngine can pronounce the word and where the word's pronunciation is defined.
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

Grammar Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


IsPronounceable Method

[image]

Grammar..::..IsPronounceable Method
Grammar Class See Also Send Feedback

Gets whether the SpeechRecognitionEngine can pronounce the word and where the word's pronunciation is defined.

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

Syntax

Visual Basic (Declaration)
Public Function IsPronounceable ( _
    word As String _
) As Pronounceable
Visual Basic (Usage)
Dim instance As Grammar
Dim word As String
Dim returnValue As Pronounceable

returnValue = instance.IsPronounceable(word)
C#
public Pronounceable IsPronounceable(
    string word
)

Parameters

word
Type: System..::..String

The word to check.

Return Value

Type: Microsoft.Speech.Recognition..::..Pronounceable

A value that indicates whether the word is pronounceable and where the pronunciation is defined.

Exceptions

Exception | Condition
InvalidOperationException | Thrown when this Grammar is not loaded in a speech recognizer.

Remarks

The speech recognizer in which the Grammar is loaded determines whether the word is pronounceable. This check is not case-sensitive. A word may be pronounceable even though its pronunciation is not defined in a lexicon or in the SpeechRecognitionEngine's dictionary. The SpeechRecognitionEngine can create pronunciations for uncommon words.

See Also

Reference

Grammar Class
Grammar Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Properties

[image] [image]

Grammar Properties
Grammar Class See Also Send Feedback

The Grammar type exposes the following members.

Properties

 | Name | Description
Public property | Enabled | Gets or sets a value that controls whether a Grammar can be used by a recognition engine to perform recognition.
Public property | Loaded | Gets whether a Grammar has been loaded by a recognition engine.
Public property | Name | Gets or sets the name of a Grammar object.
Public property | Priority | Gets or sets the priority value of a Grammar object.
Public property | RuleName | Gets the identifier of the root rule or entry point rule of a Grammar instance.
Public property | Weight | Gets or sets the weight value of a Grammar object.
Top

See Also

Reference

Grammar Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Enabled Property

[image]

Grammar..::..Enabled Property
Grammar Class Example See Also Send Feedback

Gets or sets a value that controls whether a Grammar can be used by a recognition engine to perform recognition.

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

Syntax

Visual Basic (Declaration)
Public Property Enabled As Boolean
    Get
    Set
Visual Basic (Usage)
Dim instance As Grammar
Dim value As Boolean

value = instance.Enabled

instance.Enabled = value
C#
public bool Enabled { get; set; }

Property Value

Type: System..::..Boolean

The Enabled property returns true if a speech recognizer can perform recognition using the speech recognition grammar; otherwise the property returns false. The default is true.

Remarks

An instance of Grammar may be enabled or disabled independently of being loaded by a SpeechRecognitionEngine object.

Examples

The following example shows a check box handler for a TreeView. When the box is checked, the grammar is enabled.

C# Copy image Copy Code
private void _grammarTreeView_AfterCheck(object sender, TreeViewEventArgs eventArgs)
{
  if (eventArgs.Action != TreeViewAction.Unknown)
  { // Avoid recursion due to handlers
    if (eventArgs.Node.Parent == null)
    {
      Grammar grammar = ((Grammar)eventArgs.Node.Tag);
      grammar.Enabled = eventArgs.Node.Checked;
      PropagateCheckStatus(eventArgs.Node);
    }
    else
    {
      PropagateCheckStatus(eventArgs.Node.Parent);
    }
  }
}

See Also

Reference

Grammar Class
Grammar Members
Microsoft.Speech.Recognition Namespace
Grammar
SpeechRecognitionEngine

Other Resources

Speech Recognition Grammar Specification Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Loaded Property

[image]

Grammar..::..Loaded Property
Grammar Class Example See Also Send Feedback

Gets whether a Grammar has been loaded by a recognition engine.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Loaded As Boolean
    Get
Visual Basic (Usage)
Dim instance As Grammar
Dim value As Boolean

value = instance.Loaded
C#
public bool Loaded { get; }

Property Value

Type: System..::..Boolean

The Loaded property returns true if the referenced speech recognition grammar is currently loaded in a recognition engine; otherwise the property returns false. The default is false.

Remarks

Once a Grammar has been loaded, the values of Weight, and Priority cannot be changed.

Examples

In the example below, the application checks to see if the Grammar is loaded before changing the value for Priority.

C# Copy image Copy Code
if (!(_grammar.Loaded))
{
  Grammar.Priority=5;
}

See Also

Reference

Grammar Class
Grammar Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Name Property

[image]

Grammar..::..Name Property
Grammar Class Example See Also Send Feedback

Gets or sets the name of a Grammar object.

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

Syntax

Visual Basic (Declaration)
Public Property Name As String
    Get
    Set
Visual Basic (Usage)
Dim instance As Grammar
Dim value As String

value = instance.Name

instance.Name = value
C#
public string Name { get; set; }

Property Value

Type: System..::..String

Returns user friendly-name of an instance of Grammar. If it is not set, returns nullNothingnullptrunita null reference (Nothing in Visual Basic).

Remarks

Thoughtful use of grammar names can make code maintenance easier and user interfaces more robust.

Examples

The example below shows test cases for functionality based on SubsetMatchingMode. Each Name identifies the functionality being tested.

C# Copy image Copy Code
private Grammar CreateExact(params int[] info)
{
  GrammarBuilder gb = new GrammarBuilder("A First Word");
  gb.Append("A Second Word");
  gb.Append("A Third Word");

  Utils.WriteGrammarBuilderToFile(gb, "Exact.xml");
  Grammar grammar = new Grammar(gb);
  grammar.Name = "Exact";
  return grammar;
}

private Grammar CreateOrderedSubset(params int[] info)
{
  GrammarBuilder gb
    = new GrammarBuilder("A First Word",
                SubsetMatchingMode.OrderedSubset);
  gb.Append("A Second Word",
         SubsetMatchingMode.OrderedSubset);
  gb.Append("A Third Word",
         SubsetMatchingMode.OrderedSubset);
  Utils.WriteGrammarBuilderToFile(gb, "OrderedSubset.xml");
  Grammar grammar = new Grammar(gb);
  grammar.Name = "OrderedSubset";
  return grammar;
}

private Grammar CreateOrderedSubsetContentRequired(params int[] info)
{
  GrammarBuilder gb
    = new GrammarBuilder("A First Word",
                .SubsetMatchingMode.OrderedSubsetContentRequired);

  gb.Append("A Second Word",
         SubsetMatchingMode.OrderedSubsetContentRequired);
  gb.Append("A Third Word",
         SubsetMatchingMode.OrderedSubsetContentRequired);

  Utils.WriteGrammarBuilderToFile(gb, "OrderedSubsetContentRequired.xml");
  Grammar grammar = new Grammar(gb);
  grammar.Name = "OrderedSubsetContentRequired";
  return grammar;
}

private Grammar CreateSubsequence(params int[] info)
{
  GrammarBuilder gb
    = new GrammarBuilder("A First Word",
                .SubsetMatchingMode.Subsequence);
  gb.Append("A Second Word",
         SubsetMatchingMode.Subsequence);
  gb.Append("A Third Word",
         SubsetMatchingMode.Subsequence);
  Utils.WriteGrammarBuilderToFile(gb, "Subsequence.xml");
  Grammar grammar = new Grammar(gb);
  grammar.Name = "Subsequence";
  return grammar;
}

private Grammar CreateSubsequenceContentRequired(params int[] info)
{
  GrammarBuilder gb
    = new GrammarBuilder("A First Word",
                SubsetMatchingMode.SubsequenceContentRequired);
  gb.Append("A Second Word",
         SubsetMatchingMode.SubsequenceContentRequired);
  gb.Append("A Third Word",
         SubsetMatchingMode.SubsequenceContentRequired);

  Utils.WriteGrammarBuilderToFile(gb, "SubsequenceContentRequired.xml");
  Grammar grammar = new Grammar(gb);
  grammar.Name = "SubsequenceContentRequired";
  return grammar;
}

See Also

Reference

Grammar Class
Grammar Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Priority Property

[image]

Grammar..::..Priority Property
Grammar Class Example See Also Send Feedback

Gets or sets the priority value of a Grammar object.

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

Syntax

Visual Basic (Declaration)
Public Property Priority As Integer
    Get
    Set
Visual Basic (Usage)
Dim instance As Grammar
Dim value As Integer

value = instance.Priority

instance.Priority = value
C#
public int Priority { get; set; }

Property Value

Type: System..::..Int32

The priority of the referenced speech recognition grammar. The range is from -128 and 127, inclusive. The default is 0.

Remarks

The Priority property is used to select a grammar when more than one grammar will produce an identical recognition result. If a speech recognizer has more than one speech recognition grammar loaded and enabled that match the input, and the match is the best result from the recognizer, then the recognizer uses the grammar that has the highest Priority. If the grammars that produce the identical recognition result also have the same Priority value, then the grammar that the recognizer uses is undefined.

Examples

The following example creates two Grammar objects, one for digits and one for fractions. The Grammar objects are assigned names and relative weights and priorities, and loaded by a speech recognizer. The CreateDigitsGrammar, CreateFractionsGrammar, and recognizer_SpeechRecognized methods are not shown here.

Copy image Copy Code
// Create a Grammar for recognizing numeric digits.
Grammar digitsGrammar = CreateDigitsGrammar();
digitsGrammar.Name = "Digits Grammar";
digitsGrammar.Priority = 2;
digitsGrammar.Weight = 0.6f;

// Create a Grammar for recognizing fractions.
Grammar fractionsGrammar = CreateFractionsGrammar();
fractionsGrammar.Name = "Fractions Grammar";
fractionsGrammar.Priority = 1;
fractionsGrammar.Weight = 1f;

// Create a speech recognizer.
SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();

recognizer.SpeechRecognized +=
  new EventHandler<SpeechRecognizedEventArgs>(
    recognizer_SpeechRecognized);

// Load the digits and fractions Grammar objects.
recognizer.LoadGrammar(digitsGrammar);
recognizer.LoadGrammar(fractionsGrammar);

// Start recognition.
recognizer.SetInputToDefaultAudioDevice();
recognizer.RecognizeAsync(RecognizeMode.Multiple);

See Also

Reference

Grammar Class
Grammar Members
Microsoft.Speech.Recognition Namespace
Weight

Other Resources

Speech Recognition Grammar Specification Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RuleName Property

[image]

Grammar..::..RuleName Property
Grammar Class Example See Also Send Feedback

Gets the identifier of the root rule or entry point rule of a Grammar instance.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property RuleName As String
    Get
Visual Basic (Usage)
Dim instance As Grammar
Dim value As String

value = instance.RuleName
C#
public string RuleName { get; }

Property Value

Type: System..::..String

The identifier of the root rule or entry point rule of a Grammar instance.

Remarks

To construct a Grammar object and set the name for its root rule, use one of the Grammar constructors that takes the ruleName parameter.

If the root rule of a Grammar has no name, the method returns nullNothingnullptrunita null reference (Nothing in Visual Basic).

The root rules of Grammar instances constructed from GrammarBuilder objects typically have no name, so RuleName returns nullNothingnullptrunita null reference (Nothing in Visual Basic).

Examples

The following example writes information about a Grammar object to the console.

Copy image Copy Code
private static void DumpGrammarStatus(Grammar item)
{
  Console.WriteLine("Grammar name is {0}:", item.Name);
  Console.WriteLine("  The Grammar {0} loaded.",
    item.Loaded ? "is" : "is not");
  Console.WriteLine("  The Grammar {0} enabled.",
    item.Enabled ? "is" : "is not");
  if (item.RuleName != null)
  {
    Console.WriteLine("  The root rule is {0}.", item.RuleName);
  }
  else
  {
    Console.WriteLine("  The Grammar does not specify a root rule.");
  }
}

See Also

Reference

Grammar Class
Grammar Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Weight Property

[image]

Grammar..::..Weight Property
Grammar Class Example See Also Send Feedback

Gets or sets the weight value of a Grammar object.

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

Syntax

Visual Basic (Declaration)
Public Property Weight As Single
    Get
    Set
Visual Basic (Usage)
Dim instance As Grammar
Dim value As Single

value = instance.Weight

instance.Weight = value
C#
public float Weight { get; set; }

Property Value

Type: System..::..Single

Returns a floating point value indicating the relative weight a recognition engine (SpeechRecognitionEngine) instance should assign to this grammar when processing audio input.

Remarks

Because of the complexity of a recognition engine's use of Weight, its effect on a particular grammar's performance is not as directly predictable as that of Priority.

Speech recognition is a weighted system. It evaluates all possible recognition paths based on a combination of the weight of the grammar, the weights defined for alternatives within the grammar, and the probabilities defined by speech models. The speech recognition engine uses the combination of these weights and probabilities to rank potential alternative recognitions. Grammars with higher weights will contribute more to the ranking of recognition alternatives than grammars with lower weights.

The effect of the Weight property on a speech recognizer is dependent on the implementation of the recognizer. Although the Weight property can be used to tune the accuracy of speech recognition for an application, it should be used only after controlled diagnostic study of a particular recognition environment and with full information about the recognition engine under use.

Examples

The following example creates two Grammar objects, one for digits and one for fractions. The Grammar objects are assigned names and relative weights and priorities, and loaded by a speech recognizer. The CreateDigitsGrammar, CreateFractionsGrammar, and recognizer_SpeechRecognized methods are not shown here.

Copy image Copy Code
// Create a Grammar for recognizing numeric digits.
Grammar digitsGrammar = CreateDigitsGrammar();
digitsGrammar.Name = "Digits Grammar";
digitsGrammar.Priority = 2;
digitsGrammar.Weight = 0.6f;

// Create a Grammar for recognizing fractions.
Grammar fractionsGrammar = CreateFractionsGrammar();
fractionsGrammar.Name = "Fractions Grammar";
fractionsGrammar.Priority = 1;
fractionsGrammar.Weight = 1f;

// Create a speech recognizer.
SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();

recognizer.SpeechRecognized +=
  new EventHandler<SpeechRecognizedEventArgs>(
    recognizer_SpeechRecognized);

// Load the digits and fractions Grammar objects.
recognizer.LoadGrammar(digitsGrammar);
recognizer.LoadGrammar(fractionsGrammar);

// Start recognition.
recognizer.SetInputToDefaultAudioDevice();
recognizer.RecognizeAsync(RecognizeMode.Multiple);

See Also

Reference

Grammar Class
Grammar Members
Microsoft.Speech.Recognition Namespace
Priority

Other Resources

Speech Recognition Grammar Specification Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Events

[image] [image]

Grammar Events
Grammar Class See Also Send Feedback

The Grammar type exposes the following members.

Events

 | Name | Description
Public event | SpeechRecognized | Raised when a SpeechRecognitionEngine instance performs recognition using the Grammar object.
Top

See Also

Reference

Grammar Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognized Event

[image]

Grammar..::..SpeechRecognized Event
Grammar Class Example See Also Send Feedback

Raised when a SpeechRecognitionEngine instance performs recognition using the Grammar object.

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

Syntax

Visual Basic (Declaration)
Public Event SpeechRecognized As EventHandler(Of SpeechRecognizedEventArgs)
Visual Basic (Usage)
Dim instance As Grammar
Dim handler As EventHandler(Of SpeechRecognizedEventArgs)

AddHandler instance.SpeechRecognized, handler
C#
public event EventHandler<SpeechRecognizedEventArgs> SpeechRecognized

Remarks

The SpeechRecognitionEngine object also raises a SpeechRecognized event when it recognizes input. The Grammar object's SpeechRecognized event is raised prior to the SpeechRecognitionEngine's SpeechRecognized event . For more information, see the RecognizeCompleted events.

Any tasks specific to a particular grammar should always be handled by handlers for the Grammar object's SpeechRecognized event.

Examples

The following example shows the use of an event handler for the Grammar object's SpeechRecognized event. It outputs the recognition results to the console.

C# Copy image Copy Code
public partial class Form1 : Form
{
  SpeechRecognitionEngine sre;

  public Form1()
  {
  InitializeComponent();

  // Create an in-process speech recognizer.
  sre = new SpeechRecognitionEngine();

  // Configure input to the speech recognizer.
  sre.SetInputToDefaultAudioDevice();

  // Create a simple grammar and load it.
  Grammar testGrammar = new Grammar(new GrammarBuilder("testing"));
  sre.LoadGrammarAsync(testGrammar);

  // Add a handler for the grammar's speech recognized event.
  testGrammar.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(testGrammar_SpeechRecognized);

  // Start asynchronous speech recognition.
  sre.RecognizeAsync();
  }

  // Handle the grammar's SpeechRecognized event, output the recognized text.
  void testGrammar_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
  {
    Console.WriteLine("Recognized text: " + e.Result.Text);
  }
}

See Also

Reference

Grammar Class
Grammar Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Class

[image]

GrammarBuilder Class
Members Example See Also Send Feedback

Provides a mechanism for programmatically building the constraints for a speech recognition grammar.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..GrammarBuilder

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

Syntax

Visual Basic (Declaration)
Public Class GrammarBuilder
Visual Basic (Usage)
Dim instance As GrammarBuilder
C#
public class GrammarBuilder

Remarks

Speech recognition grammars are commonly authored in the XML format defined by the Speech Recognition Grammar Specification (SRGS) Version 1.0. If you are familiar with SRGS but want to generate the grammars programmatically, you can use the Microsoft.Speech.Recognition.SrgsGrammar namespace, whose members correspond closely to the elements and attributes defined by SRGS. If you are unfamiliar with SRGS, or you want a lightweight, programmatic approach to authoring grammars with which you can efficiently accomplish many common scenarios; you can use the GrammarBuilder and Choices classes.

Use GrammarBuilder objects to build a hierarchical tree composed of Choices objects that contain alternate phrases, interspersed with preamble and post-amble phrases at each node, and seeded with semantic values that convey meaning back to the application.

To use a GrammarBuilder to create a Grammar object, use the following steps.

  1. Create a GrammarBuilder object.

  2. Append constraints to the GrammarBuilder, such as String objects, Choices, SemanticResultKey, SemanticResultValue, and other GrammarBuilder objects that define the constraints for the grammar.

  3. Use one of the Grammar()()()() constructors to create a Grammar object from the completed GrammarBuilder grammar.

Authoring with GrammarBuilder is best suited to grammars that have a single rule containing lists, or perhaps lists of lists. To programmatically build grammars that have multiple rules, or that need to make internal rule references, use the classes of the Microsoft.Speech.Recognition.SrgsGrammar namespace.

Instances of GrammarBuilder can also be obtained by implicit conversions from certain other classes or by combining a GrammarBuilder with a second object that contains constraints for a grammar. For more information, see the ImplicitWideningImplicitImplicitImplicit and Addition operators and the Add methods.

To add constraints to an existing GrammarBuilder, use the Add, Append, AppendDictation, AppendRuleReference, and AppendWildcard methods.

Important note Important

The speech recognizer can throw an exception when using a speech recognition grammar that contains duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the value of the same semantic element. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

To help with debugging, the DebugShowPhrases property returns the current status of the GrammarBuilder as a string.

For more information about building and using speech recognition grammars, see Speech Recognition (Microsoft.Speech) and Create Grammars Using GrammarBuilder (Microsoft.Speech).

Examples

The following example uses GrammarBuilder and Choices objects to construct a grammar that can recognize either of the two phrases, "Make background colorChoice" or "Set background to colorChoice".

The example uses a Choices object to create a list of acceptable values for colorChoice from an array of String objects. A Choicesobject is analogous to the one-of element in the SRGS specification, and contains a set of alternate phrases, any of which can be recognized when spoken. The example also uses a Choices object to group an array of two GrammarBuilder objects into a pair of alternative phrases that the resultant grammar can recognize. Alternate words or phrases are a component of most grammars, and the Choicesobject provides this functionality for grammars constructed with GrammarBuilder.

The example finally creates a Grammar object from a GrammarBuilder constructed from a Choices object.

Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  Choices colorChoice = new Choices(new string[] {"red", "green", "blue"});
  GrammarBuilder colorElement = new GrammarBuilder(colorChoice);

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase = new GrammarBuilder("Make background");
  makePhrase.Append(colorElement);
  GrammarBuilder setPhrase = new GrammarBuilder("Set background to");
  setPhrase.Append(colorElement);

  // Create a Choices for the two alternative phrases, convert the Choices
  // to a GrammarBuilder, and construct the grammar from the result.
  Choices bothChoices = new Choices(new GrammarBuilder[] {makePhrase, setPhrase});
  Grammar grammar = new Grammar((GrammarBuilder)bothChoices);
  grammar.Name = "backgroundColor";
  return grammar;
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

GrammarBuilder Members
Microsoft.Speech.Recognition Namespace
Choices
Grammar
SemanticResultKey
SemanticResultValue
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Members

[image] [image]

GrammarBuilder Members
GrammarBuilder Class Constructors Methods Operators Properties See Also Send Feedback

Provides a mechanism for programmatically building the constraints for a speech recognition grammar.

The GrammarBuilder type exposes the following members.

Constructors

 | Name | Description
Public method | GrammarBuilder()()()() | Initializes a new, empty instance of the GrammarBuilder class.
Public method | GrammarBuilder(String) | Initializes a new instance of the GrammarBuilder class from a sequence of words.
Public method | GrammarBuilder(Choices) | Initializes a new instance of the GrammarBuilder class from a set of alternatives.
Public method | GrammarBuilder(SemanticResultKey) | Initializes a new instance of the GrammarBuilder class from a semantic key.
Public method | GrammarBuilder(SemanticResultValue) | Initializes a new instance of the GrammarBuilder class from a semantic value.
Public method | GrammarBuilder(String, SubsetMatchingMode) | Initializes a new instance of the GrammarBuilder class from a subset of a sequence of words.
Public method | GrammarBuilder(String, Int32, Int32) | Initializes a new instance of the GrammarBuilder class from the sequence of words in a String and specifies how many times the String can be repeated.
Public method | GrammarBuilder(GrammarBuilder, Int32, Int32) | Initializes a new instance of the GrammarBuilder class for a repeated element.
Top

Properties

 | Name | Description
Public property | Culture | Gets or sets the culture of the grammar.
Public property | DebugShowPhrases | Gets a string that shows the contents and structure of the grammar contained by the GrammarBuilder.
Top

Methods

 | Name | Description
 | Add(String, GrammarBuilder) | Creates a new GrammarBuilder that contains a phrase followed by a GrammarBuilder object.
 | Add(Choices, GrammarBuilder) | Creates a new GrammarBuilder that contains a Choices object followed by a GrammarBuilder object.
 | Add(GrammarBuilder, Choices) | Creates a new GrammarBuilder that contains a GrammarBuilder object followed by a Choices object.
 | Add(GrammarBuilder, GrammarBuilder) | Creates a new GrammarBuilder that contains a sequence of two GrammarBuilder objects.
 | Add(GrammarBuilder, String) | Creates a new GrammarBuilder that contains a GrammarBuilder object followed by a phrase.
Public method | Append(String) | Appends a phrase to the current sequence of grammar elements.
Public method | Append(Choices) | Appends a set of alternatives to the current sequence of grammar elements.
Public method | Append(GrammarBuilder) | Appends a grammar element to the current sequence of grammar elements.
Public method | Append(SemanticResultKey) | Appends a semantic key to the current sequence of grammar elements.
Public method | Append(SemanticResultValue) | Appends a semantic value to the current sequence of grammar elements.
Public method | Append(String, SubsetMatchingMode) | Appends an element for a subset of a phrase to the current sequence of grammar elements.
Public method | Append(String, Int32, Int32) | Appends a repeated phrase to the current sequence of grammar elements.
Public method | Append(GrammarBuilder, Int32, Int32) | Appends a repeated grammar element to the current sequence of grammar elements.
Public method | AppendDictation()()()() | Appends grammar logic to provide access the default, free-text, dictation grammar provided by the Microsoft Speech Platform SDK 11.
Public method | AppendDictation(String) | Appends grammar logic to provide access to a special-function dictation grammar specified by a string.
Public method | AppendRuleReference(String) | Appends a grammar definition file to the current sequence of grammar elements.
Public method | AppendRuleReference(String, String) | Appends the specified rule of a grammar definition file to the current sequence of grammar elements.
Public method | AppendWildcard | Appends a recognition grammar element that matches any input to the current sequence of grammar elements.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

Operators

Name | Description
Addition(String, GrammarBuilder) | Creates a new GrammarBuilder that contains a phrase followed by a GrammarBuilder.
Addition(Choices, GrammarBuilder) | Creates a new GrammarBuilder that contains a Choices object followed by a GrammarBuilder object.
Addition(GrammarBuilder, Choices) | Creates a new GrammarBuilder that contains a GrammarBuilder followed by a Choices.
Addition(GrammarBuilder, GrammarBuilder) | Creates a new GrammarBuilder that contains a sequence of two GrammarBuilder objects.
Addition(GrammarBuilder, String) | Creates a new GrammarBuilder that contains a GrammarBuilder followed by a phrase.
ImplicitWideningImplicitImplicitImplicit(String to GrammarBuilder) | Implicitly converts a String object to an instance of GrammarBuilder.
ImplicitWideningImplicitImplicitImplicit(Choices to GrammarBuilder) | Converts a Choices object to a GrammarBuilder object.
ImplicitWideningImplicitImplicitImplicit(SemanticResultKey to GrammarBuilder) | Converts a SemanticResultKey object to a GrammarBuilder object.
ImplicitWideningImplicitImplicitImplicit(SemanticResultValue to GrammarBuilder) | Converts a SemanticResultValue object to a GrammarBuilder object.
Top

See Also

Reference

GrammarBuilder Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Constructor

[image] [image]

GrammarBuilder Constructor
GrammarBuilder Class See Also Send Feedback

Constructs a new instance of GrammarBuilder.

Overload List

 | Name | Description
Public method | GrammarBuilder()()()() | Initializes a new, empty instance of the GrammarBuilder class.
Public method | GrammarBuilder(String) | Initializes a new instance of the GrammarBuilder class from a sequence of words.
Public method | GrammarBuilder(Choices) | Initializes a new instance of the GrammarBuilder class from a set of alternatives.
Public method | GrammarBuilder(SemanticResultKey) | Initializes a new instance of the GrammarBuilder class from a semantic key.
Public method | GrammarBuilder(SemanticResultValue) | Initializes a new instance of the GrammarBuilder class from a semantic value.
Public method | GrammarBuilder(String, SubsetMatchingMode) | Initializes a new instance of the GrammarBuilder class from a subset of a sequence of words.
Public method | GrammarBuilder(String, Int32, Int32) | Initializes a new instance of the GrammarBuilder class from the sequence of words in a String and specifies how many times the String can be repeated.
Public method | GrammarBuilder(GrammarBuilder, Int32, Int32) | Initializes a new instance of the GrammarBuilder class for a repeated element.
Top

Remarks

Instances of this class can also be obtained by implicit conversions from other classes or by combining a GrammarBuilder object with a second object to from a new GrammarBuilder. For more information, see the ImplicitWideningImplicitImplicitImplicit and Addition methods.

To add constraints to an existing GrammarBuilder, use the Add, Append, AppendDictation, AppendRuleReference, and AppendWildcard methods, and the Addition operator.

Important note Important

The speech recognizer can throw an exception when using a speech recognition grammar that contains duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the value of the same semantic element. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

For more information about building and using speech recognition grammars, see Speech Recognition (Microsoft.Speech) and Create Grammars Using GrammarBuilder (Microsoft.Speech).

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Constructor

[image]

GrammarBuilder Constructor
GrammarBuilder Class Example See Also Send Feedback

Initializes a new, empty instance of the GrammarBuilder class.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New GrammarBuilder()
C#
public GrammarBuilder()

Remarks

To add rules to an existing GrammarBuilder object, use the Add, Append, AppendDictation, AppendRuleReference, and AppendWildcard methods, and the Addition operator.

The speech recognizer can throw an exception when using a speech recognition grammar that contains duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the value of the same semantic element. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example uses GrammarBuilder and Choices objects to construct a grammar that can recognize either of the two phrases, "Make background colorChoice" or "Set background to colorChoice".

The example uses a Choices object to create a list of acceptable values for colorChoice from an array of String objects. A Choices object is analogous to the one-of element in the SRGS specification, and contains a set of alternate phrases, any one of which can be recognized when spoken. The example also uses a Choices object to group an array of two GrammarBuilder objects into a pair of alternative phrases that the resultant grammar can recognize. Alternate words or phrases are a component of most grammars, and the Choices object provides this functionality for grammars constructed with GrammarBuilder.

The example finally creates a Grammarobject from a GrammarBuilder constructed from a Choicesobject.

C# Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  Choices colorChoice = new Choices(new string[] {"red", "green", "blue"});
  GrammarBuilder colorElement = new GrammarBuilder(colorChoice);

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase = new GrammarBuilder("Make background");
  makePhrase.Append(colorElement);
  GrammarBuilder setPhrase = new GrammarBuilder("Set background to");
  setPhrase.Append(colorElement);

  // Create a Choices for the two alternative phrases, convert the Choices
  // to a GrammarBuilder, and construct the Grammar object from the result.
  GrammarBuilder bothPhrases = new GrammarBuilder();
  Choices bothChoices = new Choices(new GrammarBuilder[] {makePhrase, setPhrase});
  bothPhrases.Append(bothChoices);
  Grammar grammar = new Grammar(bothPhrases);
  grammar.Name = "backgroundColor";
  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
GrammarBuilder Overload
Microsoft.Speech.Recognition Namespace
Choices
Grammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Constructor (String)

[image]

GrammarBuilder Constructor (String)
GrammarBuilder Class Example See Also Send Feedback

Initializes a new instance of the GrammarBuilder class from a sequence of words.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    phrase As String _
)
Visual Basic (Usage)
Dim phrase As String

Dim instance As New GrammarBuilder(phrase)
C#
public GrammarBuilder(
    string phrase
)

Parameters

phrase
Type: System..::..String

The sequence of words.

Remarks

The phrase represents an exact spoken phrase that the speech recognition grammar can recognize. For more information about building a speech recognition grammar that contains strings, see Use a String to Create a GrammarBuilder (Microsoft.Speech).

Examples

The following example uses GrammarBuilder and Choices objects to construct a grammar that can recognize either of the two phrases, "Make background colorChoice" or "Set background to colorChoice".

After creating a list of acceptable values for colorChoice using a Choices object, the example initializes two GrammarBuilder objects, makePhrase and setPhrase, using a string as an argument.

The example finally creates a Grammar object from a GrammarBuilder constructed from a Choices object.

C# Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  Choices colorChoice = new Choices(new string[] {"red", "green", "blue"});
  GrammarBuilder colorElement = new GrammarBuilder(colorChoice);

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase = new GrammarBuilder("Make background");
  makePhrase.Append(colorElement);
  GrammarBuilder setPhrase = new GrammarBuilder("Set background to");
  setPhrase.Append(colorElement);

  // Create a Choices for the two alternative phrases, convert the Choices
  // to a GrammarBuilder, and construct the Grammar object from the result.
  Choices bothChoices = new Choices(new GrammarBuilder[] {makePhrase, setPhrase});
  Grammar grammar = new Grammar((GrammarBuilder)bothChoices);
  grammar.Name = "backgroundColor";
  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
GrammarBuilder Overload
Microsoft.Speech.Recognition Namespace
Choices
Grammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Constructor (Choices)

[image]

GrammarBuilder Constructor (Choices)
GrammarBuilder Class Example See Also Send Feedback

Initializes a new instance of the GrammarBuilder class from a set of alternatives.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    alternateChoices As Choices _
)
Visual Basic (Usage)
Dim alternateChoices As Choices

Dim instance As New GrammarBuilder(alternateChoices)
C#
public GrammarBuilder(
    Choices alternateChoices
)

Parameters

alternateChoices
Type: Microsoft.Speech.Recognition..::..Choices

The set of alternatives.

Remarks

For more information about building a speech recognition grammar that contains alternatives, see Use a Choices Object to Create a GrammarBuilder (Microsoft.Speech).

Examples

The following example uses GrammarBuilder and Choices objects to construct a grammar that can recognize either of the two phrases, "Make background colorChoice" or "Set background to colorChoice".

The example uses a Choices object to create a list of acceptable values for colorChoice from an array of String objects. A Choices object is analogous to the one-of element in the SRGS specification, and contains a set of alternate phrases, any of which can be recognized when spoken. The example also uses a Choices object to group an array of two GrammarBuilder objects into a pair of alternative phrases that the resultant grammar can recognize. Alternate words or phrases are a component of most grammars, and the Choices object provides this functionality for grammars constructed with GrammarBuilder.

The example finally creates a Grammar object from a GrammarBuilder constructed from a Choices object.

C# Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  Choices colorChoice = new Choices(new string[] {"red", "green", "blue"});
  GrammarBuilder colorElement = new GrammarBuilder(colorChoice);

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase = new GrammarBuilder("Make background");
  makePhrase.Append(colorElement);
  GrammarBuilder setPhrase = new GrammarBuilder("Set background to");
  setPhrase.Append(colorElement);

  // Create a Choices for the two alternative phrases, convert the Choices
  // to a GrammarBuilder, and construct the grammar from the result.
  Choices bothChoices = new Choices(new GrammarBuilder[] {makePhrase, setPhrase});
  Grammar grammar = new Grammar((GrammarBuilder)bothChoices);
  grammar.Name = "backgroundColor";
  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
GrammarBuilder Overload
Microsoft.Speech.Recognition Namespace
Choices
Grammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Constructor (SemanticResultKey)

[image]

GrammarBuilder Constructor (SemanticResultKey)
GrammarBuilder Class Example See Also Send Feedback

Initializes a new instance of the GrammarBuilder class from a semantic key.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    key As SemanticResultKey _
)
Visual Basic (Usage)
Dim key As SemanticResultKey

Dim instance As New GrammarBuilder(key)
C#
public GrammarBuilder(
    SemanticResultKey key
)

Parameters

key
Type: Microsoft.Speech.Recognition..::..SemanticResultKey

The semantic key.

Remarks

When you create a GrammarBuilder instance from a SemanticResultValue object, you add semantic information to the grammar that can be returned in the recognition result. You can access the semantic information in the recognition result using the Semantics property of RecognizedPhrase, which is available in the handler for the SpeechRecognized event. If the GrammarBuilder defines a SemanticResultKey, this can be used to retrieve the semantic information in a recognition result that is associated with the key. See the example for Append(SemanticResultKey), and also see SemanticResultValue and SemanticResultKey.

Important note Important

When you construct GrammarBuilder objects that contain SemanticResultValue or SemanticResultKey instances, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example creates a speech recognition grammar that can recognize the two phrases, "Make background colorChoice" and "Set background to colorChoice", where colorChoice is selected from a set of colors. The grammar lets a user speak any of several color names, and returns semantic information about the recognized color name to the application.

The example uses a single SemanticResultKey with which you can retrieve the SemanticValue that is associated with the color spoken by the user. For example, if the input contains the phrase, "Set background to red", the recognition result contains the semantic value of "#FF0000", which you can retrieve using a handler for the SpeechRecognized event.

The example uses String, Choices, SemanticResultKey, SemanticResultValue, and GrammarBuilder objects to build the constraints that are all contained in the last GrammarBuilder object, bothPhrases. Finally, the example constructs a Grammar object from the completed GrammarBuilder.

C# Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  // Include semantic information about each of the colors.
  Choices colorChoice = new Choices();

  GrammarBuilder colorBuilder = new GrammarBuilder("red");
  SemanticResultValue colorValue =
    new SemanticResultValue(colorBuilder, "#FF0000");
  colorChoice.Add(new GrammarBuilder(colorValue));

  colorBuilder = new GrammarBuilder("green");
  colorValue = new SemanticResultValue(colorBuilder, "#00FF00");
  colorChoice.Add(new GrammarBuilder(colorValue));

  colorBuilder = new GrammarBuilder("blue");
  colorValue = new SemanticResultValue(colorBuilder, "#0000FF");
  colorChoice.Add(new GrammarBuilder(colorValue));

  GrammarBuilder colorElement = new GrammarBuilder(colorChoice);

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase = new GrammarBuilder("Make background");
  makePhrase.Append(colorElement);
  GrammarBuilder setPhrase = new GrammarBuilder("Set background to");
  setPhrase.Append(colorElement);

  // Create a Choices object for the two alternative phrases.
  Choices bothChoices = new Choices(new GrammarBuilder[] {makePhrase, setPhrase});
  GrammarBuilder bothPhrases = new GrammarBuilder(bothChoices);

  // Create the semantic key for referencing the color information.
  SemanticResultKey colorKey =
    new SemanticResultKey("ColorCode", bothPhrases);
  bothPhrases = new GrammarBuilder(colorKey);

  // Construct the Grammar object from the GrammarBuilder.
  Grammar grammar = new Grammar(bothPhrases);
  grammar.Name = "backgroundColor";
  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
GrammarBuilder Overload
Microsoft.Speech.Recognition Namespace
Choices
Grammar
SemanticResultKey
SemanticResultValue
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Constructor (SemanticResultValue)

[image]

GrammarBuilder Constructor (SemanticResultValue)
GrammarBuilder Class Example See Also Send Feedback

Initializes a new instance of the GrammarBuilder class from a semantic value.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    value As SemanticResultValue _
)
Visual Basic (Usage)
Dim value As SemanticResultValue

Dim instance As New GrammarBuilder(value)
C#
public GrammarBuilder(
    SemanticResultValue value
)

Parameters

value
Type: Microsoft.Speech.Recognition..::..SemanticResultValue

The semantic value or name/value pair.

Remarks

When you create a GrammarBuilder instance from a SemanticResultValue object, you add semantic information to the grammar that can be returned in the recognition result. You can access the semantic information in the recognition result using the Semantics property of RecognizedPhrase, which is available in the handler for the SpeechRecognized event. If the GrammarBuilder defines a SemanticResultKey, this can be used to retrieve the semantic information in a recognition result that is associated with the key. See the example for Append(SemanticResultKey), and also see SemanticResultValue and SemanticResultKey.

Important note Important

When you construct GrammarBuilder objects that contain SemanticResultValue or SemanticResultKey instances, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example creates a speech recognition grammar that can recognize the two phrases, "Make background colorChoice" and "Set background to colorChoice", where colorChoice is selected from a set of colors. The grammar lets a user speak any of several color names, and returns semantic information about the recognized color name to the application.

The example uses a single SemanticResultKey with which you can retrieve the SemanticValue that is associated with the color spoken by the user. For example, if the input contains the phrase, "Set background to red", the recognition result contains the semantic value of "#FF0000", which you can retrieve using a handler for the SpeechRecognized event.

The example uses String, Choices, SemanticResultKey, SemanticResultValue, and GrammarBuilder objects to build the constraints that are all contained in the last GrammarBuilder object, bothPhrases. Finally, the example constructs a Grammar object from the completed GrammarBuilder.

C# Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  // Include semantic information about each of the colors.
  Choices colorChoice = new Choices();

  GrammarBuilder colorBuilder = new GrammarBuilder("red");
  SemanticResultValue colorValue =
    new SemanticResultValue(colorBuilder, "#FF0000");
  colorChoice.Add(new GrammarBuilder(colorValue));

  colorBuilder = new GrammarBuilder("green");
  colorValue = new SemanticResultValue(colorBuilder, "#00FF00");
  colorChoice.Add(new GrammarBuilder(colorValue));

  colorBuilder = new GrammarBuilder("blue");
  colorValue = new SemanticResultValue(colorBuilder, "#0000FF");
  colorChoice.Add(new GrammarBuilder(colorValue));

  GrammarBuilder colorElement = new GrammarBuilder(colorChoice);

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase = new GrammarBuilder("Make background");
  makePhrase.Append(colorElement);
  GrammarBuilder setPhrase = new GrammarBuilder("Set background to");
  setPhrase.Append(colorElement);

  // Create a Choices for the two alternative phrases.
  Choices bothChoices = new Choices(new GrammarBuilder[] {makePhrase, setPhrase});
  GrammarBuilder bothPhrases = new GrammarBuilder(bothChoices);

  // Create the semantic key for referencing the color information.
  SemanticResultKey colorKey =
    new SemanticResultKey("ColorCode", bothPhrases);
  bothPhrases = new GrammarBuilder(colorKey);

  // Construct the grammar from the grammar builder.
  Grammar grammar = new Grammar(bothPhrases);
  grammar.Name = "backgroundColor";
  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
GrammarBuilder Overload
Microsoft.Speech.Recognition Namespace
Choices
Grammar
SemanticResultKey
SemanticResultValue
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Constructor (String, SubsetMatchingMode)

[image]

GrammarBuilder Constructor (String, SubsetMatchingMode)
GrammarBuilder Class Example See Also Send Feedback

Initializes a new instance of the GrammarBuilder class from a subset of a sequence of words.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    phrase As String, _
    subsetMatchingCriteria As SubsetMatchingMode _
)
Visual Basic (Usage)
Dim phrase As String
Dim subsetMatchingCriteria As SubsetMatchingMode

Dim instance As New GrammarBuilder(phrase, _
    subsetMatchingCriteria)
C#
public GrammarBuilder(
    string phrase,
    SubsetMatchingMode subsetMatchingCriteria
)

Parameters

phrase
Type: System..::..String

The sequence of words.

subsetMatchingCriteria
Type: Microsoft.Speech.Recognition..::..SubsetMatchingMode

The matching mode the speech recognition grammar uses to recognize the phrase.

Remarks

The phrase parameter represents the phrase that the speech recognition grammar can recognize. The subsetMatchingMode parameter specifies a subset of the phrase that can be spoken to achieve successful recognition of the entire phrase. You can use this to create a grammar with a list of entries that have long names, without requiring users to speak an entire name to match an item.

For more information about the matching modes, see SubsetMatchingMode. For more information about building a speech recognition grammar that contains strings, see Use a String to Create a GrammarBuilder (Microsoft.Speech).

Examples

The following example creates a speech recognition grammar for each SubsetMatchingMode value and a grammar for choosing between the matching mode grammars. If the value of phrase is "one two three four five six seven", then the Subsequence grammar recognizes the input "two three four", but not the input "one three five". However, the Ordered Subset grammar recognizes both of these inputs.

C# Copy image Copy Code
private static IEnumerable<Grammar>
  CreateMatchingModeGrammars(string phrase)
{
  List<Grammar> grammars = new List<Grammar>(5);

  Choices modeChoice = new Choices();
  Type enumType = typeof(SubsetMatchingMode);
  foreach (SubsetMatchingMode mode in Enum.GetValues(enumType))
  {
    string modeName = Enum.GetName(enumType, mode);
    modeName = BreakAtCaps(modeName);

    GrammarBuilder builder = new GrammarBuilder(phrase, mode);
    Grammar modeGrammar = new Grammar(builder);
    modeGrammar.Name = modeName;
    modeGrammar.Enabled = false;
    grammars.Add(modeGrammar);

    modeChoice.Add(modeName);
  }

  Grammar choiceGrammar = new Grammar(modeChoice);
  choiceGrammar.Name = "choice";
  grammars.Add(choiceGrammar);

  return grammars;
}

// Insert spaces preceding each uppercase letter in a string.
private static string BreakAtCaps(string item)
{
  if (item == null || item.Length == 0)
  {
    return item;
  }

  StringBuilder sb = new StringBuilder(item[0].ToString());
  for (int i = 1; i < item.Length; i++)
  {
    char c = item[i];
    if (char.IsUpper(c))
    {
      sb.Append(" ");
    }
    sb.Append(c);
  }

  return sb.ToString();
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
GrammarBuilder Overload
Microsoft.Speech.Recognition Namespace
SubsetMatchingMode
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Constructor (String, Int32, Int32)

[image]

GrammarBuilder Constructor (String, Int32, Int32)
GrammarBuilder Class Example See Also Send Feedback

Initializes a new instance of the GrammarBuilder class from the sequence of words in a String and specifies how many times the String can be repeated.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    phrase As String, _
    minRepeat As Integer, _
    maxRepeat As Integer _
)
Visual Basic (Usage)
Dim phrase As String
Dim minRepeat As Integer
Dim maxRepeat As Integer

Dim instance As New GrammarBuilder(phrase, _
    minRepeat, maxRepeat)
C#
public GrammarBuilder(
    string phrase,
    int minRepeat,
    int maxRepeat
)

Parameters

phrase
Type: System..::..String

The repeated sequence of words.

minRepeat
Type: System..::..Int32

The minimum number of times that input matching the phrase must occur to constitute a match.

maxRepeat
Type: System..::..Int32

The maximum number of times that input matching the phrase can occur to constitute a match.

Remarks

If the value of minRepeat is 0, then the new GrammarBuilder represents an optional element.

The value of minRepeat must be greater than or equal to 0 and less than or equal to the value of maxRepeat. For more information about building a speech recognition grammar that contains strings, see Use a String to Create a GrammarBuilder (Microsoft.Speech).

Examples

The following example creates a speech recognition grammar for ordering a pizza. It starts with an optional, opening phrase, followed by one to four toppings, and closes with the word "pizza".

C# Copy image Copy Code
private static Grammar CreatePizzaGrammar()
{

  // Create a Choices object with alternatives for toppings.
  Choices toppings = new Choices(new string[] {
    "cheese", "mushroom", "tomato", "onion",
    "anchovy", "chicken", "pepperoni"});

  // Create a GrammarBuilder and append the Choices object.
  GrammarBuilder andToppings = new GrammarBuilder("and", 0, 1);
  andToppings.Append(toppings);

  // Construct the phrase.
  GrammarBuilder gb = new GrammarBuilder("I would like a", 0, 1);
  gb.Append(toppings);
  gb.Append(new GrammarBuilder(andToppings, 0, 3));
  gb.Append("pizza");

  // Create the Grammar from the GrammarBuilder.
  Grammar grammar = new Grammar(gb);
  grammar.Name = "Pizza Order";

  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
GrammarBuilder Overload
Microsoft.Speech.Recognition Namespace
Choices
Grammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Constructor (GrammarBuilder, Int32, Int32)

[image]

GrammarBuilder Constructor (GrammarBuilder, Int32, Int32)
GrammarBuilder Class Example See Also Send Feedback

Initializes a new instance of the GrammarBuilder class for a repeated element.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    builder As GrammarBuilder, _
    minRepeat As Integer, _
    maxRepeat As Integer _
)
Visual Basic (Usage)
Dim builder As GrammarBuilder
Dim minRepeat As Integer
Dim maxRepeat As Integer

Dim instance As New GrammarBuilder(builder, _
    minRepeat, maxRepeat)
C#
public GrammarBuilder(
    GrammarBuilder builder,
    int minRepeat,
    int maxRepeat
)

Parameters

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The repeated element.

minRepeat
Type: System..::..Int32

The minimum number of times that input matching the element defined by builder must occur to constitute a match.

maxRepeat
Type: System..::..Int32

The maximum number of times that input matching the element defined by builder can occur to constitute a match.

Remarks

If the value of minRepeat is 0, then the new GrammarBuilder represents an optional element.

The value of minRepeat must be greater than or equal to 0 and less than or equal to the value of maxRepeat.

Important note Important

When you specify repeats for GrammarBuilder objects that contain SemanticResultValue or SemanticResultKey instances, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example creates a speech recognition grammar for ordering a pizza. It starts with an optional, opening phrase, followed by one to four toppings, and closes with the word "pizza".

C# Copy image Copy Code
private static Grammar CreatePizzaGrammar()
{

  // Create a Choices object from a string array of alternative toppings.
  Choices toppings = new Choices(new string[] {
    "cheese", "mushroom", "tomato", "onion",
    "anchovy", "chicken", "pepperoni"});

  // Create a GrammarBuilder and append the Choices object.
  GrammarBuilder andToppings = new GrammarBuilder("and", 0, 1);
  andToppings.Append(toppings);

  // Construct the phrase.
  GrammarBuilder gb = new GrammarBuilder("I would like a", 0, 1);
  gb.Append(toppings);
  gb.Append(new GrammarBuilder(andToppings, 0, 3));
  gb.Append("pizza");

  // Create the Grammar from the GrammarBuilder.
  Grammar grammar = new Grammar(gb);
  grammar.Name = "Pizza Order";

  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
GrammarBuilder Overload
Microsoft.Speech.Recognition Namespace
Choices
Grammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Methods

[image] [image]

GrammarBuilder Methods
GrammarBuilder Class See Also Send Feedback

The GrammarBuilder type exposes the following members.

Methods

 | Name | Description
 | Add(String, GrammarBuilder) | Creates a new GrammarBuilder that contains a phrase followed by a GrammarBuilder object.
 | Add(Choices, GrammarBuilder) | Creates a new GrammarBuilder that contains a Choices object followed by a GrammarBuilder object.
 | Add(GrammarBuilder, Choices) | Creates a new GrammarBuilder that contains a GrammarBuilder object followed by a Choices object.
 | Add(GrammarBuilder, GrammarBuilder) | Creates a new GrammarBuilder that contains a sequence of two GrammarBuilder objects.
 | Add(GrammarBuilder, String) | Creates a new GrammarBuilder that contains a GrammarBuilder object followed by a phrase.
Public method | Append(String) | Appends a phrase to the current sequence of grammar elements.
Public method | Append(Choices) | Appends a set of alternatives to the current sequence of grammar elements.
Public method | Append(GrammarBuilder) | Appends a grammar element to the current sequence of grammar elements.
Public method | Append(SemanticResultKey) | Appends a semantic key to the current sequence of grammar elements.
Public method | Append(SemanticResultValue) | Appends a semantic value to the current sequence of grammar elements.
Public method | Append(String, SubsetMatchingMode) | Appends an element for a subset of a phrase to the current sequence of grammar elements.
Public method | Append(String, Int32, Int32) | Appends a repeated phrase to the current sequence of grammar elements.
Public method | Append(GrammarBuilder, Int32, Int32) | Appends a repeated grammar element to the current sequence of grammar elements.
Public method | AppendDictation()()()() | Appends grammar logic to provide access the default, free-text, dictation grammar provided by the Microsoft Speech Platform SDK 11.
Public method | AppendDictation(String) | Appends grammar logic to provide access to a special-function dictation grammar specified by a string.
Public method | AppendRuleReference(String) | Appends a grammar definition file to the current sequence of grammar elements.
Public method | AppendRuleReference(String, String) | Appends the specified rule of a grammar definition file to the current sequence of grammar elements.
Public method | AppendWildcard | Appends a recognition grammar element that matches any input to the current sequence of grammar elements.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

GrammarBuilder Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method

[image] [image]

GrammarBuilder..::..Add Method
GrammarBuilder Class See Also Send Feedback

Creates a new GrammarBuilder that contains a sequence of two grammar elements.

Overload List

Name | Description
Add(String, GrammarBuilder) | Creates a new GrammarBuilder that contains a phrase followed by a GrammarBuilder object.
Add(Choices, GrammarBuilder) | Creates a new GrammarBuilder that contains a Choices object followed by a GrammarBuilder object.
Add(GrammarBuilder, Choices) | Creates a new GrammarBuilder that contains a GrammarBuilder object followed by a Choices object.
Add(GrammarBuilder, GrammarBuilder) | Creates a new GrammarBuilder that contains a sequence of two GrammarBuilder objects.
Add(GrammarBuilder, String) | Creates a new GrammarBuilder that contains a GrammarBuilder object followed by a phrase.
Top

Remarks

The static Add methods provide another mechanism by which you can combine various types to create diversity and flexibility in grammars built with GrammarBuilder. These methods correspond to the static Addition methods, which are also defined on the GrammarBuilder class. The order of the parameters determines the order of the elements in the new GrammarBuilder.

A GrammarBuilder can also be obtained from Choices, SemanticResultKey, SemanticResultValue, and String objects. For more information, see the ImplicitWideningImplicitImplicitImplicit and Addition operators.

Important note Important

The speech recognizer can throw an exception when using a speech recognition grammar that contains duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the value of the same semantic element. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

For more information about building and using speech recognition grammars, see Speech Recognition (Microsoft.Speech) and Create Grammars Using GrammarBuilder (Microsoft.Speech).

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method (String, GrammarBuilder)

[image]

GrammarBuilder..::..Add Method (String, GrammarBuilder)
GrammarBuilder Class Example See Also Send Feedback

Creates a new GrammarBuilder that contains a phrase followed by a GrammarBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Shared Function Add ( _
    phrase As String, _
    builder As GrammarBuilder _
) As GrammarBuilder
Visual Basic (Usage)
Dim phrase As String
Dim builder As GrammarBuilder
Dim returnValue As GrammarBuilder

returnValue = GrammarBuilder.Add(phrase, builder)
C#
public static GrammarBuilder Add(
    string phrase,
    GrammarBuilder builder
)

Parameters

phrase
Type: System..::..String

The first grammar element, which represents a sequence of words.

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The second grammar element.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

A GrammarBuilder for the sequence of the phrase element followed by the builder element.

Remarks

GrammarBuilder supports implicit conversions from the following classes:

  • Choices

  • SemanticResultKey

  • SemanticResultValue

  • String

This method accepts the objects listed above for the builder parameter.

For more information, see the ImplicitWideningImplicitImplicitImplicit and Addition operators.

Examples

The following example creates a speech recognition grammar that can recognize the two phrases, "Make background color" and "Set background to color", where color is selected from a set of colors. Various types are used to build the final grammar, such as String, Choices, and GrammarBuilder objects. The explicit cast operators in the calls to the Add methods are optional.

C# Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  Choices colorChoice = new Choices(new string[] {"red", "green", "blue"});

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase =
    GrammarBuilder.Add((GrammarBuilder)"Make background", colorChoice);
  GrammarBuilder setPhrase =
    GrammarBuilder.Add("Set background to", (GrammarBuilder)colorChoice);

  // Create a Choices for the two alternative phrases, convert the Choices
  // to a GrammarBuilder, and construct the grammar from the result.
  Choices bothChoices = new Choices(new GrammarBuilder[] {makePhrase, setPhrase});
  GrammarBuilder bothPhrases = new GrammarBuilder(bothChoices);

  Grammar grammar = new Grammar(bothPhrases);
  grammar.Name = "backgroundColor";
  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Add Overload
Microsoft.Speech.Recognition Namespace
Append
ImplicitWideningImplicitImplicitImplicit
Addition
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method (Choices, GrammarBuilder)

[image]

GrammarBuilder..::..Add Method (Choices, GrammarBuilder)
GrammarBuilder Class See Also Send Feedback

Creates a new GrammarBuilder that contains a Choices object followed by a GrammarBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Shared Function Add ( _
    choices As Choices, _
    builder As GrammarBuilder _
) As GrammarBuilder
Visual Basic (Usage)
Dim choices As Choices
Dim builder As GrammarBuilder
Dim returnValue As GrammarBuilder

returnValue = GrammarBuilder.Add(choices, builder)
C#
public static GrammarBuilder Add(
    Choices choices,
    GrammarBuilder builder
)

Parameters

choices
Type: Microsoft.Speech.Recognition..::..Choices

The first grammar element, which represents a set of alternatives.

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The second grammar element.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

A GrammarBuilder for the sequence of the choices element followed by the builder element.

Remarks

GrammarBuilder supports implicit conversions from the following classes:

  • Choices

  • SemanticResultKey

  • SemanticResultValue

  • String

This method accepts the objects listed above for the builder parameter.

For more information, see the ImplicitWideningImplicitImplicitImplicit and Addition operators.

Important note Important

When you combine Choices or GrammarBuilder objects that contain SemanticResultValue or SemanticResultKey instances, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Add Overload
Microsoft.Speech.Recognition Namespace
Append
ImplicitWideningImplicitImplicitImplicit
Addition
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method (GrammarBuilder, Choices)

[image]

GrammarBuilder..::..Add Method (GrammarBuilder, Choices)
GrammarBuilder Class Example See Also Send Feedback

Creates a new GrammarBuilder that contains a GrammarBuilder object followed by a Choices object.

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

Syntax

Visual Basic (Declaration)
Public Shared Function Add ( _
    builder As GrammarBuilder, _
    choices As Choices _
) As GrammarBuilder
Visual Basic (Usage)
Dim builder As GrammarBuilder
Dim choices As Choices
Dim returnValue As GrammarBuilder

returnValue = GrammarBuilder.Add(builder, choices)
C#
public static GrammarBuilder Add(
    GrammarBuilder builder,
    Choices choices
)

Parameters

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The first grammar element.

choices
Type: Microsoft.Speech.Recognition..::..Choices

The second grammar element, which represents a set of alternatives.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

A GrammarBuilder for the sequence of the builder element followed by the choices element.

Remarks

GrammarBuilder supports implicit conversions from the following classes:

  • Choices

  • SemanticResultKey

  • SemanticResultValue

  • String

This method accepts the objects listed above for the builder parameter.

For more information, see the ImplicitWideningImplicitImplicitImplicit and Addition operators.

Important note Important

When you combine Choices or GrammarBuilder objects that contain SemanticResultValue or SemanticResultKey instances, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example creates a speech recognition grammar that can recognize the two phrases, "Make background color" and "Set background to color", where color is selected from a set of colors. Various types are used to build the final grammar, such as String, Choices, and GrammarBuilder objects. The explicit cast operators in the calls to the Add methods are optional.

C# Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  Choices colorChoice = new Choices(new string[] {"red", "green", "blue"});

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase =
    GrammarBuilder.Add((GrammarBuilder)"Make background", colorChoice);
  GrammarBuilder setPhrase =
    GrammarBuilder.Add("Set background to", (GrammarBuilder)colorChoice);

  // Create a Choices for the two alternative phrases, convert the Choices
  // to a GrammarBuilder, and construct the grammar from the result.
  Choices bothChoices = new Choices(new GrammarBuilder[] {makePhrase, setPhrase});
  GrammarBuilder bothPhrases = new GrammarBuilder(bothChoices);

  Grammar grammar = new Grammar(bothPhrases);
  grammar.Name = "backgroundColor";
  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Add Overload
Microsoft.Speech.Recognition Namespace
Append
ImplicitWideningImplicitImplicitImplicit
Addition
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method (GrammarBuilder, GrammarBuilder)

[image]

GrammarBuilder..::..Add Method (GrammarBuilder, GrammarBuilder)
GrammarBuilder Class Example See Also Send Feedback

Creates a new GrammarBuilder that contains a sequence of two GrammarBuilder objects.

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

Syntax

Visual Basic (Declaration)
Public Shared Function Add ( _
    builder1 As GrammarBuilder, _
    builder2 As GrammarBuilder _
) As GrammarBuilder
Visual Basic (Usage)
Dim builder1 As GrammarBuilder
Dim builder2 As GrammarBuilder
Dim returnValue As GrammarBuilder

returnValue = GrammarBuilder.Add(builder1, _
    builder2)
C#
public static GrammarBuilder Add(
    GrammarBuilder builder1,
    GrammarBuilder builder2
)

Parameters

builder1
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The first grammar element.

builder2
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The second grammar element.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

A GrammarBuilder for the sequence of the builder1 element followed by the builder2 element.

Remarks

GrammarBuilder supports implicit conversions from the following classes:

  • Choices

  • SemanticResultKey

  • SemanticResultValue

  • String

This method accepts the objects listed above for the builder1 or builder2 parameter.

For more information, see the ImplicitWideningImplicitImplicitImplicit and Addition operators.

Important note Important

When you combine GrammarBuilder objects that contain SemanticResultValue or SemanticResultKey instances, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example creates a speech recognition grammar that can recognize the two phrases, "Make background color" and "Set background to color", where color is selected from a set of colors. Various types are used to build the final grammar, such as String, Choices, and GrammarBuilder objects. The explicit cast operators in the calls to the Add methods are optional.

C# Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  Choices colorChoice = new Choices(new string[] {"red", "green", "blue"});

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase =
    GrammarBuilder.Add((GrammarBuilder)"Make background", colorChoice);
  GrammarBuilder setPhrase =
    GrammarBuilder.Add("Set background to", (GrammarBuilder)colorChoice);

  // Create a Choices for the two alternative phrases, convert the Choices
  // to a GrammarBuilder, and construct the grammar from the result.
  Choices bothChoices = new Choices(new GrammarBuilder[] {makePhrase, setPhrase});
  GrammarBuilder bothPhrases = new GrammarBuilder(bothChoices);

  Grammar grammar = new Grammar(bothPhrases);
  grammar.Name = "backgroundColor";
  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Add Overload
Microsoft.Speech.Recognition Namespace
Append
ImplicitWideningImplicitImplicitImplicit
Addition
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method (GrammarBuilder, String)

[image]

GrammarBuilder..::..Add Method (GrammarBuilder, String)
GrammarBuilder Class Example See Also Send Feedback

Creates a new GrammarBuilder that contains a GrammarBuilder object followed by a phrase.

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

Syntax

Visual Basic (Declaration)
Public Shared Function Add ( _
    builder As GrammarBuilder, _
    phrase As String _
) As GrammarBuilder
Visual Basic (Usage)
Dim builder As GrammarBuilder
Dim phrase As String
Dim returnValue As GrammarBuilder

returnValue = GrammarBuilder.Add(builder, phrase)
C#
public static GrammarBuilder Add(
    GrammarBuilder builder,
    string phrase
)

Parameters

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The first grammar element.

phrase
Type: System..::..String

The second grammar element, which represents a sequence of words.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

A GrammarBuilder for the sequence of the builder element followed by the phrase element.

Remarks

GrammarBuilder supports implicit conversions from the following classes:

  • Choices

  • SemanticResultKey

  • SemanticResultValue

  • String

This method accepts the objects listed above for the builder parameter.

For more information, see the ImplicitWideningImplicitImplicitImplicit and Addition operators.

Important note Important

Caution is recommended when combining Choices or GrammarBuilder objects that contain SemanticResultValue or SemanticResultKey instances with other grammar elements. The speech recognizer can throw an exception when using a speech recognition grammar that contains duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the value of the same semantic element. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example creates a speech recognition grammar that can recognize the two phrases, "Make background color" and "Set background to color", where color is selected from a set of colors. Various types are used to build the final grammar, such as String, Choices, and GrammarBuilder objects. The explicit cast operators in the calls to the Add methods are optional.

C# Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  Choices colorChoice = new Choices(new string[] {"red", "green", "blue"});

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase =
    GrammarBuilder.Add((GrammarBuilder)"Make background", colorChoice);
  GrammarBuilder setPhrase =
    GrammarBuilder.Add("Set background to", (GrammarBuilder)colorChoice);

  // Create a Choices for the two alternative phrases, convert the Choices
  // to a GrammarBuilder, and construct the grammar from the result.
  Choices bothChoices = new Choices(new GrammarBuilder[] {makePhrase, setPhrase});
  GrammarBuilder bothPhrases = new GrammarBuilder(bothChoices);

  Grammar grammar = new Grammar(bothPhrases);
  grammar.Name = "backgroundColor";
  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Add Overload
Microsoft.Speech.Recognition Namespace
Append
ImplicitWideningImplicitImplicitImplicit
Addition
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Append Method

[image] [image]

GrammarBuilder..::..Append Method
GrammarBuilder Class See Also Send Feedback

Appends recognition grammar elements to the current GrammarBuilder.

Overload List

 | Name | Description
Public method | Append(String) | Appends a phrase to the current sequence of grammar elements.
Public method | Append(Choices) | Appends a set of alternatives to the current sequence of grammar elements.
Public method | Append(GrammarBuilder) | Appends a grammar element to the current sequence of grammar elements.
Public method | Append(SemanticResultKey) | Appends a semantic key to the current sequence of grammar elements.
Public method | Append(SemanticResultValue) | Appends a semantic value to the current sequence of grammar elements.
Public method | Append(String, SubsetMatchingMode) | Appends an element for a subset of a phrase to the current sequence of grammar elements.
Public method | Append(String, Int32, Int32) | Appends a repeated phrase to the current sequence of grammar elements.
Public method | Append(GrammarBuilder, Int32, Int32) | Appends a repeated grammar element to the current sequence of grammar elements.
Top

Remarks

Use these methods to append grammar elements to an existing GrammarBuilder. As you create grammar elements, you can append them to the existing builder to progressively develop the constraints for a speech recognition grammar. Each element is added to the end of the current sequence of elements.

This method has overloads for appending GrammarBuilder, String, Choices, SemanticResultKey, and SemanticResultValue objects.

Important note Important

The speech recognizer can throw an exception when using a speech recognition grammar that contains duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the value of the same semantic element. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

For more information about building and using speech recognition grammars, see Speech Recognition (Microsoft.Speech) and Create Grammars Using GrammarBuilder (Microsoft.Speech).

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Append Method (String)

[image]

GrammarBuilder..::..Append Method (String)
GrammarBuilder Class See Also Send Feedback

Appends a phrase to the current sequence of grammar elements.

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

Syntax

Visual Basic (Declaration)
Public Sub Append ( _
    phrase As String _
)
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim phrase As String

instance.Append(phrase)
C#
public void Append(
    string phrase
)

Parameters

phrase
Type: System..::..String

The sequence of words to append.

Remarks

phrase is added to the end of the current sequence of elements.

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Append Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Append Method (Choices)

[image]

GrammarBuilder..::..Append Method (Choices)
GrammarBuilder Class Example See Also Send Feedback

Appends a set of alternatives to the current sequence of grammar elements.

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

Syntax

Visual Basic (Declaration)
Public Sub Append ( _
    alternateChoices As Choices _
)
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim alternateChoices As Choices

instance.Append(alternateChoices)
C#
public void Append(
    Choices alternateChoices
)

Parameters

alternateChoices
Type: Microsoft.Speech.Recognition..::..Choices

The set of alternatives to append.

Remarks

alternateChoices is added to the end of the current sequence of elements.

Important note Important

When you append Choices objects to a GrammarBuilder instance that contains SemanticResultValue or SemanticResultKey instances, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example creates a speech recognition grammar for phrases such as "Call James at work" and "Call Anne on her cell phone", where the word "phone" is optional. The example highlights the use of the Append method.

C# Copy image Copy Code

public static Grammar CreatePhonePhrase()
{
  // Create alternatives for person names, locations, devices, and pronouns.
  Choices personChoice = new Choices(new string[] {"Anne", "James", "Mary", "Sam"});
  Choices locationChoice = new Choices(new string[] {"home", "work"});
  Choices deviceChoice = new Choices(new string[] {"home", "work", "cell"});
  Choices pronounChoice = new Choices(new string[] {"his", "her"});

  // Create a phrase for the receiving device, which optionally contains the word "phone".
  GrammarBuilder devicePhrase = new GrammarBuilder(pronounChoice);
  devicePhrase.Append(deviceChoice);
  devicePhrase.Append("phone", 0, 1);

  // Create alternatives for phrases specifying a device or a location.
  GrammarBuilder atLocation = new GrammarBuilder("at");
  atLocation.Append(locationChoice);

  GrammarBuilder onDevice = new GrammarBuilder("on");
  onDevice.Append(devicePhrase);

  Choices howChoice = new Choices(new GrammarBuilder[] {atLocation, onDevice});

  // Build the final phrase.
  GrammarBuilder callWho = new GrammarBuilder("Call");
  callWho.Append(personChoice);
  callWho.Append(howChoice);

  // Create the Grammar object.
  Grammar callGrammar = new Grammar(callWho);
  callGrammar.Name = "Call Grammar";

  return callGrammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Append Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Append Method (GrammarBuilder)

[image]

GrammarBuilder..::..Append Method (GrammarBuilder)
GrammarBuilder Class Example See Also Send Feedback

Appends a grammar element to the current sequence of grammar elements.

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

Syntax

Visual Basic (Declaration)
Public Sub Append ( _
    builder As GrammarBuilder _
)
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim builder As GrammarBuilder

instance.Append(builder)
C#
public void Append(
    GrammarBuilder builder
)

Parameters

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The grammar element to append.

Remarks

builder is added to the end of the current sequence of grammar elements.

Important note Important

When you append GrammarBuilder objects that contain SemanticResultValue or SemanticResultKey instances to a GrammarBuilder instance, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example creates a speech recognition grammar for phrases such as "Call James at work" and "Call Anne on her cell phone", where the word "phone" is optional. GrammarBuilder and Choices objects are used to construct the grammar. The example highlights the use of the Append method.

C# Copy image Copy Code

public static Grammar CreatePhonePhrase()
{
  // Create alternatives for person names, locations, devices, and pronouns.
  Choices personChoice = new Choices(new string[] {"Anne", "James", "Mary", "Sam"});
  Choices locationChoice = new Choices(new string[] {"home", "work"});
  Choices deviceChoice = new Choices(new string[] {"home", "work", "cell"});
  Choices pronounChoice = new Choices(new string[] {"his", "her"});

  // Create a phrase for the receiving device, which optionally contains the word "phone".
  GrammarBuilder devicePhrase = new GrammarBuilder(pronounChoice);
  devicePhrase.Append(deviceChoice);
  devicePhrase.Append("phone", 0, 1);

  // Create alternatives for phrases specifying a device or a location.
  GrammarBuilder atLocation = new GrammarBuilder("at");
  atLocation.Append(locationChoice);

  GrammarBuilder onDevice = new GrammarBuilder("on");
  onDevice.Append(devicePhrase);

  Choices howChoice = new Choices(new GrammarBuilder[] {atLocation, onDevice});

  // Build the final phrase.
  GrammarBuilder callWho = new GrammarBuilder("Call");
  callWho.Append(personChoice);
  callWho.Append(howChoice);

  // Create the Grammar object.
  Grammar callGrammar = new Grammar(callWho);
  callGrammar.Name = "Call Grammar";

  return callGrammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Append Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Append Method (SemanticResultKey)

[image]

GrammarBuilder..::..Append Method (SemanticResultKey)
GrammarBuilder Class Example See Also Send Feedback

Appends a semantic key to the current sequence of grammar elements.

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

Syntax

Visual Basic (Declaration)
Public Sub Append ( _
    key As SemanticResultKey _
)
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim key As SemanticResultKey

instance.Append(key)
C#
public void Append(
    SemanticResultKey key
)

Parameters

key
Type: Microsoft.Speech.Recognition..::..SemanticResultKey

The semantic key to append.

Remarks

key is added to the end of the current sequence of elements.

Important note Important

When you append SemanticResultValue or SemanticResultKey instances to a GrammarBuilder object, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example is part of a console application for choosing origin and destination cities for a flight. The application recognizes phrases such as "I want to fly from Miami to Chicago." The handler for the SpeechRecognized event uses the SemanticResultKey to extract the airport code specified in the SemanticResultValue for the origin and destination cities.

C# Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

    // Initialize an in-process speech recognition engine.
    {
      using (SpeechRecognitionEngine recognizer =
         new SpeechRecognitionEngine())
      {

        // Create a Choices object and add  cities and airport codes
        // using SemanticResultValue objects.
        Choices cities = new Choices();
        cities.Add(new SemanticResultValue("Chicago", "ORD"));
        cities.Add(new SemanticResultValue("Boston", "BOS"));
        cities.Add(new SemanticResultValue("Miami", "MIA"));
        cities.Add(new SemanticResultValue("Dallas", "DFW"));

        // Build the phrase and add SemanticResultKeys.
        GrammarBuilder chooseCities = new GrammarBuilder();
        chooseCities.Append("I want to fly from");
        chooseCities.Append(new SemanticResultKey("origin", cities));
        chooseCities.Append("to");
        chooseCities.Append(new SemanticResultKey("destination", cities));

        // Build a Grammar object from the GrammarBuilder.
        Grammar bookFlight = new Grammar(chooseCities);
        bookFlight.Name = "Book Flight";

        // 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);

        // Configure the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

        // Load the grammar object and start recognition.
        recognizer.LoadGrammarAsync(bookFlight);
        recognizer.RecognizeAsync();

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

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

    // Handle the SpeechRecognized event.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine("Speech recognized:  " + e.Result.Text);
      Console.WriteLine();
      Console.WriteLine("Semantic results:");
      Console.WriteLine("  The flight origin is " + e.Result.Semantics["origin"].Value);
      Console.WriteLine("  The flight destination is " + e.Result.Semantics["destination"].Value);
    }
  }
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Append Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Append Method (SemanticResultValue)

[image]

GrammarBuilder..::..Append Method (SemanticResultValue)
GrammarBuilder Class Example See Also Send Feedback

Appends a semantic value to the current sequence of grammar elements.

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

Syntax

Visual Basic (Declaration)
Public Sub Append ( _
    value As SemanticResultValue _
)
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim value As SemanticResultValue

instance.Append(value)
C#
public void Append(
    SemanticResultValue value
)

Parameters

value
Type: Microsoft.Speech.Recognition..::..SemanticResultValue

The semantic value to append.

Remarks

value is added to the end of the current sequence of elements.

Important note Important

When you append SemanticResultValue or SemanticResultKey instances to a GrammarBuilder object, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example is part of a console application for choosing origin and destination cities for a flight. The application recognizes phrases such as "I want to fly from Miami to Chicago." The handler for the SpeechRecognized event uses the SemanticResultKey to extract the airport code specified in the SemanticResultValue for the origin and destination cities.

C# Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

    // Initialize an in-process speech recognition engine.
    {
      using (SpeechRecognitionEngine recognizer =
         new SpeechRecognitionEngine())
      {

        // Create a Choices object and add  cities and airport codes
        // using SemanticResultValue objects.
        Choices cities = new Choices();
        cities.Add(new SemanticResultValue("Chicago", "ORD"));
        cities.Add(new SemanticResultValue("Boston", "BOS"));
        cities.Add(new SemanticResultValue("Miami", "MIA"));
        cities.Add(new SemanticResultValue("Dallas", "DFW"));

        // Build the phrase and add SemanticResultKeys.
        GrammarBuilder chooseCities = new GrammarBuilder();
        chooseCities.Append("I want to fly from");
        chooseCities.Append(new SemanticResultKey("origin", cities));
        chooseCities.Append("to");
        chooseCities.Append(new SemanticResultKey("destination", cities));

        // Build a Grammar object from the GrammarBuilder.
        Grammar bookFlight = new Grammar(chooseCities);
        bookFlight.Name = "Book Flight";

        // 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);

        // Configure the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

        // Load the grammar object and start recognition.
        recognizer.LoadGrammarAsync(bookFlight);
        recognizer.RecognizeAsync();

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

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

    // Handle the SpeechRecognized event.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine("Speech recognized:  " + e.Result.Text);
      Console.WriteLine();
      Console.WriteLine("Semantic results:");
      Console.WriteLine("  The flight origin is " + e.Result.Semantics["origin"].Value);
      Console.WriteLine("  The flight destination is " + e.Result.Semantics["destination"].Value);
    }
  }
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Append Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Append Method (String, SubsetMatchingMode)

[image]

GrammarBuilder..::..Append Method (String, SubsetMatchingMode)
GrammarBuilder Class Example See Also Send Feedback

Appends an element for a subset of a phrase to the current sequence of grammar elements.

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

Syntax

Visual Basic (Declaration)
Public Sub Append ( _
    phrase As String, _
    subsetMatchingCriteria As SubsetMatchingMode _
)
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim phrase As String
Dim subsetMatchingCriteria As SubsetMatchingMode

instance.Append(phrase, subsetMatchingCriteria)
C#
public void Append(
    string phrase,
    SubsetMatchingMode subsetMatchingCriteria
)

Parameters

phrase
Type: System..::..String

The sequence of words to append.

subsetMatchingCriteria
Type: Microsoft.Speech.Recognition..::..SubsetMatchingMode

The matching mode the grammar uses to recognize the phrase.

Remarks

The subset element is added to the end of the current sequence of elements. For more information about building a speech recognition grammar using strings, see Use a String to Create a GrammarBuilder (Microsoft.Speech).

For detailed information on the use of subset matching modes, see Microsoft.Speech.Recognition..::..SubsetMatchingMode.

Examples

The following example creates a speech recognition grammar for each SubsetMatchingMode value. For example, the generated grammar OrderedSubset recognizes the phrases, "three four five" and "one three five", and the grammar Subsequence recognizes the phrase "three four five", but not the phrase, "one three five".

C# Copy image Copy Code
private Grammar[] CreateSubsetMatchTest()
{
  List<Grammar> grammars = new List<Grammar>(4);

  string phrase = "one two three four five six";
  foreach (SubsetMatchingMode mode in
    Enum.GetValues(typeof(SubsetMatchingMode)))
  {
    GrammarBuilder gb = new GrammarBuilder();
    gb.Append(phrase, mode);

    Grammar grammar = new Grammar(gb);
    grammar.Name = mode.ToString();
    grammars.Add(grammar);
  }

  return grammars.ToArray();
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Append Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Append Method (String, Int32, Int32)

[image]

GrammarBuilder..::..Append Method (String, Int32, Int32)
GrammarBuilder Class Example See Also Send Feedback

Appends a repeated phrase to the current sequence of grammar elements.

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

Syntax

Visual Basic (Declaration)
Public Sub Append ( _
    phrase As String, _
    minRepeat As Integer, _
    maxRepeat As Integer _
)
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim phrase As String
Dim minRepeat As Integer
Dim maxRepeat As Integer

instance.Append(phrase, minRepeat, maxRepeat)
C#
public void Append(
    string phrase,
    int minRepeat,
    int maxRepeat
)

Parameters

phrase
Type: System..::..String

The repeated sequence of words to append.

minRepeat
Type: System..::..Int32

The minimum number of times that input matching phrase must occur to constitute a match.

maxRepeat
Type: System..::..Int32

The maximum number of times that input matching phrase can occur to constitute a match.

Remarks

The value of minRepeat must be greater than or equal to 0 and less than or equal to the value of maxRepeat.

Examples

The following example creates a speech recognition grammar for phrases such as "Call James at work" and "Call Anne on her cell phone", where the word "phone" is optional. GrammarBuilder and Choices objects are used to construct the grammar. The example highlights the use of the Append method.

C# Copy image Copy Code
public static Grammar CreatePhonePhrase()
{
  // Create alternatives for person names, locations, devices, and pronouns.
  Choices personChoice = new Choices(new string[] {"Anne", "James", "Mary", "Sam"});
  Choices locationChoice = new Choices(new string[] {"home", "work"});
  Choices deviceChoice = new Choices(new string[] {"home", "work", "cell"});
  Choices pronounChoice = new Choices(new string[] {"his", "her"});

  // Create a phrase for the receiving device, which optionally contains the word "phone".
  GrammarBuilder devicePhrase = new GrammarBuilder(pronounChoice);
  devicePhrase.Append(deviceChoice);
  devicePhrase.Append("phone", 0, 1);

  // Create alternatives for phrases specifying a device or a location.
  GrammarBuilder atLocation = new GrammarBuilder("at");
  atLocation.Append(locationChoice);

  GrammarBuilder onDevice = new GrammarBuilder("on");
  onDevice.Append(devicePhrase);

  Choices howChoice = new Choices(new GrammarBuilder[] {atLocation, onDevice});

  // Build the final phrase.
  GrammarBuilder callWho = new GrammarBuilder("Call");
  callWho.Append(personChoice);
  callWho.Append(howChoice);

  // Create the Grammar object.
  Grammar callGrammar = new Grammar(callWho);
  callGrammar.Name = "Call Grammar";

  return callGrammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Append Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Append Method (GrammarBuilder, Int32, Int32)

[image]

GrammarBuilder..::..Append Method (GrammarBuilder, Int32, Int32)
GrammarBuilder Class Example See Also Send Feedback

Appends a repeated grammar element to the current sequence of grammar elements.

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

Syntax

Visual Basic (Declaration)
Public Sub Append ( _
    builder As GrammarBuilder, _
    minRepeat As Integer, _
    maxRepeat As Integer _
)
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim builder As GrammarBuilder
Dim minRepeat As Integer
Dim maxRepeat As Integer

instance.Append(builder, minRepeat, maxRepeat)
C#
public void Append(
    GrammarBuilder builder,
    int minRepeat,
    int maxRepeat
)

Parameters

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The repeated grammar element to append.

minRepeat
Type: System..::..Int32

The minimum number of times that input matching the element defined by builder must occur to constitute a match.

maxRepeat
Type: System..::..Int32

The maximum number of times that input matching the element defined by builder can occur to constitute a match.

Remarks

The value of minRepeat must be greater than or equal to 0 and less than or equal to the value of maxRepeat.

Important note Important

When you specify repeats for a GrammarBuilder object that contains SemanticResultValue or SemanticResultKey instances, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example creates a speech recognition grammar for phrases such as "Call James at work" and "Call Anne on her cell phone", where the word "phone" is optional. GrammarBuilder and Choices objects are used to construct the grammar. The example highlights the use of the Append method.

C# Copy image Copy Code
public static Grammar CreatePhonePhrase()
{
  // Create alternatives for person names, locations, devices, and pronouns.
  Choices personChoice = new Choices(new string[] {"Anne", "James", "Mary", "Sam"});
  Choices locationChoice = new Choices(new string[] {"home", "work"});
  Choices deviceChoice = new Choices(new string[] {"home", "work", "cell"});
  Choices pronounChoice = new Choices(new string[] {"his", "her"});

  // Create a phrase for the receiving device, which optionally contains the word "phone".
  GrammarBuilder devicePhrase = new GrammarBuilder(pronounChoice);
  devicePhrase.Append(deviceChoice);
  devicePhrase.Append("phone", 0, 1);

  // Create alternatives for phrases specifying a device or a location.
  GrammarBuilder atLocation = new GrammarBuilder("at");
  atLocation.Append(locationChoice);

  GrammarBuilder onDevice = new GrammarBuilder("on");
  onDevice.Append(devicePhrase);

  Choices howChoice = new Choices(new GrammarBuilder[] {atLocation, onDevice});

  // Build the final phrase.
  GrammarBuilder callWho = new GrammarBuilder("Call");
  callWho.Append(personChoice);
  callWho.Append(howChoice);

  // Create the Grammar object.
  Grammar callGrammar = new Grammar(callWho);
  callGrammar.Name = "Call Grammar";

  return callGrammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Append Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendDictation Method

[image] [image]

GrammarBuilder..::..AppendDictation Method
GrammarBuilder Class See Also Send Feedback

Appends grammar logic to provide access to free text dictation grammars.

Overload List

 | Name | Description
Public method | AppendDictation()()()() | Appends grammar logic to provide access the default, free-text, dictation grammar provided by the Microsoft Speech Platform SDK 11.
Public method | AppendDictation(String) | Appends grammar logic to provide access to a special-function dictation grammar specified by a string.
Top

Remarks

The AppendDictation overloads provide applications with access to the default, free-text, dictation grammar provided by the Microsoft Speech Platform SDK 11.

For more information on special function, free-text, dictation grammars, see #ctor(String)).

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendDictation Method

[image]

GrammarBuilder..::..AppendDictation Method
GrammarBuilder Class Example See Also Send Feedback

Appends grammar logic to provide access the default, free-text, dictation grammar provided by the Microsoft Speech Platform SDK 11.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendDictation
Visual Basic (Usage)
Dim instance As GrammarBuilder

instance.AppendDictation()
C#
public void AppendDictation()

Remarks

A GrammarBuilder object that appends a dictation grammar using the AppendDictation()()()() method can be combined with a GrammarBuilder that specifies SemanticResultValue and SemanticResultKey objects.

Examples

The following example creates a Grammar that accepts free-speech dictation. The grammar is constructed from two GrammarBuilder instances; one supports the commands "start dictation" and "stop dictation", the other appends a free-text dictation grammar using the AppendDictation method. The dictation result will be obtainable from the Value property of SemanticValue instance returned with a recognized phrase and accessed with the tag "DictationInput".

C# Copy image Copy Code
private void freeTextDictation(){
    GrammarBuilder startStop = new GrammarBuilder();
    GrammarBuilder dictation = new GrammarBuilder();
    dictation.AppendDictation();

    startStop.Append(new SemanticResultKey("StartDictation", new SemanticResultValue("Start Dictation",true)));
    startStop.Append(new SemanticResultKey("DictationInput", dictation));
    startStop.Append(new SemanticResultKey("StopDictation", new SemanticResultValue("Stop Dictation", false)));
    Grammar grammar=new Grammar(startStop);
    grammar.Enabled=true;
    grammar.Name=" Free-Text Dictation ";
    _recognizer.LoadGrammar(grammar);

}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
AppendDictation Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendDictation Method (String)

[image]

GrammarBuilder..::..AppendDictation Method (String)
GrammarBuilder Class Example See Also Send Feedback

Appends grammar logic to provide access to a special-function dictation grammar specified by a string.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendDictation ( _
    category As String _
)
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim category As String

instance.AppendDictation(category)
C#
public void AppendDictation(
    string category
)

Parameters

category
Type: System..::..String

A String indicating the type of special-function dictation grammar to be appended.

Remarks

Special-function dictation grammars are specified within the Microsoft Speech Platform SDK 11 with a special URI syntax of the form grammar:dictation#topic.

The category argument supplies a value to the #topic qualifier in these URIs.

Currently, only one category is supported: "spelling".

A GrammarBuilder with an appended dictation grammar may also incorporate SemanticResultValue and SemanticResultKey objects.

Examples

The example below creates a Grammar that accepts both free-text dictation, and the spelling of words using individual letters.

The free-text dictation features, triggered by the command "start dictation" and terminated by the command "stop dictation", are built with the GrammarBuilder instance startStop.

The spelling is implemented by appending the special-function spelling grammar to the GrammarBuilder instance spellingGB, using the AppendDictation(String) method. The free-text and spelling features are combined in the GrammarBuilder instance both, which is used to construct the Grammar object.

The result will be obtainable from the Value property of SemanticValue instance returned with a recognized phrase and accessed with the tag "spellingInput".

C# Copy image Copy Code
private void DictaphoneSpellingGrammar(){

    GrammarBuilder startStop = new GrammarBuilder();
    GrammarBuilder dictation = new GrammarBuilder();
    dictation.AppendDictation();

    startStop.Append(new SemanticResultKey("StartDictation", new SemanticResultValue("Start Dictation",true)));
    startStop.Append(new SemanticResultKey("DictationInput", dictation));
    startStop.Append(new SemanticResultKey("EndDictation", new SemanticResultValue("Stop Dictation", false)));

    GrammarBuilder spelling = new GrammarBuilder();
    spelling.AppendDictation("spelling");
    GrammarBuilder spellingGB = new GrammarBuilder();
    spellingGB.Append(new SemanticResultKey("StartSpelling", new SemanticResultValue("Start Spelling",true)));
    spellingGB.Append(new SemanticResultKey("spellingInput", spelling));
    spellingGB.Append(new SemanticResultKey("StopSpelling", new SemanticResultValue("Stop Spelling", true)));

    GrammarBuilder both= GrammarBuilder.Add(startStop, spellingGB);

    Grammar grammar=new Grammar(both);
    grammar.Enabled=true;
    grammar.Name="Free-Text and Spelling Dictation";
    _recognizer.LoadGrammar(grammar);

}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
AppendDictation Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendRuleReference Method

[image] [image]

GrammarBuilder..::..AppendRuleReference Method
GrammarBuilder Class See Also Send Feedback

Appends a grammar file or a grammar rule to the current sequence of grammar elements.

Overload List

 | Name | Description
Public method | AppendRuleReference(String) | Appends a grammar definition file to the current sequence of grammar elements.
Public method | AppendRuleReference(String, String) | Appends the specified rule of a grammar definition file to the current sequence of grammar elements.
Top

Remarks

The AppendRuleReference methods can append a grammar file or a grammar rule from a file. These methods allow applications to make use of pre-deployed or publicly available grammar rules. The application must have read access to the location of specified grammar files.

These methods can read a speech recognition grammar from the following formats.

  • XML-format files that conform to the W3C Speech Recognition Grammar Specification (SRGS) Version 1.0

  • Binary files that conform to the Microsoft Speech Recognition Grammar Binary Format (.cfg file extension)

Compiling an XML-format SRGS grammar file to a binary grammar file with the .cfg extension can reduce the time consumed by searches for a match, especially if the grammar requires recognition of a large number of words and phrases. For information about compiling SRGS grammars to the CFG binary format, see SrgsGrammarCompiler.

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendRuleReference Method (String)

[image]

GrammarBuilder..::..AppendRuleReference Method (String)
GrammarBuilder Class Example See Also Send Feedback

Appends a grammar definition file to the current sequence of grammar elements.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendRuleReference ( _
    path As String _
)
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim path As String

instance.AppendRuleReference(path)
C#
public void AppendRuleReference(
    string path
)

Parameters

path
Type: System..::..String

A String containing the path or Universal Resource Identifier (URI) of the file that describes a speech recognition grammar in a supported format.

Remarks

The URI provided by the path argument may be local or remote. The application must have read access to the location of specified grammar files.

A W3C Speech Recognition Grammar Specification (SRGS) representation can define a root rule. This method appends the grammar, beginning with its root rule, to the current sequence of grammar elements. To append a specific grammar rule, use the AppendRuleReference(String, String) method.

Examples

The following C# example creates a speech recognition grammar that uses the rule named Cities in a local SRGS file, cities.grxml. The content of the cities.grxml file appears below the C# code example.

C# Copy image Copy Code
private static Grammar CreateCitiesGrammar1()
{
  GrammarBuilder builder = new GrammarBuilder();
  builder.AppendRuleReference("file://c:/temp/cities.grxml");

  Grammar citiesGrammar = new Grammar(builder);
  citiesGrammar.Name = "Cities Grammar 1";
  return citiesGrammar;
}
XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-16" ?>
<grammar version="1.0" xml:lang="en-US"
         xmlns="http://www.w3.org/2001/06/grammar"
         tag-format="semantics/1.0" root="Main">

  <!-- cities.grxml:
    Defines an SRGS grammar for requesting a flight. This grammar includes
    a Cities rule that lists the cities that can be used for departures
    and destinations. -->

  <rule id="Main">
    <item>
      I would like to fly from <ruleref uri="#Cities"/>
      to <ruleref uri="#Cities"/>
    </item>
  </rule>

  <rule id="Cities" scope="public">
    <one-of>
      <item> Seattle </item>
      <item> Los Angeles </item>
      <item> New York </item>
      <item> Miami </item>
    </one-of>
  </rule>
</grammar>

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
AppendRuleReference Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendRuleReference Method (String, String)

[image]

GrammarBuilder..::..AppendRuleReference Method (String, String)
GrammarBuilder Class Example See Also Send Feedback

Appends the specified rule of a grammar definition file to the current sequence of grammar elements.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendRuleReference ( _
    path As String, _
    rule As String _
)
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim path As String
Dim rule As String

instance.AppendRuleReference(path, rule)
C#
public void AppendRuleReference(
    string path,
    string rule
)

Parameters

path
Type: System..::..String

A String containing the file path or Universal Resource Identifier (URI) of the file that describes a speech recognition grammar in a supported format.

rule
Type: System..::..String

The identifier of the rule to append, or nullNothingnullptrunita null reference (Nothing in Visual Basic) to append the default root rule of the grammar file.

Remarks

The URI provided by the path argument may be local or remote. The application must have read access to the location of specified grammar files.

You can use the use the AppendRuleReference(String) method to append a grammar file beginning with its root rule.

Examples

The following C# example creates a speech recognition grammar that uses the rule named Cities in a local SRGS file, cities.grxml. The content of the cities.grxml file appears below the C# code example.

C# Copy image Copy Code
private static Grammar CreateCitiesGrammar2()
{
  GrammarBuilder builder = new GrammarBuilder();
  builder.Append("Does");
  builder.AppendRuleReference(@"c:\temp\cities.grxml", "Cities");
  builder.Append("have a shuttle");

  Grammar citiesGrammar = new Grammar(builder);
  citiesGrammar.Name = "Cities Grammar 2";
  return citiesGrammar;
}
XML Copy image Copy Code
<?xml version="1.0" encoding="UTF-8" ?>
<grammar version="1.0" xml:lang="en-US"
         xmlns="http://www.w3.org/2001/06/grammar"
         tag-format="semantics/1.0" root="Main">

  <!-- cities.grxml:
    Defines an SRGS grammar for requesting a flight. This grammar includes
    a Cities rule that lists the cities that can be used for departures
    and destinations. -->

  <rule id="Main">
    <item>
      I would like to fly from <ruleref uri="#Cities"/>
      to <ruleref uri="#Cities"/>
    </item>
  </rule>

  <rule id="Cities" scope="public">
    <one-of>
      <item> Seattle </item>
      <item> Los Angeles </item>
      <item> New York </item>
      <item> Miami </item>
    </one-of>
  </rule>
</grammar>

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
AppendRuleReference Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendWildcard Method

[image]

GrammarBuilder..::..AppendWildcard Method
GrammarBuilder Class Example See Also Send Feedback

Appends a recognition grammar element that matches any input to the current sequence of grammar elements.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendWildcard
Visual Basic (Usage)
Dim instance As GrammarBuilder

instance.AppendWildcard()
C#
public void AppendWildcard()

Remarks

The wildcard element is added to the end of the current sequence of elements.

The wildcard element matches any spoken word. It does not match background noise or silence.

Examples

The following example creates a grammar that accepts password input as a wildcard. The example attaches a Grammar..::..SpeechRecognized event handler to the grammar that validates the password input.

C# Copy image Copy Code
private Grammar CreatePasswordGrammar()
{
  GrammarBuilder wildcardBuilder = new GrammarBuilder();
  wildcardBuilder.AppendWildcard();
  SemanticResultKey passwordKey =
    new SemanticResultKey("Password", wildcardBuilder);

  GrammarBuilder passwordBuilder =
    new GrammarBuilder("My Password is");
  passwordBuilder.Append(passwordKey);

  Grammar passwordGrammar = new Grammar(passwordBuilder);
  passwordGrammar.Name = "Password input";

  passwordGrammar.SpeechRecognized +=
    new EventHandler<SpeechRecognizedEventArgs>(
      PasswordInputHandler);

  return passwordGrammar;
}

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

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

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

    if (IsValidPassword(passwordAudio))
    {
      Console.WriteLine("Password accepted.");

      // Add code to handle a valid password here.
    }
    else
    {
      Console.WriteLine("Invalid password.");

      // Add code to handle an invalid password here.
    }
  }
}

// Validate the password input.
private bool IsValidPassword(RecognizedAudio passwordAudio)
{
  Console.WriteLine("Validating password.");

  // Add password validation code here.

  return false;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Operators and Type Conversions

[image] [image]

GrammarBuilder Operators and Type Conversions
GrammarBuilder Class See Also Send Feedback

Operators

Name | Description
Addition(String, GrammarBuilder) | Creates a new GrammarBuilder that contains a phrase followed by a GrammarBuilder.
Addition(Choices, GrammarBuilder) | Creates a new GrammarBuilder that contains a Choices object followed by a GrammarBuilder object.
Addition(GrammarBuilder, Choices) | Creates a new GrammarBuilder that contains a GrammarBuilder followed by a Choices.
Addition(GrammarBuilder, GrammarBuilder) | Creates a new GrammarBuilder that contains a sequence of two GrammarBuilder objects.
Addition(GrammarBuilder, String) | Creates a new GrammarBuilder that contains a GrammarBuilder followed by a phrase.
ImplicitWideningImplicitImplicitImplicit(String to GrammarBuilder) | Implicitly converts a String object to an instance of GrammarBuilder.
ImplicitWideningImplicitImplicitImplicit(Choices to GrammarBuilder) | Converts a Choices object to a GrammarBuilder object.
ImplicitWideningImplicitImplicitImplicit(SemanticResultKey to GrammarBuilder) | Converts a SemanticResultKey object to a GrammarBuilder object.
ImplicitWideningImplicitImplicitImplicit(SemanticResultValue to GrammarBuilder) | Converts a SemanticResultValue object to a GrammarBuilder object.
Top

See Also

Reference

GrammarBuilder Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Addition Operator

[image] [image]

GrammarBuilder..::..Addition Operator
GrammarBuilder Class See Also Send Feedback

Creates a new GrammarBuilder that corresponds to a sequence of two grammar elements.

Overload List

Name | Description
Addition(String, GrammarBuilder) | Creates a new GrammarBuilder that contains a phrase followed by a GrammarBuilder.
Addition(Choices, GrammarBuilder) | Creates a new GrammarBuilder that contains a Choices object followed by a GrammarBuilder object.
Addition(GrammarBuilder, Choices) | Creates a new GrammarBuilder that contains a GrammarBuilder followed by a Choices.
Addition(GrammarBuilder, GrammarBuilder) | Creates a new GrammarBuilder that contains a sequence of two GrammarBuilder objects.
Addition(GrammarBuilder, String) | Creates a new GrammarBuilder that contains a GrammarBuilder followed by a phrase.
Top

Remarks

The order of the operands determines the order of the elements in the new GrammarBuilder.

Important note Important

Caution is recommended when combining Choices or GrammarBuilder objects that contain SemanticResultValue or SemanticResultKey instances with other grammar elements. The speech recognizer can throw an exception when using a speech recognition grammar that contains duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the value of the same semantic element. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

For more information about building and using speech recognition grammars, see Speech Recognition (Microsoft.Speech) and Create Grammars Using GrammarBuilder (Microsoft.Speech).

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Addition Operator (String, GrammarBuilder)

[image]

GrammarBuilder..::..Addition Operator (String, GrammarBuilder)
GrammarBuilder Class Example See Also Send Feedback

Creates a new GrammarBuilder that contains a phrase followed by a GrammarBuilder.

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

Syntax

Visual Basic (Declaration)
Public Shared Operator + ( _
    phrase As String, _
    builder As GrammarBuilder _
) As GrammarBuilder
Visual Basic (Usage)
Dim phrase As String
Dim builder As GrammarBuilder
Dim returnValue As GrammarBuilder

returnValue = (phrase + builder)
C#
public static GrammarBuilder operator +(
    string phrase,
    GrammarBuilder builder
)

Parameters

phrase
Type: System..::..String

The first grammar element, which represents a sequence of words.

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The second grammar element.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

Returns a GrammarBuilder for the sequence of the phrase parameter followed by the builder parameter.

Remarks

GrammarBuilder supports conversions from the following classes.

  • Choices

  • SemanticResultKey

  • SemanticResultValue

  • String

This method accepts the objects listed above for the builder parameter. For more information, see the ImplicitWideningImplicitImplicitImplicit operators.

Examples

The following example creates a speech recognition grammar that can recognize the two phrases, "Make background color" and "Set background to color", where color is selected from a set of colors. Various types are used to build the final grammar, such as String, Choices, and GrammarBuilder objects.

C# Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  Choices colorChoice = new Choices(new string[] { "red", "green", "blue" });

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase =
    (GrammarBuilder)"Make background" + colorChoice;
  GrammarBuilder setPhrase =
    "Set background to" + (GrammarBuilder)colorChoice;

  // Create a Choices for the two alternative phrases, convert the Choices
  // to a GrammarBuilder, and construct the Grammar object from the result.
  Choices bothChoices = new Choices(new GrammarBuilder[] { makePhrase, setPhrase });
  GrammarBuilder bothPhrases = new GrammarBuilder(bothChoices);

  Grammar grammar = new Grammar(bothPhrases);
  grammar.Name = "backgroundColor";
  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Addition Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Addition Operator (Choices, GrammarBuilder)

[image]

GrammarBuilder..::..Addition Operator (Choices, GrammarBuilder)
GrammarBuilder Class See Also Send Feedback

Creates a new GrammarBuilder that contains a Choices object followed by a GrammarBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Shared Operator + ( _
    choices As Choices, _
    builder As GrammarBuilder _
) As GrammarBuilder
Visual Basic (Usage)
Dim choices As Choices
Dim builder As GrammarBuilder
Dim returnValue As GrammarBuilder

returnValue = (choices + builder)
C#
public static GrammarBuilder operator +(
    Choices choices,
    GrammarBuilder builder
)

Parameters

choices
Type: Microsoft.Speech.Recognition..::..Choices

The first grammar element, which represents a set of alternatives.

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The second grammar element.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

Returns a GrammarBuilder for the sequence of the choices parameter followed by the builder parameter.

Remarks

GrammarBuilder supports conversions from the following classes.

  • Choices

  • SemanticResultKey

  • SemanticResultValue

  • String

This method accepts the objects listed above for the builder parameter. For more information, see the ImplicitWideningImplicitImplicitImplicit operators.

Important note Important

When you combine Choices or GrammarBuilder objects that contain SemanticResultValue or SemanticResultKey instances, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Addition Overload
Microsoft.Speech.Recognition Namespace
Add
ImplicitWideningImplicitImplicitImplicit(Choices to GrammarBuilder)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Addition Operator (GrammarBuilder, Choices)

[image]

GrammarBuilder..::..Addition Operator (GrammarBuilder, Choices)
GrammarBuilder Class Example See Also Send Feedback

Creates a new GrammarBuilder that contains a GrammarBuilder followed by a Choices.

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

Syntax

Visual Basic (Declaration)
Public Shared Operator + ( _
    builder As GrammarBuilder, _
    choices As Choices _
) As GrammarBuilder
Visual Basic (Usage)
Dim builder As GrammarBuilder
Dim choices As Choices
Dim returnValue As GrammarBuilder

returnValue = (builder + choices)
C#
public static GrammarBuilder operator +(
    GrammarBuilder builder,
    Choices choices
)

Parameters

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The first grammar element.

choices
Type: Microsoft.Speech.Recognition..::..Choices

The second grammar element, which represents a set of alternative elements.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

Returns a GrammarBuilder for the sequence of the builder parameter followed by the choices parameter.

Remarks

GrammarBuilder supports conversions from the following classes:

  • Choices

  • SemanticResultKey

  • SemanticResultValue

  • String

This method accepts the objects listed above for the builder parameter. For more information, see the ImplicitWideningImplicitImplicitImplicit operators.

Important note Important

When you combine Choices or GrammarBuilder objects that contain SemanticResultValue or SemanticResultKey instances, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

Examples

The following example creates a speech recognition grammar that can recognize the two phrases, "Make background color" and "Set background to color", where color is selected from a set of colors. Various types are used to build the final grammar, such as String, Choices, and GrammarBuilder objects.

C# Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  Choices colorChoice = new Choices(new string[] { "red", "green", "blue" });

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase =
    (GrammarBuilder)"Make background" + colorChoice;
  GrammarBuilder setPhrase =
    "Set background to" + (GrammarBuilder)colorChoice;

  // Create a Choices for the two alternative phrases, convert the Choices
  // to a GrammarBuilder, and construct the grammar from the result.
  Choices bothChoices = new Choices(new GrammarBuilder[] { makePhrase, setPhrase });
  GrammarBuilder bothPhrases = new GrammarBuilder(bothChoices);

  Grammar grammar = new Grammar(bothPhrases);
  grammar.Name = "backgroundColor";
  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Addition Overload
Microsoft.Speech.Recognition Namespace
Add
ImplicitWideningImplicitImplicitImplicit
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Addition Operator (GrammarBuilder, GrammarBuilder)

[image]

GrammarBuilder..::..Addition Operator (GrammarBuilder, GrammarBuilder)
GrammarBuilder Class See Also Send Feedback

Creates a new GrammarBuilder that contains a sequence of two GrammarBuilder objects.

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

Syntax

Visual Basic (Declaration)
Public Shared Operator + ( _
    builder1 As GrammarBuilder, _
    builder2 As GrammarBuilder _
) As GrammarBuilder
Visual Basic (Usage)
Dim builder1 As GrammarBuilder
Dim builder2 As GrammarBuilder
Dim returnValue As GrammarBuilder

returnValue = (builder1 + builder2)
C#
public static GrammarBuilder operator +(
    GrammarBuilder builder1,
    GrammarBuilder builder2
)

Parameters

builder1
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The first grammar element.

builder2
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The second grammar element.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

Returns a GrammarBuilder for the sequence of the builder1 parameter followed by the builder2 parameter.

Remarks

GrammarBuilder supports conversions from the following classes.

  • Choices

  • SemanticResultKey

  • SemanticResultValue

  • String

This method accepts the objects listed above for the builder1 and builder2 parameters. For more information, see the ImplicitWideningImplicitImplicitImplicit operators.

Important note Important

When you combine GrammarBuilder objects that contain SemanticResultValue or SemanticResultKey instances, make sure you avoid creating duplicate semantic elements with the same key name or multiple semantic elements that could repeatedly modify the Value property of a SemanticValue object. The speech recognizer can throw an exception if it encounters these circumstances. For more information about building a speech recognition grammar that contains semantic information, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech).

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Addition Overload
Microsoft.Speech.Recognition Namespace
Add
ImplicitWideningImplicitImplicitImplicit
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Addition Operator (GrammarBuilder, String)

[image]

GrammarBuilder..::..Addition Operator (GrammarBuilder, String)
GrammarBuilder Class See Also Send Feedback

Creates a new GrammarBuilder that contains a GrammarBuilder followed by a phrase.

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

Syntax

Visual Basic (Declaration)
Public Shared Operator + ( _
    builder As GrammarBuilder, _
    phrase As String _
) As GrammarBuilder
Visual Basic (Usage)
Dim builder As GrammarBuilder
Dim phrase As String
Dim returnValue As GrammarBuilder

returnValue = (builder + phrase)
C#
public static GrammarBuilder operator +(
    GrammarBuilder builder,
    string phrase
)

Parameters

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The first grammar element.

phrase
Type: System..::..String

The second grammar element, which represents a sequence of words.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

Returns a GrammarBuilder for the sequence of the builder parameter followed by the phrase parameter.

Remarks

GrammarBuilder supports conversions from the following classes.

  • Choices

  • SemanticResultKey

  • SemanticResultValue

  • String

This method accepts the objects listed above for the builder parameter. For more information, see the ImplicitWideningImplicitImplicitImplicit operators.

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Addition Overload
Microsoft.Speech.Recognition Namespace
Add
ImplicitWideningImplicitImplicitImplicit
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Implicit Conversion Operators

[image] [image]

GrammarBuilder ImplicitWideningImplicitImplicitImplicit Conversion Operators
GrammarBuilder Class See Also Send Feedback

Converts another type to a GrammarBuilder.

Overload List

Name | Description
ImplicitWideningImplicitImplicitImplicit(String to GrammarBuilder) | Implicitly converts a String object to an instance of GrammarBuilder.
ImplicitWideningImplicitImplicitImplicit(Choices to GrammarBuilder) | Converts a Choices object to a GrammarBuilder object.
ImplicitWideningImplicitImplicitImplicit(SemanticResultKey to GrammarBuilder) | Converts a SemanticResultKey object to a GrammarBuilder object.
ImplicitWideningImplicitImplicitImplicit(SemanticResultValue to GrammarBuilder) | Converts a SemanticResultValue object to a GrammarBuilder object.
Top

Remarks

Implicit conversion creates a new instance of GrammarBuilder. You can cast each of the following classes to a GrammarBuilder.

  • Choices

  • SemanticResultKey

  • SemanticResultValue

  • String

Each of the implicit casts is equivalent to calling the constructor.

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Microsoft.Speech.Recognition Namespace
GrammarBuilder
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Implicit Conversion (String to GrammarBuilder)

[image]

GrammarBuilder ImplicitWideningImplicitImplicitImplicit Conversion (String to GrammarBuilder)
GrammarBuilder Class Example See Also Send Feedback

Implicitly converts a String object to an instance of GrammarBuilder.

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

Syntax

Visual Basic (Declaration)
Public Shared Widening Operator CType ( _
    phrase As String _
) As GrammarBuilder
Visual Basic (Usage)
Dim input As String
Dim output As GrammarBuilder

output = CType(input, GrammarBuilder)
C#
public static implicit operator GrammarBuilder (
    string phrase
)

Parameters

phrase
Type: System..::..String

Valid instance of String to be implicitly converted to a containing GrammarBuilder object.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

Returns an instance of SemanticResultValue containing the logical choice defined by the phrase argument.

Examples

The following example uses GrammarBuilder and Choices objects to construct a grammar that can recognize either of the two phrases, "Make background colorChoice" or "Set background to colorChoice".

After creating a list of acceptable values for colorChoice using a Choices object, the example initializes two GrammarBuilder objects, makePhrase and setPhrase, using implicit conversion from string objects.

The example finally creates a Grammar object from a Choices object cast to a GrammarBuilder object.

C# Copy image Copy Code
private Grammar CreateColorGrammar()
{

  // Create a set of color choices.
  Choices colorChoice = new Choices(new string[] {"red", "green", "blue"});
  GrammarBuilder colorElement = new GrammarBuilder(colorChoice);

  // Create grammar builders for the two versions of the phrase.
  GrammarBuilder makePhrase = new GrammarBuilder("Make background");
  makePhrase.Append(colorElement);
  GrammarBuilder setPhrase = new GrammarBuilder("Set background to");
  setPhrase.Append(colorElement);

  // Create a Choices for the two alternative phrases, convert the Choices
  // to a GrammarBuilder, and construct the Grammar object from the result.
  Choices bothChoices = new Choices(new GrammarBuilder[] {makePhrase, setPhrase});
  Grammar grammar = new Grammar((GrammarBuilder)bothChoices);
  grammar.Name = "backgroundColor";
  return grammar;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
ImplicitWideningImplicitImplicitImplicit Overload
Microsoft.Speech.Recognition Namespace
GrammarBuilder
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Implicit Conversion (Choices to GrammarBuilder)

[image]

GrammarBuilder ImplicitWideningImplicitImplicitImplicit Conversion (Choices to GrammarBuilder)
GrammarBuilder Class Example See Also Send Feedback

Converts a Choices object to a GrammarBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Shared Widening Operator CType ( _
    choices As Choices _
) As GrammarBuilder
Visual Basic (Usage)
Dim input As Choices
Dim output As GrammarBuilder

output = CType(input, GrammarBuilder)
C#
public static implicit operator GrammarBuilder (
    Choices choices
)

Parameters

choices
Type: Microsoft.Speech.Recognition..::..Choices

The set of alternatives to convert.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The converted Choices object.

Remarks

Implicit conversion creates a new instance of GrammarBuilder.This conversion operator is equivalent to calling GrammarBuilder(Choices) and specifying choices for the alternateChoices.

Examples

The following example creates a speech recognition grammar that can recognize a response to a "yes" or "no" question. The implicit conversion operator is used in the construction of a SemanticResultValue object from a Choices object, in the construction of a Choices object from two SemanticResultValue objects, and in the construction of a Grammar object from a SemanticResultKey object.

C# Copy image Copy Code
Choices yesChoices = new Choices(new string[] {"yes", "yup", "yah"});
SemanticResultValue yesValue =
  new SemanticResultValue(yesChoices, true);

Choices noChoices = new Choices(new string[] { "no", "nope", "nah" });
SemanticResultValue noValue =
  new SemanticResultValue(noChoices, false);

SemanticResultKey yesnoKey =
  new SemanticResultKey("yesno", new Choices(new GrammarBuilder[] { yesValue, noValue }));

Grammar yesnoGrammar = new Grammar(yesnoKey);
yesnoGrammar.Name = "yesno";

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
ImplicitWideningImplicitImplicitImplicit Overload
Microsoft.Speech.Recognition Namespace
GrammarBuilder
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Implicit Conversion (SemanticResultKey to GrammarBuilder)

[image]

GrammarBuilder ImplicitWideningImplicitImplicitImplicit Conversion (SemanticResultKey to GrammarBuilder)
GrammarBuilder Class Example See Also Send Feedback

Converts a SemanticResultKey object to a GrammarBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Shared Widening Operator CType ( _
    semanticKey As SemanticResultKey _
) As GrammarBuilder
Visual Basic (Usage)
Dim input As SemanticResultKey
Dim output As GrammarBuilder

output = CType(input, GrammarBuilder)
C#
public static implicit operator GrammarBuilder (
    SemanticResultKey semanticKey
)

Parameters

semanticKey
Type: Microsoft.Speech.Recognition..::..SemanticResultKey

The semantic key to convert.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The converted SemanticResultKey object.

Remarks

Implicit conversion creates a new instance of GrammarBuilder. This conversion operator is equivalent to calling GrammarBuilder(SemanticResultKey) and specifying semanticKey for the key.

Examples

The following example creates a speech recognition grammar that can recognize a response to a "yes" or "no" question. The implicit conversion operator is used in the construction of a SemanticResultValue object from a Choices object, in the construction of a Choices object from two SemanticResultValue objects, and in the construction of a Grammar object from a SemanticResultKey object.

C# Copy image Copy Code
Choices yesChoices = new Choices(new string[] {"yes", "yup", "yah"});
SemanticResultValue yesValue =
  new SemanticResultValue(yesChoices, true);

Choices noChoices = new Choices(new string[] { "no", "nope", "nah" });
SemanticResultValue noValue =
  new SemanticResultValue(noChoices, false);

SemanticResultKey yesnoKey =
  new SemanticResultKey("yesno", new Choices(new GrammarBuilder[] { yesValue, noValue }));

Grammar yesnoGrammar = new Grammar(yesnoKey);
yesnoGrammar.Name = "yesno";

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
ImplicitWideningImplicitImplicitImplicit Overload
Microsoft.Speech.Recognition Namespace
GrammarBuilder
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Implicit Conversion (SemanticResultValue to GrammarBuilder)

[image]

GrammarBuilder ImplicitWideningImplicitImplicitImplicit Conversion (SemanticResultValue to GrammarBuilder)
GrammarBuilder Class Example See Also Send Feedback

Converts a SemanticResultValue object to a GrammarBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Shared Widening Operator CType ( _
    semanticValue As SemanticResultValue _
) As GrammarBuilder
Visual Basic (Usage)
Dim input As SemanticResultValue
Dim output As GrammarBuilder

output = CType(input, GrammarBuilder)
C#
public static implicit operator GrammarBuilder (
    SemanticResultValue semanticValue
)

Parameters

semanticValue
Type: Microsoft.Speech.Recognition..::..SemanticResultValue

The SemanticResultValue object to convert.

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The converted SemanticResultValue object.

Remarks

Implicit conversion creates a new instance of GrammarBuilder. This conversion operator is equivalent to calling GrammarBuilder(SemanticResultValue) and specifying semanticValue for the value.

Examples

The following example creates a speech recognition grammar that can recognize a response to a "yes" or "no" question. The implicit conversion operator is used in the construction of a SemanticResultValue object from a Choicesobject, in the construction of a Choices object from two SemanticResultValue objects, and in the construction of a Grammar object from a SemanticResultKey object.

C# Copy image Copy Code
Choices yesChoices = new Choices(new string[] {"yes", "yup", "yah"});
SemanticResultValue yesValue =
  new SemanticResultValue(yesChoices, true);

Choices noChoices = new Choices(new string[] { "no", "nope", "nah" });
SemanticResultValue noValue =
  new SemanticResultValue(noChoices, false);

SemanticResultKey yesnoKey =
  new SemanticResultKey("yesno", new Choices(new GrammarBuilder[] { yesValue, noValue }));

Grammar yesnoGrammar = new Grammar(yesnoKey);
yesnoGrammar.Name = "yesno";

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
ImplicitWideningImplicitImplicitImplicit Overload
Microsoft.Speech.Recognition Namespace
GrammarBuilder
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarBuilder Properties

[image] [image]

GrammarBuilder Properties
GrammarBuilder Class See Also Send Feedback

The GrammarBuilder type exposes the following members.

Properties

 | Name | Description
Public property | Culture | Gets or sets the culture of the grammar.
Public property | DebugShowPhrases | Gets a string that shows the contents and structure of the grammar contained by the GrammarBuilder.
Top

See Also

Reference

GrammarBuilder Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Culture Property

[image]

GrammarBuilder..::..Culture Property
GrammarBuilder Class See Also Send Feedback

Gets or sets the culture of the grammar.

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

Syntax

Visual Basic (Declaration)
Public Property Culture As CultureInfo
    Get
    Set
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim value As CultureInfo

value = instance.Culture

instance.Culture = value
C#
public CultureInfo Culture { get; set; }

Property Value

Type: System.Globalization..::..CultureInfo

A CultureInfo object that represents the culture of the grammar.

Remarks

The Culture property of the GrammarBuilder is the only way to set the culture of a Grammar object that was constructed from a GrammarBuilder instance.

The Microsoft Speech Platform SDK 11 accepts all valid language-country codes as values for Culture. For a given language code specified in the Culture property, a speech recognition engine that supports that language code must be installed for the grammar to be loaded successfully.

If the Culture property specifies only a language code, (such as "en" for English or "es" for Spanish), and not a country/region code, then any installed recognizer that expresses support for that generic, region-independent language will be able to load the grammar. See Language Identifier Constants and Strings for a comprehensive list of language codes.

The Microsoft Speech Platform Runtime 11 and Speech Platform SDK 11 do not include any engines for speech recognition in a specific language. You must download a language pack (an engine for speech recognition in a specific language) for each language on which you want to perform speech recognition.

The language packs are different for each version of the Speech Platform Runtime. You must download the language pack version that matches the version of the Speech Platform Runtime that you have installed. The language packs for the Speech Platform SDK 11 are for server-based applications and are different than the languages that ship with Windows Vista or Windows 7. Use the following links to download the version of the server language packs that match your Speech Platform Runtime version:

  • Server Language Packs v11.0

  • Server Language Packs v10.2

  • Server Language Packs v10.1

  • Server Language Packs v10.0

See Language Support for a list of languages for which you can download language packs.

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DebugShowPhrases Property

[image]

GrammarBuilder..::..DebugShowPhrases Property
GrammarBuilder Class Example See Also Send Feedback

Gets a string that shows the contents and structure of the grammar contained by the GrammarBuilder.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property DebugShowPhrases As String
    Get
Visual Basic (Usage)
Dim instance As GrammarBuilder
Dim value As String

value = instance.DebugShowPhrases
C#
public string DebugShowPhrases { get; }

Property Value

Type: System..::..String

The current content and structure of the GrammarBuilder.

Examples

The following example is part of a console application for choosing origin and destination cities for a flight. The grammar recognizes phrases such as "I want to fly from Miami to Chicago." The grammar includes SemanticResultValue objects that assign airport codes to cities, and SemanticResultKey objects that distinguish between the origin and destination cities.

Using DebugShowPhrases to output the structure of the grammar produces the following results:

"I want to fly from origin=[[Chicago {ORD},Boston{BOS},Miami {MIA},Dallas {DFW}]] to destination=[[Chicago {ORD},Boston {BOS},Miami {MIA},Dallas {DFW}]]"

C# Copy image Copy Code
public static Grammar bookFlight()
{
  // Create GrammarBuilder objects and append SemanticResultValue objects
  // that contain cities and airport codes.
  GrammarBuilder chicago = new GrammarBuilder();
  chicago.Append(new SemanticResultValue("Chicago", "ORD"));

  GrammarBuilder boston = new GrammarBuilder();
  boston.Append(new SemanticResultValue("Boston", "BOS"));

  GrammarBuilder miami = new GrammarBuilder();
  miami.Append(new SemanticResultValue("Miami", "MIA"));

  GrammarBuilder dallas = new GrammarBuilder();
  dallas.Append(new SemanticResultValue("Dallas", "DFW"));

  // Create a Choices object and add the cities using implicit
  // conversion from SemanticResultValue to GrammarBuilder.
  Choices cities = new Choices();
  cities.Add(new Choices(new GrammarBuilder[] { chicago, boston, miami, dallas }));

  // Build the phrase and add SemanticResultKeys.
  GrammarBuilder chooseCities = new GrammarBuilder();
  chooseCities.Append("I want to fly from");
  chooseCities.Append(new SemanticResultKey("origin", cities));
  chooseCities.Append("to");
  chooseCities.Append(new SemanticResultKey("destination", cities));

  // Write the contents and structure of the GrammarBuilder to the console.
  Console.WriteLine("Grammar content and structure: {0}",     chooseCities.DebugShowPhrases);

  // Build a Grammar object from the GrammarBuilder.
  Grammar bookFlight = new Grammar(chooseCities);
  bookFlight.Name = "Book Flight";

  return bookFlight;
}

See Also

Reference

GrammarBuilder Class
GrammarBuilder Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarInfo Class

[image]

GrammarInfo Class
Members Example See Also Send Feedback

Represents an object that contains static information about a speech recognition grammar. In contrast, a Grammar object contains information about a speech recognition grammar that is loaded into a speech recognizer at run time.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..GrammarInfo

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

Syntax

Visual Basic (Declaration)
Public Class GrammarInfo _
    Implements IDisposable
Visual Basic (Usage)
Dim instance As GrammarInfo
C#
public class GrammarInfo : IDisposable

Remarks

You will typically use the GrammarInfo and GrammarInfoPartsCollection classes to optimize compiled grammars for the speech recognition engine that your application will use in production. Optimizing a compiled grammar for a specific speech recognition engine is called "preparing" the grammar file. Usually reserved for large grammars, preparing a grammar can reduce latency when an application loads the grammar.

You can compile grammars in the Microsoft Speech Platform SDK 11 from source files in XML format or from SrgsDocument objects, using one of the Compile()()()() methods. The result is a grammar file in binary format with the ".cfg" extension. You can also use the Compile Grammar tool (see Compile Grammar Reference Manual) to create CFG files from source grammars in XML and ARPA formats. Grammar files in CFG format can be loaded by any speech recognition engine in the Speech Platform SDK 11.

When you prepare a compiled grammar file, you add information (see AddEnginePart(SpeechRecognitionEngine)) to the file about a specific speech recognition engine. This information allows the specified speech recognition engine to most efficiently load the prepared grammar file.

A prepared grammar file carries the ".cfgpp" extension, to indicate that it has been prepared for a specific speech recognition engine. For example, if your source grammar file is MyGrammar.grxml, it will become MyGrammar.cfg after being compiled, and then MyGrammar.cfgpp after being prepared.

An EnginePart is information about a specific speech recognition engine which, when added to a grammar in CFG format, allows the engine to load the grammar in the most efficient manner possible.

Note Note

If a grammar is being fetched across the internet by a hosted speech recognition engine (for example, a hosted IVR service such as Tellme), the grammar should never be prepared by the developer. Instead, the grammar's optimization should remain at the CFG format. This allows the hosted speech recognizer to do the preparation of the grammar dynamically. For hosted IVR applications, grammars outside of the hosted platform should always be in source format (for example, GRXML) or optimized to CFG format.

Examples

The following gives an example of how to write a method that prepares a grammar.

Copy image Copy Code
private System.IO.Stream Prepare(System.IO.Stream cfgStream, String engineTokenName)
        {
            GrammarInfo cfg = null;
            SpeechRecognitionEngine srEngine = null;

            try
            {
                srEngine = new SpeechRecognitionEngine(engineTokenName);
            }
            catch
            {
                throw new ArgumentException("Invalid Engine Token Name: " + engineTokenName);
            }

            try
            {
              cfg  = new GrammarInfo(cfgStream);
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Invalid CFG stream: " + ex.Message);
            }

            if ((srEngine != null) && (cfgStream != null))
            {
                try
                {
                    cfg.ExtraParts.AddEnginePart(srEngine);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("Failed to Added Engine Part from " + engineTokenName + ": " + ex.Message);
                }

                try
                {
                    cfg.Save(cfgStream);
                }
                catch (Exception ex)
               {
                    throw new InvalidOperationException("Failed to serialize cfg stream: " + ex.Message);
                }
                return cfgStream;
            }
            else
            {
                throw new InvalidOperationException("SR Engine or CFG Stream are not valid");
            }

        }

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

GrammarInfo Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarInfo Members

[image] [image]

GrammarInfo Members
GrammarInfo Class Constructors Methods Properties See Also Send Feedback

Represents an object that contains static information about a speech recognition grammar. In contrast, a Grammar object contains information about a speech recognition grammar that is loaded into a speech recognizer at run time.

The GrammarInfo type exposes the following members.

Constructors

 | Name | Description
Public method | GrammarInfo(Stream) | Creates a new instance of the GrammarInfo class, using the grammar data in the specified stream object.
Public method | GrammarInfo(String) | Creates a new instance of the GrammarInfo class, using the grammar data in the specified file path.
Top

Properties

 | Name | Description
Public property | ExtraParts | Gets a GrammarInfoPartsCollection collection that contains information about a specific speech recognition engine.
Top

Methods

 | Name | Description
Public method | Dispose | Disposes the object.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | Save(Stream) | Saves the information in a GrammarInfo object to the specified stream.
Public method | Save(String) | Saves the information in a GrammarInfo object to the specified file path.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

GrammarInfo Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarInfo Constructor

[image] [image]

GrammarInfo Constructor
GrammarInfo Class See Also Send Feedback

Overload List

 | Name | Description
Public method | GrammarInfo(Stream) | Creates a new instance of the GrammarInfo class, using the grammar data in the specified stream object.
Public method | GrammarInfo(String) | Creates a new instance of the GrammarInfo class, using the grammar data in the specified file path.
Top

See Also

Reference

GrammarInfo Class
GrammarInfo Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarInfo Constructor (Stream)

[image]

GrammarInfo Constructor (Stream)
GrammarInfo Class See Also Send Feedback

Creates a new instance of the GrammarInfo class, using the grammar data in the specified stream object.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    stream As Stream _
)
Visual Basic (Usage)
Dim stream As Stream

Dim instance As New GrammarInfo(stream)
C#
public GrammarInfo(
    Stream stream
)

Parameters

stream
Type: System.IO..::..Stream

The stream from which to load the grammar information.

See Also

Reference

GrammarInfo Class
GrammarInfo Members
GrammarInfo Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarInfo Constructor (String)

[image]

GrammarInfo Constructor (String)
GrammarInfo Class See Also Send Feedback

Creates a new instance of the GrammarInfo class, using the grammar data in the specified file path.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    filePath As String _
)
Visual Basic (Usage)
Dim filePath As String

Dim instance As New GrammarInfo(filePath)
C#
public GrammarInfo(
    string filePath
)

Parameters

filePath
Type: System..::..String

The full path to the file.

See Also

Reference

GrammarInfo Class
GrammarInfo Members
GrammarInfo Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarInfo Methods

[image] [image]

GrammarInfo Methods
GrammarInfo Class See Also Send Feedback

The GrammarInfo type exposes the following members.

Methods

 | Name | Description
Public method | Dispose | Disposes the object.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | Save(Stream) | Saves the information in a GrammarInfo object to the specified stream.
Public method | Save(String) | Saves the information in a GrammarInfo object to the specified file path.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

GrammarInfo Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Dispose Method

[image]

GrammarInfo..::..Dispose Method
GrammarInfo Class See Also Send Feedback

Disposes the object.

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

Syntax

Visual Basic (Declaration)
Public Sub Dispose
Visual Basic (Usage)
Dim instance As GrammarInfo

instance.Dispose()
C#
public void Dispose()

Implements

IDisposable..::..Dispose()()()()

See Also

Reference

GrammarInfo Class
GrammarInfo Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Save Method

[image] [image]

GrammarInfo..::..Save Method
GrammarInfo Class See Also Send Feedback

Saves the information in a GrammarInfo object to a stream or a file.

Overload List

 | Name | Description
Public method | Save(Stream) | Saves the information in a GrammarInfo object to the specified stream.
Public method | Save(String) | Saves the information in a GrammarInfo object to the specified file path.
Top

See Also

Reference

GrammarInfo Class
GrammarInfo Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Save Method (Stream)

[image]

GrammarInfo..::..Save Method (Stream)
GrammarInfo Class See Also Send Feedback

Saves the information in a GrammarInfo object to the specified stream.

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

Syntax

Visual Basic (Declaration)
Public Sub Save ( _
    stream As Stream _
)
Visual Basic (Usage)
Dim instance As GrammarInfo
Dim stream As Stream

instance.Save(stream)
C#
public void Save(
    Stream stream
)

Parameters

stream
Type: System.IO..::..Stream

The stream to which to save the information.

Exceptions

Exception | Condition
ArgumentNullException | Thrown when stream is nullNothingnullptrunita null reference (Nothing in Visual Basic).
InvalidOperationException | Thrown when there is an error saving to the given stream.

See Also

Reference

GrammarInfo Class
GrammarInfo Members
Save Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Save Method (String)

[image]

GrammarInfo..::..Save Method (String)
GrammarInfo Class See Also Send Feedback

Saves the information in a GrammarInfo object to the specified file path.

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

Syntax

Visual Basic (Declaration)
Public Sub Save ( _
    filePath As String _
)
Visual Basic (Usage)
Dim instance As GrammarInfo
Dim filePath As String

instance.Save(filePath)
C#
public void Save(
    string filePath
)

Parameters

filePath
Type: System..::..String

The path to the file that will receive the information.

Exceptions

Exception | Condition
InvalidOperationException | Thrown when there is an error saving to the specified file path.
ArgumentNullException | Thrown when filePath is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentException | Thrown when filePath is an empty string.

See Also

Reference

GrammarInfo Class
GrammarInfo Members
Save Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarInfo Properties

[image] [image]

GrammarInfo Properties
GrammarInfo Class See Also Send Feedback

The GrammarInfo type exposes the following members.

Properties

 | Name | Description
Public property | ExtraParts | Gets a GrammarInfoPartsCollection collection that contains information about a specific speech recognition engine.
Top

See Also

Reference

GrammarInfo Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ExtraParts Property

[image]

GrammarInfo..::..ExtraParts Property
GrammarInfo Class See Also Send Feedback

Gets a GrammarInfoPartsCollection collection that contains information about a specific speech recognition engine.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property ExtraParts As GrammarInfoPartsCollection
    Get
Visual Basic (Usage)
Dim instance As GrammarInfo
Dim value As GrammarInfoPartsCollection

value = instance.ExtraParts
C#
public GrammarInfoPartsCollection ExtraParts { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..GrammarInfoPartsCollection

Returns GrammarInfoPartsCollection.

See Also

Reference

GrammarInfo Class
GrammarInfo Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarInfoPartsCollection Class

[image]

GrammarInfoPartsCollection Class
Members See Also Send Feedback

Represents a collection of speech recognition engine parts.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..GrammarInfoPartsCollection

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

Syntax

Visual Basic (Declaration)
Public Class GrammarInfoPartsCollection
Visual Basic (Usage)
Dim instance As GrammarInfoPartsCollection
C#
public class GrammarInfoPartsCollection

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

GrammarInfoPartsCollection Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarInfoPartsCollection Members

[image] [image]

GrammarInfoPartsCollection Members
GrammarInfoPartsCollection Class Methods See Also Send Feedback

Represents a collection of speech recognition engine parts.

The GrammarInfoPartsCollection type exposes the following members.

Methods

 | Name | Description
Public method | AddEnginePart | Adds the part of the engine passed as a parameter to the collection.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

GrammarInfoPartsCollection Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GrammarInfoPartsCollection Methods

[image] [image]

GrammarInfoPartsCollection Methods
GrammarInfoPartsCollection Class See Also Send Feedback

The GrammarInfoPartsCollection type exposes the following members.

Methods

 | Name | Description
Public method | AddEnginePart | Adds the part of the engine passed as a parameter to the collection.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

GrammarInfoPartsCollection Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AddEnginePart Method

[image]

GrammarInfoPartsCollection..::..AddEnginePart Method
GrammarInfoPartsCollection Class See Also Send Feedback

Adds the part of the engine passed as a parameter to the collection.

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

Syntax

Visual Basic (Declaration)
Public Function AddEnginePart ( _
    engine As SpeechRecognitionEngine _
) As Guid
Visual Basic (Usage)
Dim instance As GrammarInfoPartsCollection
Dim engine As SpeechRecognitionEngine
Dim returnValue As Guid

returnValue = instance.AddEnginePart(engine)
C#
public Guid AddEnginePart(
    SpeechRecognitionEngine engine
)

Parameters

engine
Type: Microsoft.Speech.Recognition..::..SpeechRecognitionEngine

A SpeechRecognitionEngine instance.

Return Value

Type: System..::..Guid

A Guid that is associated with the added engine part.

Exceptions

Exception | Condition
InvalidOperationException | Thrown if the engine part could not be added for any reason.

See Also

Reference

GrammarInfoPartsCollection Class
GrammarInfoPartsCollection Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InvalidCultureException Class

[image]

InvalidCultureException Class
Members See Also Send Feedback

Thrown on an attempt to use a grammar with an unrecognized CultureInfo setting.

Inheritance Hierarchy

System..::..Object
System..::..Exception
Microsoft.Speech.Recognition..::..InvalidCultureException

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class InvalidCultureException _
    Inherits Exception
Visual Basic (Usage)
Dim instance As InvalidCultureException
C#
[SerializableAttribute]
public sealed class InvalidCultureException : Exception

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

InvalidCultureException Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InvalidCultureException Members

[image] [image]

InvalidCultureException Members
InvalidCultureException Class Constructors Methods Properties See Also Send Feedback

Thrown on an attempt to use a grammar with an unrecognized CultureInfo setting.

The InvalidCultureException type exposes the following members.

Constructors

 | Name | Description
Public method | InvalidCultureException()()()() | Creates a new instance of InvalidCultureException.
Public method | InvalidCultureException(String) | Creates a new instance of InvalidCultureException.
Public method | InvalidCultureException(String, Exception) | Creates a new instance of InvalidCultureException.
Top

Properties

 | Name | Description
Public property | Data | (Inherited from Exception.)
Public property | HelpLink | (Inherited from Exception.)
Protected property | HResult | (Inherited from Exception.)
Public property | InnerException | (Inherited from Exception.)
Public property | Message | (Inherited from Exception.)
Public property | Source | (Inherited from Exception.)
Public property | StackTrace | (Inherited from Exception.)
Public property | TargetSite | (Inherited from Exception.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetBaseException | (Inherited from Exception.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetObjectData | (Inherited from Exception.)
Public method | GetType | (Inherited from Exception.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Exception.)
Top

See Also

Reference

InvalidCultureException Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InvalidCultureException Constructor

[image] [image]

InvalidCultureException Constructor
InvalidCultureException Class See Also Send Feedback

Creates a new instance of InvalidCultureException.

Overload List

 | Name | Description
Public method | InvalidCultureException()()()() | Creates a new instance of InvalidCultureException.
Public method | InvalidCultureException(String) | Creates a new instance of InvalidCultureException.
Public method | InvalidCultureException(String, Exception) | Creates a new instance of InvalidCultureException.
Top

See Also

Reference

InvalidCultureException Class
InvalidCultureException Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InvalidCultureException Constructor

[image]

InvalidCultureException Constructor
InvalidCultureException Class See Also Send Feedback

Creates a new instance of InvalidCultureException.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New InvalidCultureException()
C#
public InvalidCultureException()

See Also

Reference

InvalidCultureException Class
InvalidCultureException Members
InvalidCultureException Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InvalidCultureException Constructor (String)

[image]

InvalidCultureException Constructor (String)
InvalidCultureException Class See Also Send Feedback

Creates a new instance of InvalidCultureException.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    message As String _
)
Visual Basic (Usage)
Dim message As String

Dim instance As New InvalidCultureException(message)
C#
public InvalidCultureException(
    string message
)

Parameters

message
Type: System..::..String

See Also

Reference

InvalidCultureException Class
InvalidCultureException Members
InvalidCultureException Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InvalidCultureException Constructor (String, Exception)

[image]

InvalidCultureException Constructor (String, Exception)
InvalidCultureException Class See Also Send Feedback

Creates a new instance of InvalidCultureException.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    message As String, _
    innerException As Exception _
)
Visual Basic (Usage)
Dim message As String
Dim innerException As Exception

Dim instance As New InvalidCultureException(message, _
    innerException)
C#
public InvalidCultureException(
    string message,
    Exception innerException
)

Parameters

message
Type: System..::..String
innerException
Type: System..::..Exception

See Also

Reference

InvalidCultureException Class
InvalidCultureException Members
InvalidCultureException Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InvalidCultureException Methods

[image] [image]

InvalidCultureException Methods
InvalidCultureException Class See Also Send Feedback

The InvalidCultureException type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetBaseException | (Inherited from Exception.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetObjectData | (Inherited from Exception.)
Public method | GetType | (Inherited from Exception.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Exception.)
Top

See Also

Reference

InvalidCultureException Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InvalidCultureException Properties

[image] [image]

InvalidCultureException Properties
InvalidCultureException Class See Also Send Feedback

The InvalidCultureException type exposes the following members.

Properties

 | Name | Description
Public property | Data | (Inherited from Exception.)
Public property | HelpLink | (Inherited from Exception.)
Protected property | HResult | (Inherited from Exception.)
Public property | InnerException | (Inherited from Exception.)
Public property | Message | (Inherited from Exception.)
Public property | Source | (Inherited from Exception.)
Public property | StackTrace | (Inherited from Exception.)
Public property | TargetSite | (Inherited from Exception.)
Top

See Also

Reference

InvalidCultureException Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


LoadGrammarCompletedEventArgs Class

[image]

LoadGrammarCompletedEventArgs Class
Members Example See Also Send Feedback

Provides data for the LoadGrammarCompleted event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
System.ComponentModel..::..AsyncCompletedEventArgs
Microsoft.Speech.Recognition..::..LoadGrammarCompletedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class LoadGrammarCompletedEventArgs _
    Inherits AsyncCompletedEventArgs
Visual Basic (Usage)
Dim instance As LoadGrammarCompletedEventArgs
C#
public class LoadGrammarCompletedEventArgs : AsyncCompletedEventArgs

Remarks

An instance of LoadGrammarCompletedEventArgs is created when the SpeechRecognitionEngine object raises its LoadGrammarCompleted event or the DtmfRecognitionEngine object raises its LoadGrammarCompleted event. The events are raised when calls to the LoadGrammarAsync methods complete.

To obtain information about the Grammar object that was loaded, access the Grammar property in the handler for the event.

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.

Examples

The following example creates two speech recognition grammars and constructs a Grammar object from each of the completed grammars. It then asynchronously loads the Grammar objects to the SpeechRecognitionEngine instance. The handler for the recognizer's LoadGrammarCompleted event reports the status of Grammar objects when loaded. The handler for the SpeechRecognized event reports the name of the Grammar object that was used to perform a recognition and the text of the recognition result.

Copy image Copy Code
using System;
using Microsoft.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();

      // 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);

      // Create the "yesno" grammar and build it into a Grammar object.
      Choices yesChoices = new Choices(new string[] { "yes", "yup", "yeah" });
      SemanticResultValue yesValue =
          new SemanticResultValue(yesChoices, (bool)true);
      Choices noChoices = new Choices(new string[] { "no", "nope", "neah" });
      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";

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

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

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

    // 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");
    }

    // 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.
    }
  }
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

LoadGrammarCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
Grammar
SpeechRecognitionEngine..::..LoadGrammar
SpeechRecognitionEngine..::..LoadGrammar
LoadGrammarAsync
DtmfRecognitionEngine
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


LoadGrammarCompletedEventArgs Members

[image] [image]

LoadGrammarCompletedEventArgs Members
LoadGrammarCompletedEventArgs Class Methods Properties See Also Send Feedback

Provides data for the LoadGrammarCompleted event.

The LoadGrammarCompletedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Grammar | Gets the Grammar object that has completed loading.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

LoadGrammarCompletedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


LoadGrammarCompletedEventArgs Methods

[image] [image]

LoadGrammarCompletedEventArgs Methods
LoadGrammarCompletedEventArgs Class See Also Send Feedback

The LoadGrammarCompletedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

LoadGrammarCompletedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


LoadGrammarCompletedEventArgs Properties

[image] [image]

LoadGrammarCompletedEventArgs Properties
LoadGrammarCompletedEventArgs Class See Also Send Feedback

The LoadGrammarCompletedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Grammar | Gets the Grammar object that has completed loading.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

See Also

Reference

LoadGrammarCompletedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Property

[image]

LoadGrammarCompletedEventArgs..::..Grammar Property
LoadGrammarCompletedEventArgs Class Example See Also Send Feedback

Gets the Grammar object that has completed loading.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Grammar As Grammar
    Get
Visual Basic (Usage)
Dim instance As LoadGrammarCompletedEventArgs
Dim value As Grammar

value = instance.Grammar
C#
public Grammar Grammar { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..Grammar

The Grammar object that has completed loading.

Remarks

The Grammar property returns the Grammar that an application specifies in a call to LoadGrammarAsync or LoadGrammarAsync(Grammar).

Examples

In the example below, a handler for SpeechRecognitionEngine..::..LoadGrammarCompleted uses the Grammar property to update a display of loaded Grammar objects.

Copy image Copy Code
//On load we update the display.
//A hash table is used to get the node information we added in AddToTree.
_recognizer.LoadGrammarCompleted +=
    delegate(object sender, LoadGrammarCompletedEventArgs eventArgs) {
        Grammar grammar = eventArgs.Grammar;
        SrgsDocument document;
        document = _grammarDocumentList[grammar] as SrgsDocument;
        if (grammar != null) {

//Should probably do a sanity check and remove node if it exists.
TreeNode grammarNode = new TreeNode(grammar.Name);
grammarNode.Checked = grammar.Enabled;
grammarNode.Tag = grammar;

if (document != null) {
    foreach (SrgsRule rule in document.Rules) {
        TreeNode ruleNode = new TreeNode(rule.Id);

        if (document.Root == rule) {
ruleNode.ForeColor = Color.Red;
        }

        ruleNode.Tag = rule;
        ruleNode.Checked = true;
        grammarNode.Nodes.Add(ruleNode);
    }
}
_grammarTreeView.Nodes.Add(grammarNode);
grammarNode.ExpandAll();
        }
    };

See Also

Reference

LoadGrammarCompletedEventArgs Class
LoadGrammarCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
Grammar
LoadGrammar
LoadGrammarAsync
LoadGrammarCompletedEventArgs
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Pronounceable Enumeration

[image]

Pronounceable Enumeration
See Also Send Feedback

Lists values that represent whether the SpeechRecognitionEngine can pronounce a word and whether the pronunciation is defined in a lexicon.

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

Syntax

Visual Basic (Declaration)
Public Enumeration Pronounceable
Visual Basic (Usage)
Dim instance As Pronounceable
C#
public enum Pronounceable

Members

Member name | Description
UnknownWordUnpronounceable | Indicates that a word does not exist in the lexicon and is not pronounceable.
UnknownWordPronounceable | Indicates that a word does not exist in the lexicon but is pronounceable.
KnownWordPronounceable | Indicates that a word exists in the lexicon and is pronounceable.

Remarks

The Grammar object's IsPronounceable(String) method returns a member of Pronounceable enumeration.

See Also

Reference

Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognitionEventArgs Class

[image]

RecognitionEventArgs Class
Members Example See Also Send Feedback

Provides information about speech recognition events.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Recognition..::..RecognitionEventArgs
Microsoft.Speech.Recognition..::..DtmfHypothesizedEventArgs
Microsoft.Speech.Recognition..::..DtmfRecognitionRejectedEventArgs
Microsoft.Speech.Recognition..::..DtmfRecognizedEventArgs
Microsoft.Speech.Recognition..::..SpeechHypothesizedEventArgs
Microsoft.Speech.Recognition..::..SpeechRecognitionRejectedEventArgs
Microsoft.Speech.Recognition..::..SpeechRecognizedEventArgs

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public MustInherit Class RecognitionEventArgs _
    Inherits EventArgs
Visual Basic (Usage)
Dim instance As RecognitionEventArgs
C#
[SerializableAttribute]
public abstract class RecognitionEventArgs : EventArgs

Remarks

The Result property obtains the recognition information as a RecognitionResult object. For more information about speech recognition events, see Use Speech Recognition Events (Microsoft.Speech).

RecognitionEventArgs is the base for the following classes:

  • DtmfRecognizedEventArgs and SpeechRecognizedEventArgs.

  • DtmfRecognitionRejectedEventArgs and SpeechRecognitionRejectedEventArgs.

  • DtmfHypothesizedEventArgs and SpeechHypothesizedEventArgs.

RecognitionEventArgs derives from EventArgs.

Examples

The following example attaches a handler for the SpeechHypothesized, SpeechRecognized, and SpeechRecognitionRejected events of the speech recognizer. The event argument types for the three events all derive from RecognitionEventArgs, which is used as the event data parameter in the handler.

C# Copy image Copy Code
// Initialize the speech recognizer.
private void Initialize(SpeechRecognitionEngine recognizer)
{
  // Attach handlers for the SpeechHypothesized, SpeechRecognitionRejected,
  // and SpeechRecognized events.
  recognizer.SpeechHypothesized +=
    new EventHandler<SpeechHypothesizedEventArgs>(DisplayResult);
  recognizer.SpeechRecognitionRejected +=
    new EventHandler<SpeechRecognitionRejectedEventArgs>(DisplayResult);
  recognizer.SpeechRecognized +=
    new EventHandler<SpeechRecognizedEventArgs>(DisplayResult);

  // Add other initialization code here.
}

// Handle the SpeechHypothesized, SpeechRecognitionRejected,
// and SpeechRecognized events.
private void DisplayResult(object sender, RecognitionEventArgs e)
{
  if (e is SpeechHypothesizedEventArgs)
  {
    Console.WriteLine("Speech hypothesized:");
  }
  else if (e is SpeechRecognitionRejectedEventArgs)
  {
    Console.WriteLine("Speech recognition rejected:");
  }
  else if (e is SpeechRecognizedEventArgs)
  {
    Console.WriteLine("Speech recognized:");
  }

  // Add code to handle the event.
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

RecognitionEventArgs Members
Microsoft.Speech.Recognition Namespace
SpeechRecognized
DtmfHypothesized
RecognizeCompleted
DtmfRecognitionRejected
DtmfRecognized
Result
RecognitionResult
SpeechHypothesized
RecognizeCompleted
SpeechRecognitionRejected
SpeechRecognized
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognitionEventArgs Members

[image] [image]

RecognitionEventArgs Members
RecognitionEventArgs Class Methods Properties See Also Send Feedback

Provides information about speech recognition events.

The RecognitionEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Result | Gets the results of the speech or DTMF recognition operation.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

RecognitionEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognitionEventArgs Methods

[image] [image]

RecognitionEventArgs Methods
RecognitionEventArgs Class See Also Send Feedback

The RecognitionEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

RecognitionEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognitionEventArgs Properties

[image] [image]

RecognitionEventArgs Properties
RecognitionEventArgs Class See Also Send Feedback

The RecognitionEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Result | Gets the results of the speech or DTMF recognition operation.
Top

See Also

Reference

RecognitionEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Result Property

[image]

RecognitionEventArgs..::..Result Property
RecognitionEventArgs Class Example See Also Send Feedback

Gets the results of the speech or DTMF recognition operation.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Result As RecognitionResult
    Get
Visual Basic (Usage)
Dim instance As RecognitionEventArgs
Dim value As RecognitionResult

value = instance.Result
C#
public RecognitionResult Result { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

The RecognitionResult that contains the results of the speech or DTMF recognition operation.

Remarks

The RecognitionResult object derives from RecognizedPhrase and contains full information about a phrase returned by a recognition operation. You can obtain a list off all the recognition candidates from the Alternates property.

Examples

The example below shows the use Result to obtain an instance of RecognitionResult, which is then used to display information about the results of a speech recognition operation.

Copy image Copy Code
       // Display the semantics, rules, and alternates of the result.
        private void DisplayResult(RecognitionEventArgs eventArgs)
        {

            // Clear results, semantic XML, semantics tree, and alternates.
            _recognitionSmlBrowser.Navigate("about:blank");
            _semanticsTreeView.Nodes.Clear();
            _alternatesListBox.Items.Clear();
            _recognitionInfo.Text = null;
            _recognizedTextDisplay.Text = null;

            //Obtain result from RecognitionEventArg passed in.

            if (eventArgs != null && eventArgs.Result != null)
            {
                RecognitionResult result = eventArgs.Result;
                //Set Text color on the basis of the event type passed in.
                _recognitionInfo.Text = null;
                switch (eventArgs.GetType().ToString())
                {

                    case "Microsoft.Speech.Recognition.SpeechHypothesizedEventArgs":
                       _recognizedTextDisplay.ForeColor = Color.Black;
                        _recognizedTextDisplay.Text = result.Text;
                        _recognitionInfo.Text = null;
                        break;
                    case "Microsoft.Speech.Recognition.SpeechRecognitionRejectedEventArgs":
                        _recognizedTextDisplay.ForeColor = Color.OrangeRed;
                        _recognizedTextDisplay.Text ="Unable to Recognize Input";
                        DisplaySemanticsSML(result);
                        DisplaySemanticsTreeView(result);
                        _recognitionInfo.Text = null;
                        break;
                    case "Microsoft.Speech.Recognition.SpeechRecognizedEventArgs":
                        _recognizedTextDisplay.ForeColor = Color.Green;
                        _recognizedTextDisplay.Text = result.Text;
                        _recognitionInfo.Text =
                            "Confidence Level:    " + result.Confidence + Environment.NewLine
                          + "Recognizing Grammar: " + result.Grammar.Name + Environment.NewLine
                          + ((result.Grammar.RuleName != null) ? ("Recognizing Rule   : " + result.Grammar.RuleName) : "");
                        DisplaySemanticsSML(result);
                        DisplaySemanticsTreeView(result);
                        break;
                    default:
                        _recognizedTextDisplay.ForeColor = Color.Black;
                        break;
                }

                _recognizedTextDisplay.Show();
                _recognitionInfo.Show();

                DisplayAlternates(result);
            }
        }

See Also

Reference

RecognitionEventArgs Class
RecognitionEventArgs Members
Microsoft.Speech.Recognition Namespace
RecognitionEventArgs
RecognitionResult
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognitionResult Class

[image]

RecognitionResult Class
Members Example See Also Send Feedback

Contains detailed information about input that was recognized by instances of SpeechRecognitionEngine or DtmfRecognitionEngine.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..RecognizedPhrase
Microsoft.Speech.Recognition..::..RecognitionResult

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class RecognitionResult _
    Inherits RecognizedPhrase _
    Implements ISerializable
Visual Basic (Usage)
Dim instance As RecognitionResult
C#
[SerializableAttribute]
public sealed class RecognitionResult : RecognizedPhrase,
    ISerializable

Remarks

This class derives from RecognizedPhrase and provides detailed information about recognition of speech and DTMF tones, including the following:

  • The Grammar property references the Grammar that the recognizer used to identify the speech.

  • The Text property contains the normalized text for the phrase. For more information about text normalization, see ReplacementText.

  • The Semantics property references the semantic information contained in the result. The semantic information is a dictionary of the key names and associated semantic data.

  • The Alternates property contains a collection of RecognizedPhrase objects that represent other candidate interpretations of the audio input. See Alternates for additional information.

  • The Words property contains an ordered collection of RecognizedWordUnit objects that represent each recognized word in the input. Each RecognizedWordUnit contains display format, lexical format, and pronunciation information for the corresponding word.

Certain members of the SpeechRecognitionEngine, DtmfRecognitionEngine, and Grammar classes can generate a RecognitionResult. For more information, see the following methods and events.

  • Methods and events of the SpeechRecognitionEngine class:

    • EmulateRecognize

    • EmulateRecognizeAsync

    • SpeechHypothesized

    • SpeechRecognitionRejected

    • SpeechRecognized

  • The RecognizeCompleted event of the DtmfRecognitionEngine class.

  • The SpeechRecognized event of the Grammar class.

For more information about recognition events, see Use Speech Recognition Events (Microsoft.Speech).

Examples

The following example shows a handler for the SpeechRecognized event of a SpeechRecognitionEngine object, and some of the information about the associated RecognitionResult.

C# Copy image Copy Code
// Handle the SpeechRecognized event.
void SpeechRecognizedHandler(object sender, SpeechRecognizedEventArgs e)
{
  if (e.Result == null) return;

  // Add event handler code here.

  // The following code illustrates some of the information available
  // in the recognition result.
  Console.WriteLine("Grammar({0}), {1}: {2}",
    e.Result.Grammar.Name, e.Result.Audio.Duration, e.Result.Text);

  // Display the semantic values in the recognition result.
  foreach (KeyValuePair<String, SemanticValue> child in e.Result.Semantics)
  {
    Console.WriteLine(" {0} key: {1}",
      child.Key, child.Value.Value ?? "null");
  }
  Console.WriteLine();

  // Display information about the words in the recognition result.
  foreach (RecognizedWordUnit word in e.Result.Words)
  {
    RecognizedAudio audio = e.Result.GetAudioForWordRange(word, word);
    Console.WriteLine(" {0,-10} {1,-10} {2,-10} {3} ({4})",
      word.Text, word.LexicalForm, word.Pronunciation,
      audio.Duration, word.DisplayAttributes);
  }

  // Display the recognition alternates for the result.
  foreach (RecognizedPhrase phrase in e.Result.Alternates)
  {
    Console.WriteLine(" alt({0}) {1}", phrase.Confidence, phrase.Text);
  }
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

RecognitionResult Members
Microsoft.Speech.Recognition Namespace
RecognitionEventArgs
RecognizedPhrase
SpeechHypothesized
SpeechRecognized
SpeechRecognitionRejected
SpeechRecognized
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognitionResult Members

[image] [image]

RecognitionResult Members
RecognitionResult Class Methods Properties Explicit Interface Implementations See Also Send Feedback

Contains detailed information about input that was recognized by instances of SpeechRecognitionEngine or DtmfRecognitionEngine.

The RecognitionResult type exposes the following members.

Properties

 | Name | Description
Public property | Alternates | Gets the collection of possible matches for input to the speech recognizer.
Public property | Audio | Gets the audio associated with the recognition result.
Public property | Confidence | Gets a value, assigned by the recognizer, that represents the likelihood that a RecognizedPhrase matches a given input. (Inherited from RecognizedPhrase.)
Public property | Grammar | Gets the Grammar object that the speech recognizer used to return the RecognizedPhrase. (Inherited from RecognizedPhrase.)
Public property | HomophoneGroupId | Infrastructure. Gets the identifier for the homophone group for the phrase. (Inherited from RecognizedPhrase.)
Public property | Homophones | Gets a collection of the recognition alternates that have the same pronunciation as this recognized phrase. (Inherited from RecognizedPhrase.)
Public property | ReplacementWordUnits | Gets information about the text that the speech recognizer changed as part of speech-to-text normalization. (Inherited from RecognizedPhrase.)
Public property | Semantics | Gets the semantic information that is associated with the recognized phrase. (Inherited from RecognizedPhrase.)
Public property | Text | Gets the normalized text generated by a speech recognition engine from recognized input. (Inherited from RecognizedPhrase.)
Public property | Words | Gets the words generated by a speech recognizer from recognized input. (Inherited from RecognizedPhrase.)
Top

Methods

 | Name | Description
Public method | ConstructSmlFromSemantics | Returns a semantic markup language (SML) document for the semantic information in the RecognizedPhrase object. (Inherited from RecognizedPhrase.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

Explicit Interface Implementations

 | Name | Description
Explicit interface implemetation | ISerializable..::..GetObjectData | Populates a SerializationInfo instance with the data needed to serialize the target object.
Top

See Also

Reference

RecognitionResult Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognitionResult Methods

[image] [image]

RecognitionResult Methods
RecognitionResult Class See Also Send Feedback

The RecognitionResult type exposes the following members.

Methods

 | Name | Description
Public method | ConstructSmlFromSemantics | Returns a semantic markup language (SML) document for the semantic information in the RecognizedPhrase object. (Inherited from RecognizedPhrase.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

Explicit Interface Implementations

 | Name | Description
Explicit interface implemetation | ISerializable..::..GetObjectData | Populates a SerializationInfo instance with the data needed to serialize the target object.
Top

See Also

Reference

RecognitionResult Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ISerializable.GetObjectData Method

[image]

RecognitionResult..::..ISerializable..::..GetObjectData Method
RecognitionResult Class See Also Send Feedback

Populates a SerializationInfo instance with the data needed to serialize the target object.

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

Syntax

Visual Basic (Declaration)
<SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter := True)> _
Private Sub GetObjectData ( _
    info As SerializationInfo, _
    context As StreamingContext _
) Implements ISerializable.GetObjectData
Visual Basic (Usage)
Dim instance As RecognitionResult
Dim info As SerializationInfo
Dim context As StreamingContext

CType(instance, ISerializable).GetObjectData(info, _
    context)
C#
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
void ISerializable.GetObjectData(
    SerializationInfo info,
    StreamingContext context
)

Parameters

info
Type: System.Runtime.Serialization..::..SerializationInfo

The object to populate with data.

context
Type: System.Runtime.Serialization..::..StreamingContext

The destination for the serialization.

Implements

ISerializable..::..GetObjectData(SerializationInfo, StreamingContext)

Remarks

This member is an explicit interface member implementation. It can be used only when the RecognitionResult instance is cast to an ISerializable interface.

See Also

Reference

RecognitionResult Class
RecognitionResult Members
Microsoft.Speech.Recognition Namespace
System.Runtime.Serialization..::..ISerializable
RecognitionResult
RecognizedAudio
Audio
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognitionResult Properties

[image] [image]

RecognitionResult Properties
RecognitionResult Class See Also Send Feedback

The RecognitionResult type exposes the following members.

Properties

 | Name | Description
Public property | Alternates | Gets the collection of possible matches for input to the speech recognizer.
Public property | Audio | Gets the audio associated with the recognition result.
Public property | Confidence | Gets a value, assigned by the recognizer, that represents the likelihood that a RecognizedPhrase matches a given input. (Inherited from RecognizedPhrase.)
Public property | Grammar | Gets the Grammar object that the speech recognizer used to return the RecognizedPhrase. (Inherited from RecognizedPhrase.)
Public property | HomophoneGroupId | Infrastructure. Gets the identifier for the homophone group for the phrase. (Inherited from RecognizedPhrase.)
Public property | Homophones | Gets a collection of the recognition alternates that have the same pronunciation as this recognized phrase. (Inherited from RecognizedPhrase.)
Public property | ReplacementWordUnits | Gets information about the text that the speech recognizer changed as part of speech-to-text normalization. (Inherited from RecognizedPhrase.)
Public property | Semantics | Gets the semantic information that is associated with the recognized phrase. (Inherited from RecognizedPhrase.)
Public property | Text | Gets the normalized text generated by a speech recognition engine from recognized input. (Inherited from RecognizedPhrase.)
Public property | Words | Gets the words generated by a speech recognizer from recognized input. (Inherited from RecognizedPhrase.)
Top

See Also

Reference

RecognitionResult Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Alternates Property

[image]

RecognitionResult..::..Alternates Property
RecognitionResult Class Example See Also Send Feedback

Gets the collection of possible matches for input to the speech recognizer.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Alternates As ReadOnlyCollection(Of RecognizedPhrase)
    Get
Visual Basic (Usage)
Dim instance As RecognitionResult
Dim value As ReadOnlyCollection(Of RecognizedPhrase)

value = instance.Alternates
C#
public ReadOnlyCollection<RecognizedPhrase> Alternates { get; }

Property Value

Type: System.Collections.ObjectModel..::..ReadOnlyCollection <(Of <(<' RecognizedPhrase >)>)>

A read-only collection of the recognition alternates.

Remarks

Recognition Alternates are ordered by the values of their Confidence properties. The confidence value of a given phrase indicates the probability that the phrase matches the input. The phrase with the highest confidence value is the phrase that most likely matches the input.

Each Confidence value should be evaluated individually and without reference to the confidence values of other Alternates. The properties that the RecognitionResult inherits from RecognizedPhrase provide detailed information about the phrase with the highest confidence score.

One use for the Alternates collection is for automated error correction. For example, when designing a directory dialog, an application could prompt the user to check if the application has the correct information from a recognition event, as in, "Did you say 'Anna'?" If the user says "no", then the application could query the user about any alternates that had a high enough Confidence score.

For more information about speech recognition and the use of recognition alternates, see Speech Recognition (Microsoft.Speech) and Use Speech Recognition Events (Microsoft.Speech).

Examples

The following example shows a handler for the SpeechRecognized event and some of the information about the associated RecognitionResult.

C# Copy image Copy Code
// Handle the SpeechRecognized event.
void SpeechRecognizedHandler(object sender, SpeechRecognizedEventArgs e)
{
  if (e.Result == null) return;

  // Add event handler code here.

  // The following code illustrates some of the information available
  // in the recognition result.
  Console.WriteLine("Grammar({0}), {1}: {2}",
    e.Result.Grammar.Name, e.Result.Audio.Duration, e.Result.Text);

  // Display the semantic values in the recognition result.
  foreach (KeyValuePair<String, SemanticValue> child in e.Result.Semantics)
  {
    Console.WriteLine(" {0} key: {1}",
      child.Key, child.Value.Value ?? "null");
  }
  Console.WriteLine();

  // Display information about the words in the recognition result.
  foreach (RecognizedWordUnit word in e.Result.Words)
  {
    RecognizedAudio audio = e.Result.GetAudioForWordRange(word, word);
    Console.WriteLine(" {0,-10} {1,-10} {2,-10} {3} ({4})",
      word.Text, word.LexicalForm, word.Pronunciation,
      audio.Duration, word.DisplayAttributes);
  }

  // Display the recognition alternates for the result.
  foreach (RecognizedPhrase phrase in e.Result.Alternates)
  {
    Console.WriteLine(" alt({0}) {1}", phrase.Confidence, phrase.Text);
  }
}

See Also

Reference

RecognitionResult Class
RecognitionResult Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Audio Property

[image]

RecognitionResult..::..Audio Property
RecognitionResult Class Example See Also Send Feedback

Gets the audio associated with the recognition result.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Audio As RecognizedAudio
    Get
Visual Basic (Usage)
Dim instance As RecognitionResult
Dim value As RecognizedAudio

value = instance.Audio
C#
public RecognizedAudio Audio { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..RecognizedAudio

The audio associated with the recognition result or nullNothingnullptrunita null reference (Nothing in Visual Basic) if the recognizer generated the result from a call to the EmulateRecognize()()()() or EmulateRecognizeAsync()()()() methods.

Examples

The following example shows a handler for the SpeechRecognized event and some of the information about the associated RecognitionResult.

C# Copy image Copy Code
// Handle the SpeechRecognized event.
void SpeechRecognizedHandler(object sender, SpeechRecognizedEventArgs e)
{
  if (e.Result == null) return;

  // Add event handler code here.

  // The following code illustrates some of the information available
  // in the recognition result.
      Console.WriteLine("Grammar({0}): {1}", e.Result.Grammar.Name, e.Result.Text);
      Console.WriteLine("Audio for result:");
      Console.WriteLine("  Start time: "+ e.Result.Audio.StartTime);
      Console.WriteLine("  Duration: " + e.Result.Audio.Duration);
      Console.WriteLine("  Format: " + e.Result.Audio.Format.EncodingFormat);

  // Display the semantic values in the recognition result.
  foreach (KeyValuePair<String, SemanticValue> child in e.Result.Semantics)
  {
    Console.WriteLine(" {0} key: {1}",
      child.Key, child.Value.Value ?? "null");
  }
  Console.WriteLine();

  // Display the recognition alternates for the result.
  foreach (RecognizedPhrase phrase in e.Result.Alternates)
  {
    Console.WriteLine(" alt({0}) {1}", phrase.Confidence, phrase.Text);
  }
}

See Also

Reference

RecognitionResult Class
RecognitionResult Members
Microsoft.Speech.Recognition Namespace
RecognitionResult
RecognizedAudio
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeCompletedEventArgs Class

[image]

RecognizeCompletedEventArgs Class
Members Example See Also Send Feedback

Provides data for the RecognizeCompleted event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
System.ComponentModel..::..AsyncCompletedEventArgs
Microsoft.Speech.Recognition..::..RecognizeCompletedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class RecognizeCompletedEventArgs _
    Inherits AsyncCompletedEventArgs
Visual Basic (Usage)
Dim instance As RecognizeCompletedEventArgs
C#
public class RecognizeCompletedEventArgs : AsyncCompletedEventArgs

Remarks

An instance of RecognizeCompletedEventArgs is created when the SpeechRecognitionEngine object raises the RecognizeCompleted event at the completion of a RecognizeAsync()()()() operation. To obtain information related to the RecognizeCompleted event, access the following properties in the handler for the event:

  • AudioPosition

  • BabbleTimeout

  • InitialSilenceTimeout

  • InputStreamEnded

  • Result

RecognizeCompletedEventArgs derives from EventArgs For more information about speech recognition events, see Use Speech Recognition Events (Microsoft.Speech).

Examples

The following example performs asynchronous speech recognition on a speech recognition grammar, using the SpeechRecognitionEngine..::..RecognizeAsync method. The example uses Choices and GrammarBuilder objects to create the speech recognition grammar before building it into a Grammar object. A handler for the SpeechRecognitionEngine..::..RecognizeCompleted event outputs information about the recognition operation to the console.

Copy image Copy Code
using System;
using Microsoft.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");
    }
  }
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

RecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
Microsoft.Speech.Recognition..::..SpeechRecognitionEngine
SpeechRecognitionEngine..::..RecognizeCompleted
SpeechRecognitionEngine..::..RecognizeAsync
Microsoft.Speech.Recognition..::..EmulateRecognizeCompletedEventArgs
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeCompletedEventArgs Members

[image] [image]

RecognizeCompletedEventArgs Members
RecognizeCompletedEventArgs Class Methods Properties See Also Send Feedback

Provides data for the RecognizeCompleted event.

The RecognizeCompletedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioPosition | Gets the location in the input device's audio stream associated with the SpeechRecognitionEngine..::..RecognizeCompleted event.
Public property | BabbleTimeout | Gets a value that indicates whether a babble timeout generated the SpeechRecognitionEngine..::..RecognizeCompleted event.
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | InitialSilenceTimeout | Gets a value that indicates whether an initial silence timeout generated the SpeechRecognitionEngine..::..RecognizeCompleted event.
Public property | InputStreamEnded | Gets a value indicating whether the input stream ended.
Public property | Result | Gets the recognition result.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

RecognizeCompletedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeCompletedEventArgs Methods

[image] [image]

RecognizeCompletedEventArgs Methods
RecognizeCompletedEventArgs Class See Also Send Feedback

The RecognizeCompletedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

RecognizeCompletedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeCompletedEventArgs Properties

[image] [image]

RecognizeCompletedEventArgs Properties
RecognizeCompletedEventArgs Class See Also Send Feedback

The RecognizeCompletedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioPosition | Gets the location in the input device's audio stream associated with the SpeechRecognitionEngine..::..RecognizeCompleted event.
Public property | BabbleTimeout | Gets a value that indicates whether a babble timeout generated the SpeechRecognitionEngine..::..RecognizeCompleted event.
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | InitialSilenceTimeout | Gets a value that indicates whether an initial silence timeout generated the SpeechRecognitionEngine..::..RecognizeCompleted event.
Public property | InputStreamEnded | Gets a value indicating whether the input stream ended.
Public property | Result | Gets the recognition result.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

See Also

Reference

RecognizeCompletedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioPosition Property

[image]

RecognizeCompletedEventArgs..::..AudioPosition Property
RecognizeCompletedEventArgs Class Example See Also Send Feedback

Gets the location in the input device's audio stream associated with the SpeechRecognitionEngine..::..RecognizeCompleted event.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioPosition As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As RecognizeCompletedEventArgs
Dim value As TimeSpan

value = instance.AudioPosition
C#
public TimeSpan AudioPosition { get; }

Property Value

Type: System..::..TimeSpan

The location in the input device's audio stream associated with the SpeechRecognitionEngine..::..RecognizeCompleted event.

Remarks

This property references the position at the beginning of the recognized phrase in the input device's generated audio stream. By contrast, the RecognizerAudioPosition property references the recognizer's position within its audio input. These positions can be different. For more information, see Use Speech Recognition Events (Microsoft.Speech).

Examples

The following example performs asynchronous speech recognition on a speech recognition grammar, using the SpeechRecognitionEngine..::..RecognizeAsync method. The example uses Choices and GrammarBuilder objects to create the speech recognition grammar before building it into a Grammar object. A handler for the SpeechRecognitionEngine..::..RecognizeCompleted event outputs information about the recognition operation to the console.

Copy image Copy Code
using System;
using Microsoft.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");
    }
  }
}

See Also

Reference

RecognizeCompletedEventArgs Class
RecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


BabbleTimeout Property

[image]

RecognizeCompletedEventArgs..::..BabbleTimeout Property
RecognizeCompletedEventArgs Class Example See Also Send Feedback

Gets a value that indicates whether a babble timeout generated the SpeechRecognitionEngine..::..RecognizeCompleted event.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property BabbleTimeout As Boolean
    Get
Visual Basic (Usage)
Dim instance As RecognizeCompletedEventArgs
Dim value As Boolean

value = instance.BabbleTimeout
C#
public bool BabbleTimeout { get; }

Property Value

Type: System..::..Boolean

true if the SpeechRecognitionEngine has detected only background noise for longer than was specified by its BabbleTimeout property; otherwise false.

Examples

The following example performs asynchronous speech recognition on a speech recognition grammar, using the SpeechRecognitionEngine..::..RecognizeAsync method. The example uses Choices and GrammarBuilder objects to create the speech recognition grammar before building it into a Grammar object. A handler for the SpeechRecognitionEngine..::..RecognizeCompleted event outputs information about the recognition operation to the console.

Copy image Copy Code
using System;
using Microsoft.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");
    }
  }
}

See Also

Reference

RecognizeCompletedEventArgs Class
RecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InitialSilenceTimeout Property

[image]

RecognizeCompletedEventArgs..::..InitialSilenceTimeout Property
RecognizeCompletedEventArgs Class Example See Also Send Feedback

Gets a value that indicates whether an initial silence timeout generated the SpeechRecognitionEngine..::..RecognizeCompleted event.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property InitialSilenceTimeout As Boolean
    Get
Visual Basic (Usage)
Dim instance As RecognizeCompletedEventArgs
Dim value As Boolean

value = instance.InitialSilenceTimeout
C#
public bool InitialSilenceTimeout { get; }

Property Value

Type: System..::..Boolean

true if the SpeechRecognitionEngine has detected only silence for a longer time period than was specified by its InitialSilenceTimeout property; otherwise false.

Examples

The following example performs asynchronous speech recognition on a speech recognition grammar, using the SpeechRecognitionEngine..::..RecognizeAsync method. The example uses Choices and GrammarBuilder objects to create the speech recognition grammar before building it into a Grammar object. A handler for the SpeechRecognitionEngine..::..RecognizeCompleted event outputs information about the recognition operation to the console.

Copy image Copy Code
using System;
using Microsoft.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");
    }
  }
}

See Also

Reference

RecognizeCompletedEventArgs Class
RecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InputStreamEnded Property

[image]

RecognizeCompletedEventArgs..::..InputStreamEnded Property
RecognizeCompletedEventArgs Class Example See Also Send Feedback

Gets a value indicating whether the input stream ended.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property InputStreamEnded As Boolean
    Get
Visual Basic (Usage)
Dim instance As RecognizeCompletedEventArgs
Dim value As Boolean

value = instance.InputStreamEnded
C#
public bool InputStreamEnded { get; }

Property Value

Type: System..::..Boolean

true if the recognizer no longer has audio input; otherwise, false.

Remarks

The recognizer sets this property to true when a file provides the input stream for the recognizer and the end of the file is reached. The end of the input stream can coincide with a successful recognition operation. For more information about using a file as the input stream, see the SetInputToAudioStream and SetInputToWaveFile methods.

Examples

The following example performs asynchronous speech recognition on a speech recognition grammar, using the SpeechRecognitionEngine..::..RecognizeAsync method. The example uses Choices and GrammarBuilder objects to create the speech recognition grammar before building it into a Grammar object. A handler for the SpeechRecognitionEngine..::..RecognizeCompleted event outputs information about the recognition operation to the console.

Copy image Copy Code
using System;
using Microsoft.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");
    }
  }
}

See Also

Reference

RecognizeCompletedEventArgs Class
RecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Result Property

[image]

RecognizeCompletedEventArgs..::..Result Property
RecognizeCompletedEventArgs Class Example See Also Send Feedback

Gets the recognition result.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Result As RecognitionResult
    Get
Visual Basic (Usage)
Dim instance As RecognizeCompletedEventArgs
Dim value As RecognitionResult

value = instance.Result
C#
public RecognitionResult Result { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

The recognition result if the recognition operation succeeded; otherwise, nullNothingnullptrunita null reference (Nothing in Visual Basic).

Remarks

The RecognitionResult object derives from RecognizedPhrase and contains full information about a phrase returned by a recognition operation.

Examples

The following example performs asynchronous speech recognition on a speech recognition grammar, using the SpeechRecognitionEngine..::..RecognizeAsync method. The example uses Choices and GrammarBuilder objects to create the speech recognition grammar before building it into a Grammar object. A handler for the SpeechRecognitionEngine..::..RecognizeCompleted event outputs information about the recognition operation to the console.

Copy image Copy Code
using System;
using Microsoft.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");
    }
  }
}

See Also

Reference

RecognizeCompletedEventArgs Class
RecognizeCompletedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedAudio Class

[image]

RecognizedAudio Class
Members Example See Also Send Feedback

Represents audio input that is associated with a RecognitionResult.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..RecognizedAudio

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class RecognizedAudio
Visual Basic (Usage)
Dim instance As RecognizedAudio
C#
[SerializableAttribute]
public class RecognizedAudio

Remarks

A speech recognizer generates information about the audio input as part of the recognition operation. To access the recognized audio, use the Audio property.

A recognition result can be produced by the following events and methods of the SpeechRecognitionEngine class:

  • Events:

    • SpeechRecognitionEngine..::..SpeechHypothesized

    • SpeechRecognitionEngine..::..SpeechRecognitionRejected

    • SpeechRecognitionEngine..::..SpeechRecognized

    • SpeechRecognitionEngine..::..EmulateRecognizeCompleted

    • SpeechRecognitionEngine..::..RecognizeCompleted

  • Methods:

    • SpeechRecognitionEngine..::..EmulateRecognize

    • SpeechRecognitionEngine..::..EmulateRecognizeAsync

    • SpeechRecognitionEngine..::..Recognize

    • SpeechRecognitionEngine..::..RecognizeAsync

Important note Important

A recognition result produced by emulated speech recognition does not contain recognized audio. For such a recognition result, its Audio property returns nullNothingnullptrunita null reference (Nothing in Visual Basic). For more information about emulated speech recognition, see the EmulateRecognize()()()() and EmulateRecognizeAsync()()()() methods of the SpeechRecognitionEngine class.

Examples

In the example below, an application first determines whether recognition operation has been emulated by determining if the RecognizedAudio object received is not nullNothingnullptrunita null reference (Nothing in Visual Basic). If the RecognizedAudio object is not nullNothingnullptrunita null reference (Nothing in Visual Basic), information about the recognized audio is written to a Label for display.

C# Copy image Copy Code
if (result != null)
{ // Clear
  RecognizedAudio resultRecognizedAudio = result.Audio;
  if (resultRecognizedAudio == null)
  {
    label.Text += String.Format(
            "  Emulated input\n");
  } else
  {
    label.Text += String.Format(
        "  Candidate Phrase at:       {0} mSec\n" +
        "  Phrase Length:             {1} mSec\n" +
        "  Input State Time:          {2}\n" +
        "  Input Format:              {3}\n",
        resultRecognizedAudio.AudioPosition.TotalMilliseconds,
        resultRecognizedAudio.Duration.TotalMilliseconds,
        resultRecognizedAudio.StartTime.ToShortTimeString(),
        resultRecognizedAudio.Format.EncodingFormat.ToString());
  }

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

RecognizedAudio Members
Microsoft.Speech.Recognition Namespace
SpeechRecognitionEngine
RecognitionEventArgs
SpeechHypothesizedEventArgs
SpeechRecognizedEventArgs
SpeechRecognitionRejectedEventArgs
SpeechHypothesized
SpeechRecognized
SpeechRecognitionRejected
SpeechHypothesized
SpeechRecognized
SpeechRecognitionRejected
SpeechRecognized
EmulateRecognize
EmulateRecognizeAsync
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedAudio Members

[image] [image]

RecognizedAudio Members
RecognizedAudio Class Methods Properties See Also Send Feedback

Represents audio input that is associated with a RecognitionResult.

The RecognizedAudio type exposes the following members.

Properties

 | Name | Description
Public property | AudioPosition | Gets the location in the input audio stream for the start of the recognized audio.
Public property | Duration | Gets the duration of the input audio stream for the recognized audio.
Public property | Format | Gets the format of the audio processed by a recognition engine.
Public property | StartTime | Gets the system time at the start of the recognition operation.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetRange | Selects and returns a section of the current recognized audio as binary data.
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Public method | WriteToAudioStream | Writes the entire audio to a stream as raw data.
Public method | WriteToWaveStream | Writes audio to a stream in Wave format.
Top

See Also

Reference

RecognizedAudio Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedAudio Methods

[image] [image]

RecognizedAudio Methods
RecognizedAudio Class See Also Send Feedback

The RecognizedAudio type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetRange | Selects and returns a section of the current recognized audio as binary data.
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Public method | WriteToAudioStream | Writes the entire audio to a stream as raw data.
Public method | WriteToWaveStream | Writes audio to a stream in Wave format.
Top

See Also

Reference

RecognizedAudio Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetRange Method

[image]

RecognizedAudio..::..GetRange Method
RecognizedAudio Class Example See Also Send Feedback

Selects and returns a section of the current recognized audio as binary data.

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

Syntax

Visual Basic (Declaration)
Public Function GetRange ( _
    audioPosition As TimeSpan, _
    duration As TimeSpan _
) As RecognizedAudio
Visual Basic (Usage)
Dim instance As RecognizedAudio
Dim audioPosition As TimeSpan
Dim duration As TimeSpan
Dim returnValue As RecognizedAudio

returnValue = instance.GetRange(audioPosition, _
    duration)
C#
public RecognizedAudio GetRange(
    TimeSpan audioPosition,
    TimeSpan duration
)

Parameters

audioPosition
Type: System..::..TimeSpan

The starting point of the audio data to be returned.

duration
Type: System..::..TimeSpan

The length of the segment to be returned.

Return Value

Type: Microsoft.Speech.Recognition..::..RecognizedAudio

Returns a RecognizedAudio instance that contains the subset of the original input selected by the values of audioPosition and duration.

Remarks

An ArgumentOutOfRangeException exception is thrown if audioPosition and duration attempt to reference beyond the bounds of the recognized audio.

Examples

The following example shows a testing routine that uses WriteToWaveStream, and WriteToAudioStream to write all of the recognized audio to a stream. It also uses GetRange to write selected portions of that audio to a stream.

Note Note

Because of the granularity of ticks and the non-zero size of the wave header, the size of a write to stream generated from a call such as GetRange(new TimeSpan (0), new TimeSpan (audio.Duration.Ticks / 2)0 may not be exactly half that of the write from calls such as WriteToWaveStream(waveStream) or WriteToAudioStream(audioStream). The following example takes this discrepancy into account.

C# Copy image Copy Code
public void AudioRangeTest (RecognitionResult recognitionResult)
{
  RecognizedAudio audio = recognitionResult.Audio;

  // Write audio to a stream using WriteToAudioStream.
  MemoryStream audioStream = new MemoryStream ();
  audio.WriteToAudioStream (audioStream);
  audioStream.Flush ();

  // Write audio to a stream using WriteToWave.
  MemoryStream waveStream = new MemoryStream ();
  audio.WriteToWaveStream (waveStream);
  waveStream.Flush ();

  // Check that the result of WriteToWave is slightly larger than the
  // result of WriteToAudioStream, due to Wave formatting.
  if (audioStream.Length != waveStream.Length - 16 ) )
   {
     MessageBox.Show(String.Format("Error: length of stream write by WriteToWaveStream(waveStream) is not 16 bytes larger than that of GetRange(new TimeSpan (0), audio.Duration)"));

  // Perform the same check for GetRange.
  Stream rangeStreamFull = new MemoryStream ();
  RecognizedAudio range = audio.GetRange (new TimeSpan (0), audio.Duration);
  range.WriteToWaveStream (rangeStreamFull);
  rangeStreamFull.Flush ();
  rangeStreamFull.Close ();
  if (rangeStreamFull.Length != audioStream.Length)
  {
    MessageBox.Show(String.Format("Error: length of stream write by WriteToAudioStream(waveStream) does not match that of GetRange(new TimeSpan (0), audio.Duration)"));
  }
  // Test retrieving the first half the audio.
  rangeStreamHalf = new MemoryStream ();
  range = audio.GetRange (new TimeSpan (0),
                   new TimeSpan (audio.Duration.Ticks / 2));
  range.WriteToWaveStream (rangeStreamHalf);
  rangeStreamHalf.Flush ();
  rangeStreamHalf.Close ();
  if ( !(rangeStreamHalf.Length >= waveStream.Length / 2 - 20)
         && (rangeStreamHalf.Length <= waveStream.Length / 2 + 50))
  {
    MessageBox.Show(String.Format("Error: When retrieving the first half of audio, length of audio.GetRange (new TimeSpan (0), new TimeSpan (audio.Duration.Ticks / 2)) is not approximately half that of WriteToWaveStream(waveStream)."));
  }
  // Test retrieving the second half the audio.
  rangeStream = new MemoryStream ();
  range = audio.GetRange (new TimeSpan (audio.Duration.Ticks / 2),
                   new TimeSpan (audio.Duration.Ticks / 2));
  range.WriteToWaveStream (rangeStream);
  rangeStream.Flush ();
  rangeStream.Close ();
  if ( !(rangeStreamHalf.Length >= waveStream.Length / 2 - 20)
         && rangeStreamHalf.Length <= waveStream.Length / 2 + 50))
  {
    MessageBox.Show(String.Format("Error: When retrieving the first half of audio, length of audio.GetRange (new TimeSpan (0), new TimeSpan (audio.Duration.Ticks / 2)) is not approximately half that of WriteToWaveStream(waveStream)."));
  }
}

See Also

Reference

RecognizedAudio Class
RecognizedAudio Members
Microsoft.Speech.Recognition Namespace
RecognizedAudio
WriteToWaveStream
WriteToAudioStream
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


WriteToAudioStream Method

[image]

RecognizedAudio..::..WriteToAudioStream Method
RecognizedAudio Class Example See Also Send Feedback

Writes the entire audio to a stream as raw data.

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

Syntax

Visual Basic (Declaration)
Public Sub WriteToAudioStream ( _
    outputStream As Stream _
)
Visual Basic (Usage)
Dim instance As RecognizedAudio
Dim outputStream As Stream

instance.WriteToAudioStream(outputStream)
C#
public void WriteToAudioStream(
    Stream outputStream
)

Parameters

outputStream
Type: System.IO..::..Stream

The stream that will receive the audio data.

Remarks

Audio data is written to outputStream in binary form. No header information is included.

The WriteToAudioStream method uses the Wave format, but does not include the Wave header. To include the Wave header, use the WriteToWaveStream method.

Examples

The example below show a testing routine that uses WriteToWaveStream, and WriteToAudioStream to write all the recognized audio to a stream, as well as GetRange to write selected portions of that audio to a stream.

Note Note

Because of the granularity of ticks and the non-zero size of the wave header, the size of a write to stream generated from a call such as GetRange(new TimeSpan(0), new TimeSpan(audio.Duration.Ticks / 2)) may not be exactly half that of the write from calls such as WriteToWaveStream(waveStream) or WriteToAudioStream(audioStream). The following example takes this discrepancy into account.

C# Copy image Copy Code
public void AudioRangeTest (RecognitionResult recognitionResult)
{
  RecognizedAudio audio = recognitionResult.Audio;

  // Write audio to a stream using WriteToAudioStream.
  MemoryStream audioStream = new MemoryStream ();
  audio.WriteToAudioStream (audioStream);
  audioStream.Flush ();

  // Write audio to a stream using WriteToWave.
  MemoryStream waveStream = new MemoryStream ();
  audio.WriteToWaveStream (waveStream);
  waveStream.Flush ();

  // Check that the result of WriteToWave is slightly larger than the
  // result of WriteToAudioStream, due to Wave formatting.
  if (audioStream.Length != waveStream.Length - 16 ) )
   {
     MessageBox.Show(String.Format("Error: length of stream write by WriteToWaveStream(waveStream) is not 16 bytes larger than that of GetRange(new TimeSpan (0), audio.Duration)"));

  // Perform the same check for GetRange.
  Stream rangeStreamFull = new MemoryStream ();
  RecognizedAudio range = audio.GetRange (new TimeSpan (0), audio.Duration);
  range.WriteToWaveStream (rangeStreamFull);
  rangeStreamFull.Flush ();
  rangeStreamFull.Close ();
  if (rangeStreamFull.Length != audioStream.Length)
  {
    MessageBox.Show(String.Format("Error: length of stream write by WriteToAudioStream(waveStream) does not match that of GetRange(new TimeSpan (0), audio.Duration)"));
  }
  // Test retrieving the first half the audio.
  rangeStreamHalf = new MemoryStream ();
  range = audio.GetRange (new TimeSpan (0),
                   new TimeSpan (audio.Duration.Ticks / 2));
  range.WriteToWaveStream (rangeStreamHalf);
  rangeStreamHalf.Flush ();
  rangeStreamHalf.Close ();
  if ( !(rangeStreamHalf.Length >= waveStream.Length / 2 - 20)
         && (rangeStreamHalf.Length <= waveStream.Length / 2 + 50))
  {
    MessageBox.Show(String.Format("Error: When retrieving the first half of audio, length of audio.GetRange (new TimeSpan (0), new TimeSpan (audio.Duration.Ticks / 2)) is not approximately half that of WriteToWaveStream(waveStream)."));
  }
  // Test retrieving the second half the audio.
  rangeStream = new MemoryStream ();
  range = audio.GetRange (new TimeSpan (audio.Duration.Ticks / 2),
                   new TimeSpan (audio.Duration.Ticks / 2));
  range.WriteToWaveStream (rangeStream);
  rangeStream.Flush ();
  rangeStream.Close ();
  if ( !(rangeStreamHalf.Length >= waveStream.Length / 2 - 20)
         && rangeStreamHalf.Length <= waveStream.Length / 2 + 50))
  {
    MessageBox.Show(String.Format("Error: When retrieving the first half of audio, length of audio.GetRange (new TimeSpan (0), new TimeSpan (audio.Duration.Ticks / 2)) is not approximately half that of WriteToWaveStream(waveStream)."));
  }
}

See Also

Reference

RecognizedAudio Class
RecognizedAudio Members
Microsoft.Speech.Recognition Namespace
RecognizedAudio
WriteToWaveStream
GetRange
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


WriteToWaveStream Method

[image]

RecognizedAudio..::..WriteToWaveStream Method
RecognizedAudio Class See Also Send Feedback

Writes audio to a stream in Wave format.

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

Syntax

Visual Basic (Declaration)
Public Sub WriteToWaveStream ( _
    outputStream As Stream _
)
Visual Basic (Usage)
Dim instance As RecognizedAudio
Dim outputStream As Stream

instance.WriteToWaveStream(outputStream)
C#
public void WriteToWaveStream(
    Stream outputStream
)

Parameters

outputStream
Type: System.IO..::..Stream

The stream that will receive the audio data.

Remarks

Audio data is written to outputStream in Wave format, which includes a resource interchange file format (RIFF) header.

The WriteToAudioStream method uses the same binary format, but does not include the Wave header.

See Also

Reference

RecognizedAudio Class
RecognizedAudio Members
Microsoft.Speech.Recognition Namespace
RecognizedAudio
WriteToAudioStream
GetRange
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedAudio Properties

[image] [image]

RecognizedAudio Properties
RecognizedAudio Class See Also Send Feedback

The RecognizedAudio type exposes the following members.

Properties

 | Name | Description
Public property | AudioPosition | Gets the location in the input audio stream for the start of the recognized audio.
Public property | Duration | Gets the duration of the input audio stream for the recognized audio.
Public property | Format | Gets the format of the audio processed by a recognition engine.
Public property | StartTime | Gets the system time at the start of the recognition operation.
Top

See Also

Reference

RecognizedAudio Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioPosition Property

[image]

RecognizedAudio..::..AudioPosition Property
RecognizedAudio Class Example See Also Send Feedback

Gets the location in the input audio stream for the start of the recognized audio.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioPosition As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As RecognizedAudio
Dim value As TimeSpan

value = instance.AudioPosition
C#
public TimeSpan AudioPosition { get; }

Property Value

Type: System..::..TimeSpan

The location in the input audio stream for the start of the recognized audio.

Remarks

This property references the position at the beginning of the recognized phrase in the input device's generated audio stream. By contrast, the RecognizerAudioPosition property references the recognizer's position within its audio input. These positions can be different. For more information, see Use Speech Recognition Events (Microsoft.Speech).

The StartTime property gets the system time at the start of the recognition operation.

Examples

The following example handles the SpeechRecognitionEngine..::..SpeechRecognized or Grammar..::..SpeechRecognized event and outputs to the console information about the recognized audio that is associated with the recognition result.

C# Copy image Copy Code
// Handle the SpeechRecognized event.
void SpeechRecognizedHandler(object sender, SpeechRecognizedEventArgs e)
{
  if (e.Result == null) return;

  RecognitionResult result = e.Result;

  Console.WriteLine("Grammar({0}): {1}",
    result.Grammar.Name, result.Text);

  if (e.Result.Audio != null)
  {
    RecognizedAudio audio = e.Result.Audio;

    Console.WriteLine("   start time: {0}", audio.StartTime);
    Console.WriteLine("   encoding format: {0}", audio.Format.EncodingFormat);
    Console.WriteLine("   position: {0}, duration: {1}",
      audio.AudioPosition, audio.Duration);
  }

  // Add event handler code here.
}

See Also

Reference

RecognizedAudio Class
RecognizedAudio Members
Microsoft.Speech.Recognition Namespace
StartTime
RecognizedAudio
Duration
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Duration Property

[image]

RecognizedAudio..::..Duration Property
RecognizedAudio Class Example See Also Send Feedback

Gets the duration of the input audio stream for the recognized audio.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Duration As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As RecognizedAudio
Dim value As TimeSpan

value = instance.Duration
C#
public TimeSpan Duration { get; }

Property Value

Type: System..::..TimeSpan

The duration within the input audio stream for the recognized audio.

Examples

The following example handles the SpeechRecognitionEngine..::..SpeechRecognized event and outputs to the console information about the recognized audio that is associated with the recognition result.

C# Copy image Copy Code
// Handle the SpeechRecognized event.
void SpeechRecognizedHandler(object sender, SpeechRecognizedEventArgs e)
{
  if (e.Result == null) return;

  RecognitionResult result = e.Result;

  Console.WriteLine("Grammar({0}): {1}",
    result.Grammar.Name, result.Text);

  if (e.Result.Audio != null)
  {
    RecognizedAudio audio = e.Result.Audio;

    Console.WriteLine("   start time: {0}", audio.StartTime);
    Console.WriteLine("   encoding format: {0}", audio.Format.EncodingFormat);
    Console.WriteLine("   position: {0}, duration: {1}",
      audio.AudioPosition, audio.Duration);
  }

  // Add event handler code here.
}

See Also

Reference

RecognizedAudio Class
RecognizedAudio Members
Microsoft.Speech.Recognition Namespace
StartTime
RecognizedAudio
AudioPosition
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Format Property

[image]

RecognizedAudio..::..Format Property
RecognizedAudio Class Example See Also Send Feedback

Gets the format of the audio processed by a recognition engine.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Format As SpeechAudioFormatInfo
    Get
Visual Basic (Usage)
Dim instance As RecognizedAudio
Dim value As SpeechAudioFormatInfo

value = instance.Format
C#
public SpeechAudioFormatInfo Format { get; }

Property Value

Type: Microsoft.Speech.AudioFormat..::..SpeechAudioFormatInfo

The format of the audio processed by the speech recognizer.

Examples

The following example handles the SpeechRecognitionEngine..::..SpeechRecognized event and outputs to the console information about the recognized audio that is associated with the recognition result.

C# Copy image Copy Code
// Handle the SpeechRecognized event.
void SpeechRecognizedHandler(object sender, SpeechRecognizedEventArgs e)
{
  if (e.Result == null) return;

  RecognitionResult result = e.Result;

  Console.WriteLine("Grammar({0}): {1}",
    result.Grammar.Name, result.Text);

  if (e.Result.Audio != null)
  {
    RecognizedAudio audio = e.Result.Audio;

    Console.WriteLine("   start time: {0}", audio.StartTime);
    Console.WriteLine("   encoding format: {0}", audio.Format.EncodingFormat);
    Console.WriteLine("   position: {0}, duration: {1}",
      audio.AudioPosition, audio.Duration);
  }

  // Add event handler code here.
}

See Also

Reference

RecognizedAudio Class
RecognizedAudio Members
Microsoft.Speech.Recognition Namespace
SpeechAudioFormatInfo
RecognizedAudio
Duration
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartTime Property

[image]

RecognizedAudio..::..StartTime Property
RecognizedAudio Class Example See Also Send Feedback

Gets the system time at the start of the recognition operation.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property StartTime As DateTime
    Get
Visual Basic (Usage)
Dim instance As RecognizedAudio
Dim value As DateTime

value = instance.StartTime
C#
public DateTime StartTime { get; }

Property Value

Type: System..::..DateTime

The system time at the start of the recognition operation.

Remarks

The StartTime property gets the system time at the start of the recognition operation, which can be useful for latency and performance calculations.

The AudioPosition property gets the location in the input device's generated audio stream.

Examples

The following example handles the SpeechRecognitionEngine..::..SpeechRecognized event and outputs to the console information about the recognized audio that is associated with the recognition result.

C# Copy image Copy Code
// Handle the SpeechRecognized event.
void SpeechRecognizedHandler(object sender, SpeechRecognizedEventArgs e)
{
  if (e.Result == null) return;

  RecognitionResult result = e.Result;

  Console.WriteLine("Grammar({0}): {1}",
    result.Grammar.Name, result.Text);

  if (e.Result.Audio != null)
  {
    RecognizedAudio audio = e.Result.Audio;

    Console.WriteLine("   start time: {0}", audio.StartTime);
    Console.WriteLine("   encoding format: {0}", audio.Format.EncodingFormat);
    Console.WriteLine("   position: {0}, duration: {1}",
      audio.AudioPosition, audio.Duration);
  }

  // Add event handler code here.
}

See Also

Reference

RecognizedAudio Class
RecognizedAudio Members
Microsoft.Speech.Recognition Namespace
AudioPosition
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedPhrase Class

[image]

RecognizedPhrase Class
Members Example See Also Send Feedback

Contains detailed information, generated by the speech recognition engine, about the recognized input.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..RecognizedPhrase
Microsoft.Speech.Recognition..::..RecognitionResult

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class RecognizedPhrase
Visual Basic (Usage)
Dim instance As RecognizedPhrase
C#
[SerializableAttribute]
public class RecognizedPhrase

Remarks

This class contains detailed information about words and phrases processed during speech recognition operations, including the following:

  • The Grammar property references the Grammar that the recognizer used to identify the input.

  • The Text property contains the normalized text for the phrase.

  • The Semantics property references the semantic information contained in the result. The semantic information is a dictionary of the key names and associated semantic data.

  • The Words property contains an ordered collection of RecognizedWordUnit objects that represent each recognized word in the input. Each word unit contains display format, lexical format, and pronunciation information for the corresponding word.

  • The ReplacementWordUnits property contains information about specialized word substitution.

  • The Homophones and HomophoneGroupId properties contain information about recognition alternates that have the same or similar pronunciation.

  • The value of the Confidence property indicates the degree of certainty, assigned by the speech recognizer, that a recognized phrase matches the input.

The speech recognizer returns recognition results in a RecognitionResult object, which inherits from RecognizedPhrase. The recognition result Alternates property contains an ordered collection of RecognizedPhrase objects, each of which is a possible match for the input to the recognizer.

Examples

The following example shows a handler for a SpeechRecognitionEngine..::..SpeechRecognized or Grammar..::..SpeechRecognized event and some of the information associated with the RecognitionResult object. The RecognitionResult class derives from the RecognizedPhrase class.

C# Copy image Copy Code
void SpeechRecognizedHandler(object sender, SpeechRecognizedEventArgs e)
{
  if (e.Result == null) return;

  // Add event handler code here.

  // The following code illustrates some of the information available
  // in the recognition result.
  Console.WriteLine("Recognition result summary:");
  Console.WriteLine(
    "  Recognized phrase: {0}\n" +
    "  Confidence score {1}\n" +
    "  Grammar used: {2}\n",
    e.Result.Text, e.Result.Confidence, e.Result.Grammar.Name);

  // Display the semantic values in the recognition result.
  Console.WriteLine("  Semantic results:");
  foreach (KeyValuePair<String, SemanticValue> child in e.Result.Semantics)
  {
    Console.WriteLine("    The {0} city is {1}",
      child.Key, child.Value.Value ?? "null");
  }
  Console.WriteLine();

  // Display information about the words in the recognition result.
  Console.WriteLine("  Word summary: ");
  foreach (RecognizedWordUnit word in e.Result.Words)
  {
    Console.WriteLine(
      "    Lexical form ({1})" +
      " Pronunciation ({0})" +
      " Display form ({2})",
      word.Pronunciation, word.LexicalForm, word.DisplayAttributes);
  }

  // Display information about the audio in the recognition result.
  Console.WriteLine("  Input audio summary:\n" +
    "    Candidate Phrase at:       {0} mSec\n" +
    "    Phrase Length:             {1} mSec\n" +
    "    Input State Time:          {2}\n" +
    "    Input Format:              {3}\n",
    e.Result.Audio.AudioPosition,
    e.Result.Audio.Duration,
    e.Result.Audio.StartTime,
    e.Result.Audio.Format.EncodingFormat);

  // Display information about the alternate recognitions in the recognition result.
  Console.WriteLine("  Alternate phrase collection:");
  foreach (RecognizedPhrase phrase in e.Result.Alternates)
  {
    Console.WriteLine("    Phrase: " + phrase.Text);
    Console.WriteLine("    Confidence score: " + phrase.Confidence);
  }
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

RecognizedPhrase Members
Microsoft.Speech.Recognition Namespace
RecognitionResult
RecognizedWordUnit
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedPhrase Members

[image] [image]

RecognizedPhrase Members
RecognizedPhrase Class Methods Properties See Also Send Feedback

Contains detailed information, generated by the speech recognition engine, about the recognized input.

The RecognizedPhrase type exposes the following members.

Properties

 | Name | Description
Public property | Confidence | Gets a value, assigned by the recognizer, that represents the likelihood that a RecognizedPhrase matches a given input.
Public property | Grammar | Gets the Grammar object that the speech recognizer used to return the RecognizedPhrase.
Public property | HomophoneGroupId | Infrastructure. Gets the identifier for the homophone group for the phrase.
Public property | Homophones | Gets a collection of the recognition alternates that have the same pronunciation as this recognized phrase.
Public property | ReplacementWordUnits | Gets information about the text that the speech recognizer changed as part of speech-to-text normalization.
Public property | Semantics | Gets the semantic information that is associated with the recognized phrase.
Public property | Text | Gets the normalized text generated by a speech recognition engine from recognized input.
Public property | Words | Gets the words generated by a speech recognizer from recognized input.
Top

Methods

 | Name | Description
Public method | ConstructSmlFromSemantics | Returns a semantic markup language (SML) document for the semantic information in the RecognizedPhrase object.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

RecognizedPhrase Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedPhrase Methods

[image] [image]

RecognizedPhrase Methods
RecognizedPhrase Class See Also Send Feedback

The RecognizedPhrase type exposes the following members.

Methods

 | Name | Description
Public method | ConstructSmlFromSemantics | Returns a semantic markup language (SML) document for the semantic information in the RecognizedPhrase object.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

RecognizedPhrase Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ConstructSmlFromSemantics Method

[image]

RecognizedPhrase..::..ConstructSmlFromSemantics Method
RecognizedPhrase Class Example See Also Send Feedback

Returns a semantic markup language (SML) document for the semantic information in the RecognizedPhrase object.

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

Syntax

Visual Basic (Declaration)
Public Function ConstructSmlFromSemantics As IXPathNavigable
Visual Basic (Usage)
Dim instance As RecognizedPhrase
Dim returnValue As IXPathNavigable

returnValue = instance.ConstructSmlFromSemantics()
C#
public IXPathNavigable ConstructSmlFromSemantics()

Return Value

Type: System.Xml.XPath..::..IXPathNavigable

Returns an SML description of the semantics of the RecognizedPhrase as an XPath navigable object.

Examples

In the following example, a method returns a string that contains the SML for the semantics of a recognized phrase.

Copy image Copy Code
private string GetSemanticsSML(RecognizedPhrase result)
{
  if (result.Semantics.Count > 0)
  {
    return result.ConstructSmlFromSemantics().CreateNavigator().OuterXml;
  }
  else
  {
    return null;
  }
}

See Also

Reference

RecognizedPhrase Class
RecognizedPhrase Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedPhrase Properties

[image] [image]

RecognizedPhrase Properties
RecognizedPhrase Class See Also Send Feedback

The RecognizedPhrase type exposes the following members.

Properties

 | Name | Description
Public property | Confidence | Gets a value, assigned by the recognizer, that represents the likelihood that a RecognizedPhrase matches a given input.
Public property | Grammar | Gets the Grammar object that the speech recognizer used to return the RecognizedPhrase.
Public property | HomophoneGroupId | Infrastructure. Gets the identifier for the homophone group for the phrase.
Public property | Homophones | Gets a collection of the recognition alternates that have the same pronunciation as this recognized phrase.
Public property | ReplacementWordUnits | Gets information about the text that the speech recognizer changed as part of speech-to-text normalization.
Public property | Semantics | Gets the semantic information that is associated with the recognized phrase.
Public property | Text | Gets the normalized text generated by a speech recognition engine from recognized input.
Public property | Words | Gets the words generated by a speech recognizer from recognized input.
Top

See Also

Reference

RecognizedPhrase Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Confidence Property

[image]

RecognizedPhrase..::..Confidence Property
RecognizedPhrase Class Example See Also Send Feedback

Gets a value, assigned by the recognizer, that represents the likelihood that a RecognizedPhrase matches a given input.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Confidence As Single
    Get
Visual Basic (Usage)
Dim instance As RecognizedPhrase
Dim value As Single

value = instance.Confidence
C#
public float Confidence { get; }

Property Value

Type: System..::..Single

A relative measure of the certainty of correct recognition of a phrase. The value is from 0.0 to 1.0, for low to high confidence, respectively.

Remarks

Confidence scores do not indicate the absolute likelihood that a phrase was recognized correctly. Instead, confidence scores provide a mechanism for comparing the relative accuracy of multiple recognition alternates for a given input. This facilitates returning the most accurate recognition result. For example, if a recognized phrase has a confidence score of 0.8, this does not mean that the phrase has an 80% chance of being the correct match for the input. It means that the phrase is more likely to be the correct match for the input than other results that have confidence scores less than 0.8.

A confidence score on its own is not meaningful unless you have alternative results to compare against, either from the same recognition operation or from previous recognitions of the same input. The values are used to rank alternative candidate phrases returned by the Alternates property on RecognitionResult objects.

Confidence values are relative and unique to each recognition engine. Confidence values returned by two different recognition engines cannot be meaningfully compared.

A speech recognition engine may assign a low confidence score to spoken input for various reasons, including background interference, inarticulate speech, or unanticipated words or word sequences. If your application is using a SpeechRecognitionEngine instance, you can modify the confidence level at which speech input is accepted or rejected with one of the UpdateRecognizerSetting()()()() methods.

The Alternates property of the RecognitionResult object contains an ordered collection of RecognizedPhrase objects, each of which is a possible match for the input to the recognizer. The alternates are ordered from highest to lowest confidence.

Examples

The following example shows a handler for a SpeechRecognitionEngine..::..SpeechRecognized or Grammar..::..SpeechRecognized event. The example shows information associated with the RecognitionResult object, some of which is derived from RecognizedPhrase. The handler displays confidence scores for a recognized phrase as well as for recognition alternates.

C# Copy image Copy Code
void SpeechRecognizedHandler(object sender, SpeechRecognizedEventArgs e)
{
  if (e.Result == null) return;

  // Add event handler code here.

  // The following code illustrates some of the information available
  // in the recognition result.
  Console.WriteLine("Recognition result summary:");
  Console.WriteLine(
    "  Recognized phrase: {0}\n" +
    "  Confidence score {1}\n" +
    "  Grammar used: {2}\n",
    e.Result.Text, e.Result.Confidence, e.Result.Grammar.Name);

  // Display the semantic values in the recognition result.
  Console.WriteLine("  Semantic results:");
  foreach (KeyValuePair<String, SemanticValue> child in e.Result.Semantics)
  {
    Console.WriteLine("    The {0} city is {1}",
      child.Key, child.Value.Value ?? "null");
  }
  Console.WriteLine();

  // Display information about the words in the recognition result.
  Console.WriteLine("  Word summary: ");
  foreach (RecognizedWordUnit word in e.Result.Words)
  {
    Console.WriteLine(
      "    Lexical form ({1})" +
      " Pronunciation ({0})" +
      " Display form ({2})",
      word.Pronunciation, word.LexicalForm, word.DisplayAttributes);
  }

  // Display information about the audio in the recognition result.
  Console.WriteLine("  Input audio summary:\n" +
    "    Candidate Phrase at:       {0} mSec\n" +
    "    Phrase Length:             {1} mSec\n" +
    "    Input State Time:          {2}\n" +
    "    Input Format:              {3}\n",
    e.Result.Audio.AudioPosition,
    e.Result.Audio.Duration,
    e.Result.Audio.StartTime,
    e.Result.Audio.Format.EncodingFormat);

  // Display information about the alternate recognitions in the recognition result.
  Console.WriteLine("  Alternate phrase collection:");
  foreach (RecognizedPhrase phrase in e.Result.Alternates)
  {
    Console.WriteLine("    Phrase: " + phrase.Text);
    Console.WriteLine("    Confidence score: " + phrase.Confidence);
  }
}

See Also

Reference

RecognizedPhrase Class
RecognizedPhrase Members
Microsoft.Speech.Recognition Namespace
RecognitionResult
RecognizedWordUnit
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammar Property

[image]

RecognizedPhrase..::..Grammar Property
RecognizedPhrase Class See Also Send Feedback

Gets the Grammar object that the speech recognizer used to return the RecognizedPhrase.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Grammar As Grammar
    Get
Visual Basic (Usage)
Dim instance As RecognizedPhrase
Dim value As Grammar

value = instance.Grammar
C#
public Grammar Grammar { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..Grammar

The grammar object that the speech recognizer used to identify the input.

See Also

Reference

RecognizedPhrase Class
RecognizedPhrase Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


HomophoneGroupId Property

[image]

RecognizedPhrase..::..HomophoneGroupId Property
RecognizedPhrase Class See Also Send Feedback

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

Gets the identifier for the homophone group for the phrase.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property HomophoneGroupId As Integer
    Get
Visual Basic (Usage)
Dim instance As RecognizedPhrase
Dim value As Integer

value = instance.HomophoneGroupId
C#
public int HomophoneGroupId { get; }

Property Value

Type: System..::..Int32

The identifier for the homophone group for the phrase.

Remarks

The speech recognizer assigns a group identifier to all recognition alternates that have the same pronunciation. For each alternate that has a unique pronunciation, the recognizer creates a homophone group. The speech recognizer generates new group of identifiers for each recognition operation, and the identifiers cannot be used to compare alternates from generated from separate recognition operations.

For example, for a recognition result that contained the alternates "the tale", "the tail", and "the ale", the first two alternates would belong to one homophone group, and the last alternate would be the single member of a second homophone group.

See Also

Reference

RecognizedPhrase Class
RecognizedPhrase Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Homophones Property

[image]

RecognizedPhrase..::..Homophones Property
RecognizedPhrase Class Example See Also Send Feedback

Gets a collection of the recognition alternates that have the same pronunciation as this recognized phrase.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Homophones As ReadOnlyCollection(Of RecognizedPhrase)
    Get
Visual Basic (Usage)
Dim instance As RecognizedPhrase
Dim value As ReadOnlyCollection(Of RecognizedPhrase)

value = instance.Homophones
C#
public ReadOnlyCollection<RecognizedPhrase> Homophones { get; }

Property Value

Type: System.Collections.ObjectModel..::..ReadOnlyCollection <(Of <(<' RecognizedPhrase >)>)>

A read-only collection of the recognition alternates that have the same pronunciation as this recognized phrase.

Remarks

This property returns all other recognition alternates that have the same pronunciation as this recognized phrase.

For example, for a recognition result that contained the alternates, "the tale" and "the tail", the homophones collection for the first alternate, "the tale", would contain the second phrase, "the tail". The homophones collection for the second alternate, "the tail", would contain the first phrase, "the tale".

Examples

The code fragment and utility method shown below display the Text property of the RecognizedPhrase instances returned by the Homophones property to a ListControl on a user interface.

C# Copy image Copy Code
Utils.DisplayDataOnListBox(_recognizedPhraseHomophonesListBox, _recognizedPhrase.Homophones, "Text");

/*
 *
 */
// Updates alternates list with alternates of the result.
internal static void DisplayDataOnListBox(ListControl list, object dataSource, string displayMember)
{
  list.DataSource = dataSource; //result.Alternates;
  list.DisplayMember = displayMember; //"Text";
}

See Also

Reference

RecognizedPhrase Class
RecognizedPhrase Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ReplacementWordUnits Property

[image]

RecognizedPhrase..::..ReplacementWordUnits Property
RecognizedPhrase Class Example See Also Send Feedback

Gets information about the text that the speech recognizer changed as part of speech-to-text normalization.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property ReplacementWordUnits As Collection(Of ReplacementText)
    Get
Visual Basic (Usage)
Dim instance As RecognizedPhrase
Dim value As Collection(Of ReplacementText)

value = instance.ReplacementWordUnits
C#
public Collection<ReplacementText> ReplacementWordUnits { get; }

Property Value

Type: System.Collections.ObjectModel..::..Collection <(Of <(<' ReplacementText >)>)>

A collection of ReplacementText objects that describe sections of text that the speech recognizer replaced when it normalized the recognized input.

Remarks

As part of the speech recognition process, the speech recognizer normalizes the recognized input into a display form.

For example, the spoken input, "twenty five dollars", generates a recognition result where the Words property contains the words, "twenty", "five", and "dollars", and the Text property contains the phrase, "$25.00". For more information about text normalization, see the ReplacementText class.

Examples

In the example below, information about a RecognizedPhrase object returned by a recognition engine is displayed to a user interface.

C# Copy image Copy Code
internal static void DisplayBasicPhraseInfo(Label label, RecognizedPhrase result, SpeechRecognitionEngine recognizer)
{
  if (result != null && label != null)
  {// Blank
    if (recognizer != null)
    { // Clear
      label.Text += String.Format(
          "  Recognizer currently at:   {0} mSec\n" +
          "  Audio Device currently at: {1} mSec\n",
          recognizer.RecognizerAudioPosition.TotalMilliseconds,
          recognizer.AudioPosition.TotalMilliseconds);
    }

    if (result != null)
    { // Clear
      RecognitionResult recResult = result as RecognitionResult;
      if (recResult != null)
      {
        RecognizedAudio resultRecognizedAudio = recResult.Audio;
        if (resultRecognizedAudio == null)
        {
          label.Text += String.Format("  Emulated input\n");
        }
        else
        {
          label.Text += String.Format(
            "  Candidate Phrase at:       {0} mSec\n" +
            "  Phrase Length:             {1} mSec\n" +
            "  Input State Time:          {2}\n" +
            "  Input Format:              {3}\n",
            resultRecognizedAudio.AudioPosition.TotalMilliseconds,
            resultRecognizedAudio.Duration.TotalMilliseconds,
            resultRecognizedAudio.StartTime.ToShortTimeString(),
            resultRecognizedAudio.Format.EncodingFormat.ToString());
        }
      }

      label.Text += String.Format("  Confidence Level:          {0}\n", result.Confidence);
      if (result.Grammar != null)
      {
        label.Text += String.Format(
            "  Recognizing Grammar:       {0}\n" +
            "  Recognizing Rule:          {1}\n",
            ((result.Grammar.Name != null) ? (result.Grammar.Name) : "None"),
            ((result.Grammar.RuleName != null) ? (result.Grammar.RuleName) : "None"));
      }

      if (result.ReplacementWordUnits.Count != 0)
      {
        label.Text += String.Format("  Replacement text:\n");
        foreach (ReplacementText rep in result.ReplacementWordUnits)
        {
          label.Text += String.Format("      At index {0} for {1} words. Text: {2}\n",
          rep.FirstWordIndex, rep.CountOfWords, rep.Text);
        }
        label.Text+=String.Format("\n\n");

      }
    }

  }
}

See Also

Reference

RecognizedPhrase Class
RecognizedPhrase Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Semantics Property

[image]

RecognizedPhrase..::..Semantics Property
RecognizedPhrase Class Example See Also Send Feedback

Gets the semantic information that is associated with the recognized phrase.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Semantics As SemanticValue
    Get
Visual Basic (Usage)
Dim instance As RecognizedPhrase
Dim value As SemanticValue

value = instance.Semantics
C#
public SemanticValue Semantics { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..SemanticValue

The semantic information associated with the recognized phrase.

Remarks

A speech recognition grammar can include semantic information. When a speech recognizer generates a recognition result for such a grammar, the semantic information might be included in the recognition result, according to the rules of the grammar and the input to the recognizer. For more information about semantic information, see Create and Access Semantic Content (Microsoft.Speech) and the and the SemanticResultKey and SemanticResultValue classes.

Examples

The following example defines a method that gets specific semantic information from a recognized phrase. When this method returns, it contains the value for the semantic key, or null if the value was not retrieved. This method checks only for top-level keys. Since the semantic information is contained in a tree of values, lower-level keys must be accessed through the returned semantic value.

Copy image Copy Code
static bool TryGetSemanticValue(
      RecognizedPhrase phrase, string key, out SemanticValue value)
{
  value = null;
  bool found = phrase.Semantics.ContainsKey(key);
  if (found)
  {
    value = phrase.Semantics[key];
  }

  return found;
}

See Also

Reference

RecognizedPhrase Class
RecognizedPhrase Members
Microsoft.Speech.Recognition Namespace
SemanticResultKey
SemanticResultValue
SemanticValue
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Text Property

[image]

RecognizedPhrase..::..Text Property
RecognizedPhrase Class Example See Also Send Feedback

Gets the normalized text generated by a speech recognition engine from recognized input.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Text As String
    Get
Visual Basic (Usage)
Dim instance As RecognizedPhrase
Dim value As String

value = instance.Text
C#
public string Text { get; }

Property Value

Type: System..::..String

The normalized text generated by a speech recognition engine from recognized input.

Remarks

As part of the speech recognition process, the speech recognition engine performs speech-to-text normalization of the recognized input into a display form.

For example, the spoken input, "twenty five dollars", generates a recognition result where the Words property contains the words, "twenty", "five", and "dollars", and the Text property contains the phrase, "$25.00". For more information about text normalization, see ReplacementText.

Examples

The example below is a handler for displaying to a user interface the result of recognition events. The handler uses Text on an instance of RecognizedPhraseto display the recognized text from the recognition candidate in the Alternates collection with the highest Confidence score.

C# Copy image Copy Code
private void DisplayResult(EventArgs eventArgs)
{
  // Make sure all different event types are supported.
  RecognitionResult result = null;
  if (null != (eventArgs as RecognitionEventArgs))
  {
    result = (eventArgs as RecognitionEventArgs).Result;
  }
  else if (null != (eventArgs as EmulateRecognizeCompletedEventArgs))
  {
    result = (eventArgs as EmulateRecognizeCompletedEventArgs).Result;
  }

  // In all cases, clear results, semantic XML, semantics tree, and alternates.
  _recognitionSmlBrowser.Navigate("about:blank");
  _semanticsTreeView.Nodes.Clear();
  //            _candidateList.Items.Clear();
  _candidateList.DataSource = null;
  _candidateList.DisplayMember = null;
  _phraseInfoLabel.Text = "";
  _bestCandidateTextBox.Text = "";

  if (result != null)
  {
    // Obtain result from RecognitionEventArg passed in.
    // Set Text color on the basis of the event type passed in.
    switch (eventArgs.GetType().ToString())
    {
      case "Microsoft.Speech.Recognition.SpeechHypothesizedEventArgs":
        _bestCandidateTextBox.ForeColor = Color.Black;
        _bestCandidateTextBox.Text = result.Text;
        _phraseInfoLabel.Text = null;
        break;
      case "Microsoft.Speech.Recognition.SpeechRecognitionRejectedEventArgs":
        _bestCandidateTextBox.ForeColor = Color.OrangeRed;
        _bestCandidateTextBox.Text = "Unable to Recognize Input";
        _phraseInfoLabel.Text = String.Format("Rejected Phrase Information\n");
        Utils.DisplayBasicPhraseInfo(_phraseInfoLabel, result, _recognizer);
        Utils.DisplaySemanticsSML(_recognitionSmlBrowser, result);
        Utils.DisplaySemanticsTreeView(_semanticsTreeView, result.Semantics);
        break;
      case "Microsoft.Speech.Recognition.SpeechRecognizedEventArgs":
        _bestCandidateTextBox.ForeColor = Color.Green;
        _bestCandidateTextBox.Text = result.Text;
        _phraseInfoLabel.Text = String.Format("Recognized Phrase Information\n");

        Utils.DisplayBasicPhraseInfo(_phraseInfoLabel, result, _recognizer);
        Utils.DisplaySemanticsSML(_recognitionSmlBrowser, result);
        Utils.DisplaySemanticsTreeView(_semanticsTreeView, result.Semantics);
        break;
      case "Microsoft.Speech.Recognition.EmulateRecognizeCompletedEventArgs":
        _bestCandidateTextBox.ForeColor = Color.Green;
        _bestCandidateTextBox.Text = result.Text;
        _phraseInfoLabel.Text = String.Format("Recognized Phrase Information\n");
        Utils.DisplayBasicPhraseInfo(_phraseInfoLabel, result, _recognizer);
        Utils.DisplaySemanticsSML(_recognitionSmlBrowser, result);
        Utils.DisplaySemanticsTreeView(_semanticsTreeView, result.Semantics);
        break;
      default:
        _bestCandidateTextBox.ForeColor = Color.Black;
        break;
    }

    Utils.DisplayDataOnListBox(_candidateList, result.Alternates, "Text");

  }
}

See Also

Reference

RecognizedPhrase Class
RecognizedPhrase Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Words Property

[image]

RecognizedPhrase..::..Words Property
RecognizedPhrase Class Example See Also Send Feedback

Gets the words generated by a speech recognizer from recognized input.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Words As ReadOnlyCollection(Of RecognizedWordUnit)
    Get
Visual Basic (Usage)
Dim instance As RecognizedPhrase
Dim value As ReadOnlyCollection(Of RecognizedWordUnit)

value = instance.Words
C#
public ReadOnlyCollection<RecognizedWordUnit> Words { get; }

Property Value

Type: System.Collections.ObjectModel..::..ReadOnlyCollection <(Of <(<' RecognizedWordUnit >)>)>

The collection of RecognizedWordUnit objects generated by a speech recognizer for recognized input.

Remarks

This property contains the words produced from the input by the speech recognizer prior to the recognizer's speech-to-text normalization of the result.

For example, the spoken input, "twenty five dollars", generates a recognition result where the Words property contains the words, "twenty", "five", and "dollars", and the Text property contains the phrase, "$25.00". For more information about text normalization, see ReplacementText.

Examples

The example code fragment and utility method below, show an application calling the utility method to process the ReadOnlyCollection of RecognizedWordUnit objects and display them to a user interface.

C# Copy image Copy Code
_inputPhraseTextBox.Text = Utils.GetDisplay(_recognizedPhrase.Words);
/*
 *
 */
internal static string GetDisplay(ReadOnlyCollection<RecognizedWordUnit> Words)
{
  StringBuilder sb = new StringBuilder();
  DisplayAttributes displayAttribute;
  string text;
  for (int i = 0; i < Words.Count; i++)
  {
    displayAttribute = Words[i].DisplayAttributes;
    text = Words[i].Text;

    // Remove leading spaces
    if ((displayAttribute & DisplayAttributes.ConsumeLeadingSpaces) != 0)
    {
      while (sb.Length > 0 && char.IsWhiteSpace(sb[sb.Length - 1]))
      {
        sb.Remove(sb.Length - 1, 1);
      }
    }

    // Append text
    sb.Append(text);

    // Add trailing spaces
    if ((displayAttribute & DisplayAttributes.ZeroTrailingSpaces) != 0)
    {
      // no action
    }
    else if ((displayAttribute & DisplayAttributes.OneTrailingSpace) != 0)
    {
      sb.Append(" ");
    }
    else if ((displayAttribute & DisplayAttributes.TwoTrailingSpaces) != 0)
    {
      sb.Append("  ");
    }
  }
  return sb.ToString().Trim();
}

See Also

Reference

RecognizedPhrase Class
RecognizedPhrase Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedWordUnit Class

[image]

RecognizedWordUnit Class
Members Example See Also Send Feedback

Provides the atomic unit of recognized speech.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..RecognizedWordUnit

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class RecognizedWordUnit
Visual Basic (Usage)
Dim instance As RecognizedWordUnit
C#
[SerializableAttribute]
public class RecognizedWordUnit

Remarks

All results returned by a recognition engine are constructed of RecognizedWordUnit objects.

An array of RecognizedWordUnit objects is accessible for any recognition operations through the Words property on the RecognizedPhrase object.

Addition to providing a measure of recognition certainty (Confidence) an instance of RecognizedWordUnit provides:

  • Normalized and exact (or lexical) text representations for a recognized word. For more information, see ReplacementText, Text, and LexicalForm.

    Note Note

    Normalization of text from speech input is the use of special constructs or symbols to express speech in writing. For example, normalization can replace the spoken words "a dollar and sixteen cents" with "$1.16" in output text.

  • Pronunciation information using characters from a supported phonetic alphabet, such as the International Phonetic Alphabet (IPA) or the Universal Phone Set (UPS). For more information see Pronunciation.

  • Printing formatting. For more information see DisplayAttributes and DisplayAttributes.

Examples

The example below shows a utility routine (stringFromWordArray) that generates strings containing lexical output (using LexicalForm), normalized text (using Text), or a phonetic information in the International Phonetic Alphabet (using Pronunciation). Strings are formatted using DisplayAttributes objects obtained from the DisplayAttributes property, from a ReadOnlyCollection of RecognizedWordUnit objects. The RecognizedWordUnit objects are obtained from the Words property on the RecognizedPhrase object.

C# Copy image Copy Code
internal enum WordType {
          Text,
          Normalized = Text,
          Lexical,
          Pronunciation
}
C# Copy image Copy Code
internal static string stringFromWordArray(ReadOnlyCollection<RecognizedWordUnit> words, WordType type)
{
  string text = "";
  foreach (RecognizedWordUnit word in words)
  {
    string wordText = "";
    if (type == WordType.Text || type == WordType.Normalized)
    {
      wordText = word.Text;
    }
    else if (type == WordType.Lexical)
    {
      wordText = word.LexicalForm;
    }
    else if (type == WordType.Pronunciation)
    {
      wordText = word.Pronunciation;
    }
    else
    {
      throw new InvalidEnumArgumentException(String.Format("[0}: is not a valid input", type));
    }
    // Use display attribute

    if ((word.DisplayAttributes & DisplayAttributes.OneTrailingSpace) != 0)
    {
      wordText += " ";
    }
    if ((word.DisplayAttributes & DisplayAttributes.TwoTrailingSpaces) != 0)
    {
      wordText += "  ";
    }
    if ((word.DisplayAttributes & DisplayAttributes.ConsumeLeadingSpaces) != 0)
    {
      wordText = wordText.TrimStart();
    }
    if ((word.DisplayAttributes & DisplayAttributes.ZeroTrailingSpaces) != 0)
    {
      wordText = wordText.TrimEnd();
    }

    text += wordText;

  }
  return text;
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

RecognizedWordUnit Members
Microsoft.Speech.Recognition Namespace
DisplayAttributes
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedWordUnit Members

[image] [image]

RecognizedWordUnit Members
RecognizedWordUnit Class Constructors Methods Properties See Also Send Feedback

Provides the atomic unit of recognized speech.

The RecognizedWordUnit type exposes the following members.

Constructors

 | Name | Description
Public method | RecognizedWordUnit | Initializes a new instance of the RecognizedWordUnit class.
Top

Properties

 | Name | Description
Public property | AudioDuration | Gets the time interval that represents the length of the audio signal for the word.
Public property | AudioPosition | Gets the location in the input device's audio stream when recognition of the word began.
Public property | Confidence | Gets a value, assigned by the recognizer, that represents the likelihood that a recognized word matches a given input.
Public property | DisplayAttributes | Gets formatting information used in creating the text output from the current RecognizedWordUnit instance.
Public property | LexicalForm | Gets the unnormalized text of a recognized word.
Public property | Pronunciation | Gets the phonetic spelling of a recognized word.
Public property | Text | Gets the normalized text for a recognized word.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

RecognizedWordUnit Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedWordUnit Constructor

[image]

RecognizedWordUnit Constructor
RecognizedWordUnit Class Example See Also Send Feedback

Initializes a new instance of the RecognizedWordUnit class.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    text As String, _
    confidence As Single, _
    pronunciation As String, _
    lexicalForm As String, _
    displayAttributes As DisplayAttributes, _
    audioPosition As TimeSpan, _
    audioDuration As TimeSpan _
)
Visual Basic (Usage)
Dim text As String
Dim confidence As Single
Dim pronunciation As String
Dim lexicalForm As String
Dim displayAttributes As DisplayAttributes
Dim audioPosition As TimeSpan
Dim audioDuration As TimeSpan

Dim instance As New RecognizedWordUnit(text, confidence, _
    pronunciation, lexicalForm, displayAttributes, _
    audioPosition, audioDuration)
C#
public RecognizedWordUnit(
    string text,
    float confidence,
    string pronunciation,
    string lexicalForm,
    DisplayAttributes displayAttributes,
    TimeSpan audioPosition,
    TimeSpan audioDuration
)

Parameters

text
Type: System..::..String

The normalized text for a recognized word.

This value may be nullNothingnullptrunita null reference (Nothing in Visual Basic), "", or Empty.

confidence
Type: System..::..Single

A float value from 0.0 through 1.0 indicating the certainty of word recognition.

pronunciation
Type: System..::..String

The phonetic spelling of a recognized word.

This value may be nullNothingnullptrunita null reference (Nothing in Visual Basic), "", or Empty.

lexicalForm
Type: System..::..String

The unnormalized text for a recognized word.

This argument is required and may not be nullNothingnullptrunita null reference (Nothing in Visual Basic), "", or Empty.

displayAttributes
Type: Microsoft.Speech.Recognition..::..DisplayAttributes

Defines the use of white space to display recognized words.

audioPosition
Type: System..::..TimeSpan

The location of the recognized word in the audio input stream.

This value may be Zero

audioDuration
Type: System..::..TimeSpan

The length of the audio input corresponding to the recognized word.

This value may be Zero

Remarks

If text or pronunciation are nullNothingnullptrunita null reference (Nothing in Visual Basic), "", or Empty and the RecognizedWordUnit is used in a recognition operation, the recognition engine will generate appropriate values in any output RecognizedWordUnit instance.

Direct construction of RecognizedWordUnit instances is typically used only with when emulating recognition operations using EmulateRecognizeAsync or EmulateRecognize.

For actual applications, do not directly construct RecognizedWordUnit, rather obtain it through the Words property on the RecognizedPhrase object.

Examples

The example below is a somewhat contrived test of emulation, where new words are generated from the input and passed to the emulator, and then verified.

C# Copy image Copy Code
private void _emulateAndVerify_Click(object sender, EventArgs e) {

char[] delimiterChars = { ' ', ',', '.', ':', ';', '\t' };
string text = _emulateTextBox.Text;
string[] words = text.Split(delimiterChars);

RecognizedWordUnit[] InputWordUnits = new RecognizedWordUnit[words.Length];
for (int i = 0; i < words.Length; i++) {
    //DisplayAttributes at=
    InputWordUnits[i] = new RecognizedWordUnit("", 0, "",
              words[i].ToLower(), DisplayAttributes.OneTrailingSpace, new TimeSpan(), new TimeSpan());
}
RecognitionResult rec = _recognizer.EmulateRecognize(InputWordUnits, System.Globalization.CompareOptions.IgnoreCase);
if (rec == null) {
    MessageBox.Show(String.Format("Recognition emulation for {0} failed.\n", text));
} else if (InputWordUnits.Length != rec.Words.Count) {
    MessageBox.Show(String.Format(
                    "Length mismatch: Input was {0} words, Recognition has {1} words.\n}"));
} else {
    for (int i = 0; i < InputWordUnits.Length; i++) {

        if (rec.Words[i].LexicalForm.ToLower() != InputWordUnits[i].LexicalForm.ToLower()) {
            MessageBox.Show(String.Format(
                            "Input word {0} \"{1}\" not found. Recognition output is {2}",
                            i, InputWordUnits[i].LexicalForm, rec.Words[i].LexicalForm));
            continue;
        }
    }
}

See Also

Reference

RecognizedWordUnit Class
RecognizedWordUnit Members
Microsoft.Speech.Recognition Namespace
DisplayAttributes
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedWordUnit Methods

[image] [image]

RecognizedWordUnit Methods
RecognizedWordUnit Class See Also Send Feedback

The RecognizedWordUnit type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

RecognizedWordUnit Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizedWordUnit Properties

[image] [image]

RecognizedWordUnit Properties
RecognizedWordUnit Class See Also Send Feedback

The RecognizedWordUnit type exposes the following members.

Properties

 | Name | Description
Public property | AudioDuration | Gets the time interval that represents the length of the audio signal for the word.
Public property | AudioPosition | Gets the location in the input device's audio stream when recognition of the word began.
Public property | Confidence | Gets a value, assigned by the recognizer, that represents the likelihood that a recognized word matches a given input.
Public property | DisplayAttributes | Gets formatting information used in creating the text output from the current RecognizedWordUnit instance.
Public property | LexicalForm | Gets the unnormalized text of a recognized word.
Public property | Pronunciation | Gets the phonetic spelling of a recognized word.
Public property | Text | Gets the normalized text for a recognized word.
Top

See Also

Reference

RecognizedWordUnit Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioDuration Property

[image]

RecognizedWordUnit..::..AudioDuration Property
RecognizedWordUnit Class See Also Send Feedback

Gets the time interval that represents the length of the audio signal for the word.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioDuration As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As RecognizedWordUnit
Dim value As TimeSpan

value = instance.AudioDuration
C#
public TimeSpan AudioDuration { get; }

Property Value

Type: System..::..TimeSpan

The length of the audio signal for the word.

See Also

Reference

RecognizedWordUnit Class
RecognizedWordUnit Members
Microsoft.Speech.Recognition Namespace
RecognizedAudio
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioPosition Property

[image]

RecognizedWordUnit..::..AudioPosition Property
RecognizedWordUnit Class See Also Send Feedback

Gets the location in the input device's audio stream when recognition of the word began.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioPosition As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As RecognizedWordUnit
Dim value As TimeSpan

value = instance.AudioPosition
C#
public TimeSpan AudioPosition { get; }

Property Value

Type: System..::..TimeSpan

The location in the input device's audio stream when recognition of the word began.

See Also

Reference

RecognizedWordUnit Class
RecognizedWordUnit Members
Microsoft.Speech.Recognition Namespace
RecognizedAudio
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Confidence Property

[image]

RecognizedWordUnit..::..Confidence Property
RecognizedWordUnit Class See Also Send Feedback

Gets a value, assigned by the recognizer, that represents the likelihood that a recognized word matches a given input.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Confidence As Single
    Get
Visual Basic (Usage)
Dim instance As RecognizedWordUnit
Dim value As Single

value = instance.Confidence
C#
public float Confidence { get; }

Property Value

Type: System..::..Single

Returns a float, typically between 0 and 1, indicating the certainty of the speech recognition engine as to the correctness of recognition for a word.

Remarks

Confidence scores do not indicate the absolute likelihood that a word was recognized correctly. Instead, confidence scores provide a mechanism for comparing the relative accuracy of multiple recognition alternates for a given input. This facilitates returning the most accurate recognition result. For example, if a recognized word has a confidence score of 0.8, this does not mean that the word has an 80% chance of being the correct match for the input. It means that the word is more likely to be the correct match for the input than other results that have confidence scores less than 0.8.

A confidence score on its own is not meaningful unless you have alternative results to compare against, either from the same recognition operation or from previous recognitions of the same input.

The values returned by Confidence are relative and unique to each recognition engine. There is no definition of how confidence values between two different recognition engines compare, nor how the Confidence of individual RecognizedWordUnit objects define the Confidence of a RecognizedPhrase.

A speech recognition engine may assign a low confidence score to spoken input for various reasons, including background interference, inarticulate speech, or unanticipated words or word sequences. If your application is using a SpeechRecognitionEngine instance, you can modify the confidence level at which speech input is accepted or rejected with one of the UpdateRecognizerSetting()()()() methods.

See Also

Reference

RecognizedWordUnit Class
RecognizedWordUnit Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DisplayAttributes Property

[image]

RecognizedWordUnit..::..DisplayAttributes Property
RecognizedWordUnit Class Example See Also Send Feedback

Gets formatting information used in creating the text output from the current RecognizedWordUnit instance.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property DisplayAttributes As DisplayAttributes
    Get
Visual Basic (Usage)
Dim instance As RecognizedWordUnit
Dim value As DisplayAttributes

value = instance.DisplayAttributes
C#
public DisplayAttributes DisplayAttributes { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..DisplayAttributes

Specifies the use of white space to display of the contents of a RecognizedWordUnit object.

Remarks

The DisplayAttributes object returned by DisplayAttributes specifies the leading and trailing spaces to be used with a given word.

For more information about how to use this formatting information, see DisplayAttributes.

Examples

The following example shows a utility routine (stringFromWordArray) that generates lexical output (using LexicalForm), normalized output (using Text), and phonetic text output (using Pronunciation). The text output is formatted by the use of DisplayAttributes objects obtained from the DisplayAttributes property from a ReadOnlyCollection of RecognizedWordUnit objects. The RecognizedWordUnit objects are obtained from the Words property on the RecognizedPhrase object.

C# Copy image Copy Code
internal enum WordType {
          Text,
          Normalized = Text,
          Lexical,
          Pronunciation
}
C# Copy image Copy Code
internal static string stringFromWordArray(ReadOnlyCollection<RecognizedWordUnit> words, WordType type)
{
  string text = "";
  foreach (RecognizedWordUnit word in words)
  {
    string wordText = "";
    if (type == WordType.Text || type == WordType.Normalized)
    {
      wordText = word.Text;
    }
    else if (type == WordType.Lexical)
    {
      wordText = word.LexicalForm;
    }
    else if (type == WordType.Pronunciation)
    {
      wordText = word.Pronunciation;
    }
    else
    {
      throw new InvalidEnumArgumentException(String.Format("[0}: is not a valid input", type));
    }
    // Use display attribute

    if ((word.DisplayAttributes & DisplayAttributes.OneTrailingSpace) != 0)
    {
      wordText += " ";
    }
    if ((word.DisplayAttributes & DisplayAttributes.TwoTrailingSpaces) != 0)
    {
      wordText += "  ";
    }
    if ((word.DisplayAttributes & DisplayAttributes.ConsumeLeadingSpaces) != 0)
    {
      wordText = wordText.TrimStart();
    }
    if ((word.DisplayAttributes & DisplayAttributes.ZeroTrailingSpaces) != 0)
    {
      wordText = wordText.TrimEnd();
    }

    text += wordText;
  }
  return text;
}

See Also

Reference

RecognizedWordUnit Class
RecognizedWordUnit Members
Microsoft.Speech.Recognition Namespace
DisplayAttributes
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


LexicalForm Property

[image]

RecognizedWordUnit..::..LexicalForm Property
RecognizedWordUnit Class Example See Also Send Feedback

Gets the unnormalized text of a recognized word.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property LexicalForm As String
    Get
Visual Basic (Usage)
Dim instance As RecognizedWordUnit
Dim value As String

value = instance.LexicalForm
C#
public string LexicalForm { get; }

Property Value

Type: System..::..String

Returns a String containing the text of a recognized word, without any normalization.

Remarks

In most cases the values returned by Text and LexicalForm will be identical. However, recognition engines may use speech normalization to return more user-friendly or colloquial text representations of audio input.

Speech normalization is the use of special constructs or symbols to express speech in writing. For example, normalization can replace the spoken words "a dollar and sixteen cents" with "$1.16" in output text.

Examples

The following example shows a utility routine that generates text in one of three formats: lexical (using LexicalForm), normalized (using Text), and phonetic (using Pronunciation). The text output is obtained from a ReadOnlyCollection of RecognizedWordUnit objects, which is obtained from the Words property on the RecognizedPhrase object.

C# Copy image Copy Code
internal enum WordType
{
  Text,
  Normalized = Text,
  Lexical,
  Pronunciation
}
C# Copy image Copy Code
internal static string stringFromWordArray(
         ReadOnlyCollection<RecognizedWordUnit> words,
         WordType type)
{
  string text = "";
  foreach (RecognizedWordUnit word in words)
  {
    string wordText = "";
    if (type == WordType.Text || type == WordType.Normalized)
    {
      wordText = word.Text;
    }
    else if (type == WordType.Lexical)
    {
      wordText = word.LexicalForm;
    }
    else if (type == WordType.Pronunciation)
    {
      wordText = word.Pronunciation;
    }
    else
    {
      throw new InvalidEnumArgumentException(
          String.Format("[0}: is not a valid input", type));
    }

    // Use display attribute
    if ((word.DisplayAttributes & DisplayAttributes.OneTrailingSpace) != 0)
    {
      wordText += " ";
    }
    if ((word.DisplayAttributes & DisplayAttributes.TwoTrailingSpaces) != 0)
    {
      wordText += "  ";
    }
    if ((word.DisplayAttributes & DisplayAttributes.ConsumeLeadingSpaces) != 0)
    {
      wordText = wordText.TrimStart();
    }
    if ((word.DisplayAttributes & DisplayAttributes.ZeroTrailingSpaces) != 0)
    {
    wordText = wordText.TrimEnd();
    }

    text += wordText;

  }
  return text;
}

See Also

Reference

RecognizedWordUnit Class
RecognizedWordUnit Members
Microsoft.Speech.Recognition Namespace
DisplayAttributes
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Pronunciation Property

[image]

RecognizedWordUnit..::..Pronunciation Property
RecognizedWordUnit Class Example See Also Send Feedback

Gets the phonetic spelling of a recognized word.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Pronunciation As String
    Get
Visual Basic (Usage)
Dim instance As RecognizedWordUnit
Dim value As String

value = instance.Pronunciation
C#
public string Pronunciation { get; }

Property Value

Type: System..::..String

A string of characters from a supported phonetic alphabet, such as the International Phonetic Alphabet (IPA) or the Universal Phone Set (UPS).

Remarks

The contents of Pronunciation indicate which pronunciation the speech recognition engine used to match speech input to one of its loaded Grammar objects. Pronunciations may be defined in the speech recognition engine's internal lexicon, in a lexicon document that is linked from a recognition grammar in a loaded Grammar object, or inline in a recognition grammar in a loaded Grammar object. A speech recognition engine may also create pronunciations for uncommon words whose pronunciations are not defined in a lexicon or grammar to which the speech recognition engine currently has access.

Many Windows-based Unicode fonts, such as Courier New, support the display of IPA strings.

Examples

The following example shows a utility routine that generates a string with one of three possible formats: lexical (using LexicalForm), normalized (using Text), and phonetic (using Pronunciation). The text output is obtained from a ReadOnlyCollection of RecognizedWordUnit objects, which is obtained from the Words property on the RecognizedPhrase object.

C# Copy image Copy Code
internal enum WordType
{
  Text,
  Normalized = Text,
  Lexical,
  Pronunciation
}
C# Copy image Copy Code
internal static string stringFromWordArray(
          ReadOnlyCollection<RecognizedWordUnit> words,
          WordType type)
{
  string text = "";
  foreach (RecognizedWordUnit word in words)
  {
    string wordText = "";
    if (type == WordType.Text || type == WordType.Normalized)
    {
      wordText = word.Text;
    }
    else if (type == WordType.Lexical)
    {
      wordText = word.LexicalForm;
    }
    else if (type == WordType.Pronunciation)
    {
      wordText = word.Pronunciation;
    }
    else
    {
      throw new InvalidEnumArgumentException(
          String.Format("[0}: is not a valid input", type));
    }
    // Use display attribute

    if ((word.DisplayAttributes & DisplayAttributes.OneTrailingSpace) != 0)
    {
      wordText += " ";
    }
    if ((word.DisplayAttributes & DisplayAttributes.TwoTrailingSpaces) != 0)
    {
      wordText += "  ";
    }
    if ((word.DisplayAttributes & DisplayAttributes.ConsumeLeadingSpaces) != 0)
    {
      wordText = wordText.TrimStart();
    }
    if ((word.DisplayAttributes & DisplayAttributes.ZeroTrailingSpaces) != 0)
    {
      wordText = wordText.TrimEnd();
    }

    text += wordText;
  }
  return text;
}

See Also

Reference

RecognizedWordUnit Class
RecognizedWordUnit Members
Microsoft.Speech.Recognition Namespace
DisplayAttributes
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Text Property

[image]

RecognizedWordUnit..::..Text Property
RecognizedWordUnit Class Example See Also Send Feedback

Gets the normalized text for a recognized word.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Text As String
    Get
Visual Basic (Usage)
Dim instance As RecognizedWordUnit
Dim value As String

value = instance.Text
C#
public string Text { get; }

Property Value

Type: System..::..String

A string that contains the normalized text output for a given input word.

Remarks

In most cases, the values returned by Text and LexicalForm will be identical. However, recognition engines may use speech normalization to return more user-friendly or colloquial text representations of audio input.

Speech normalization is the use of special constructs or symbols to express speech in writing. For example, normalization can replace the spoken words "a dollar and sixteen cents" with "$1.16" in output text.

Examples

The following example shows a utility routine that generates a string in one of three formats: lexical (using LexicalForm), normalized (using Text), and phonetic (using Pronunciation). The text output is obtained from a ReadOnlyCollection of RecognizedWordUnit objects, which is obtained from the Words property on the RecognizedPhrase object.

C# Copy image Copy Code
internal enum WordType
{
  Text,
  Normalized = Text,
  Lexical,
  Pronunciation
}
C# Copy image Copy Code
internal static string stringFromWordArray(
          ReadOnlyCollection<RecognizedWordUnit> words,
          WordType type)
{
  string text = "";
  foreach (RecognizedWordUnit word in words)
  {
    string wordText = "";
    if (type == WordType.Text || type == WordType.Normalized)
    {
      wordText = word.Text;
    }
    else if (type == WordType.Lexical)
    {
      wordText = word.LexicalForm;
    }
    else if (type == WordType.Pronunciation)
    {
      wordText = word.Pronunciation;
    }
    else
    {
      throw new InvalidEnumArgumentException(
           String.Format("[0}: is not a valid input", type));
    }

    // Use display attribute
    if ((word.DisplayAttributes & DisplayAttributes.OneTrailingSpace) != 0)
    {
      wordText += " ";
    }
    if ((word.DisplayAttributes & DisplayAttributes.TwoTrailingSpaces) != 0)
    {
      wordText += "  ";
    }
    if ((word.DisplayAttributes & DisplayAttributes.ConsumeLeadingSpaces) != 0)
    {
      wordText = wordText.TrimStart();
    }
    if ((word.DisplayAttributes & DisplayAttributes.ZeroTrailingSpaces) != 0)
    {
      wordText = wordText.TrimEnd();
    }

    text += wordText;

  }
  return text;
}

See Also

Reference

RecognizedWordUnit Class
RecognizedWordUnit Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeMode Enumeration

[image]

RecognizeMode Enumeration
Example See Also Send Feedback

Enumerates values of the recognition mode.

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

Syntax

Visual Basic (Declaration)
Public Enumeration RecognizeMode
Visual Basic (Usage)
Dim instance As RecognizeMode
C#
public enum RecognizeMode

Members

Member name | Description
Single | Specifies that recognition terminates after completion.
Multiple | Specifies that recognition does not terminate after completion.

Remarks

This enumeration is used as an argument to RecognizeAsync(RecognizeMode)

Examples

The following example shows the implementation of a start/stop button for an application that has a graphical user interface and uses SpeechRecognitionEngine. Depending on the state of the application, RecognizeAsync(RecognizeMode) is called with either Single or Multiple when the button is clicked.

Copy image Copy Code
private void _startRecogButton_Click(object sender, EventArgs eventArgs)
{

  // Toggle speech recognition on.
  if (_startRecogButton.Text == "Start Speech Recognition")
  {
    _startRecogButton.Text = "Stop Speech Recognition";
    if (_useMultiple)
    {
      _recognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
    }
    else
    {
      _recognitionEngine.RecognizeAsync(RecognizeMode.Single);
    }
  }

  // Toggle speech recognition off.
  else
  {
    _startRecogButton.Text = "Start Speech Recognition";

    // Stop after current phrase is finished.
    if (_friendlyStop)
    {
      _recognitionEngine.RecognizeAsyncStop();
    }

    // Stop before current phrase is finished.
    else
    {
      _recognitionEngine.RecognizeAsyncCancel();
    }
  }
}

See Also

Reference

Microsoft.Speech.Recognition Namespace
SpeechRecognitionEngine
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizerInfo Class

[image]

RecognizerInfo Class
Members Example See Also Send Feedback

Represents information about a SpeechRecognitionEngine object.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..RecognizerInfo

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

Syntax

Visual Basic (Declaration)
Public Class RecognizerInfo
Visual Basic (Usage)
Dim instance As RecognizerInfo
C#
public class RecognizerInfo

Remarks

SpeechRecognitionEngine..::..RecognizerInfo provides identifying information for an initialized SpeechRecognitionEngine object.

You can use instances of RecognizerInfo to construct a specific configuration of SpeechRecognitionEngine using the SpeechRecognitionEngine(RecognizerInfo) constructor.

The static method InstalledRecognizers()()()() returns a list of all available SpeechRecognitionEngine configurations as RecognizerInfo instances.

Examples

The example below validates a given CultureInfo and identifier string against the permitted SpeechRecognitionEngine configurations, expressed as a list of RecognizerInfo objects.

If the CultureInfo and identifier string are valid, the example creates a new instance of SpeechRecognitionEngine using the RecognizerInfo instance as an argument.

C# Copy image Copy Code
private SpeechRecognitionEngine SelectRecognizer(CultureInfo requiredCulture, string requiredId)
{
  // Select based on a specific recognizer configuration:
  SpeechRecognitionEngine speechRecognitionEngine = null;
  foreach (RecognizerInfo config in SpeechRecognitionEngine.InstalledRecognizers())
  {
    if (config.Culture.Equals(requiredCulture) && config.Id== requiredId)
    {
      speechRecognitionEngine = new SpeechRecognitionEngine(config);
      break;
    }
  }
  return speechRecognitionEngine;
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

RecognizerInfo Members
Microsoft.Speech.Recognition Namespace
SpeechRecognitionEngine
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizerInfo Members

[image] [image]

RecognizerInfo Members
RecognizerInfo Class Methods Properties See Also Send Feedback

Represents information about a SpeechRecognitionEngine object.

The RecognizerInfo type exposes the following members.

Properties

 | Name | Description
Public property | AdditionalInfo | Gets additional information about a SpeechRecognitionEngine instance.
Public property | Culture | Gets the culture supported by a SpeechRecognitionEngine instance.
Public property | Description | Gets the description of a SpeechRecognitionEngine instance.
Public property | Id | Gets the identifier of a SpeechRecognitionEngine instance.
Public property | Name | Gets the friendly name of a SpeechRecognitionEngine instance.
Public property | SupportedAudioFormats | Gets the audio formats supported by a SpeechRecognitionEngine instance.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

RecognizerInfo Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizerInfo Methods

[image] [image]

RecognizerInfo Methods
RecognizerInfo Class See Also Send Feedback

The RecognizerInfo type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

RecognizerInfo Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizerInfo Properties

[image] [image]

RecognizerInfo Properties
RecognizerInfo Class See Also Send Feedback

The RecognizerInfo type exposes the following members.

Properties

 | Name | Description
Public property | AdditionalInfo | Gets additional information about a SpeechRecognitionEngine instance.
Public property | Culture | Gets the culture supported by a SpeechRecognitionEngine instance.
Public property | Description | Gets the description of a SpeechRecognitionEngine instance.
Public property | Id | Gets the identifier of a SpeechRecognitionEngine instance.
Public property | Name | Gets the friendly name of a SpeechRecognitionEngine instance.
Public property | SupportedAudioFormats | Gets the audio formats supported by a SpeechRecognitionEngine instance.
Top

See Also

Reference

RecognizerInfo Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AdditionalInfo Property

[image]

RecognizerInfo..::..AdditionalInfo Property
RecognizerInfo Class Example See Also Send Feedback

Gets additional information about a SpeechRecognitionEngine instance.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AdditionalInfo As IDictionary(Of String, String)
    Get
Visual Basic (Usage)
Dim instance As RecognizerInfo
Dim value As IDictionary(Of String, String)

value = instance.AdditionalInfo
C#
public IDictionary<string, string> AdditionalInfo { get; }

Property Value

Type: System.Collections.Generic..::..IDictionary <(Of <(<' String, String >)>)>

Returns an instance of IDictionary containing information about the configuration of a SpeechRecognitionEngine.

Examples

The following example implements a button-click that displays all the information in a RecognizerInfo object in a MessageBox.

The key/value pairs contained in the IDictionary instance returned by AdditionalInfo are concatenated into a text table.

C# Copy image Copy Code
private void recognizerInfoButton_Click(object sender, EventArgs e)
{
  RecognizerInfo info = _recognizer.RecognizerInfo;
  string AudioFormats = "";
  foreach (SpeechAudioFormatInfo fmt in info.SupportedAudioFormats)
  {
    AudioFormats += String.Format("       {0}\n",
      fmt.EncodingFormat.ToString());
  }
  string AdditionalInfo = "";
  foreach (string key in info.AdditionalInfo.Keys)
  {
    AdditionalInfo += String.Format("      {0}: {1}\n", key, info.AdditionalInfo[key]);
  }
  MessageBox.Show(String.Format(
                          "Name:                 {0 }\n" +
                          "Description:          {1} \n" +
                          "SupportedAudioFormats:\n" +
                          "{2} " +
                          "Culture:              {3} \n" +
                          "AdditionalInfo:       \n" +
                          " {4}\n",
                          info.Name.ToString(),
                          info.Description.ToString(),
                          AudioFormats,
                          info.Culture.ToString(),
                          AdditionalInfo));
}

See Also

Reference

RecognizerInfo Class
RecognizerInfo Members
Microsoft.Speech.Recognition Namespace
RecognizerInfo
SpeechRecognitionEngine
IDictionary
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Culture Property

[image]

RecognizerInfo..::..Culture Property
RecognizerInfo Class Example See Also Send Feedback

Gets the culture supported by a SpeechRecognitionEngine instance.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Culture As CultureInfo
    Get
Visual Basic (Usage)
Dim instance As RecognizerInfo
Dim value As CultureInfo

value = instance.Culture
C#
public CultureInfo Culture { get; }

Property Value

Type: System.Globalization..::..CultureInfo

Returns information about the culture supported by a given SpeechRecognitionEngine instance.

Remarks

A CultureInfo object can include the name of the culture, the associated language, the country/region, the calendar used, and how to format dates and sort strings.

Examples

The following example implements a button click that displays all the information in a RecognizerInfo instance. The example uses the Culture property to obtain the identifying string for the CultureInfo used by the recognition engine configuration.

C# Copy image Copy Code
private void recognizerInfoButton_Click(object sender, EventArgs e)
{
  RecognizerInfo info = _recognizer.RecognizerInfo;
  string AudioFormats = "";
  foreach (SpeechAudioFormatInfo fmt in info.SupportedAudioFormats)
  {
    AudioFormats += String.Format("       {0}\n",
      fmt.EncodingFormat.ToString());
  }
  string AdditionalInfo = "";
  foreach (string key in info.AdditionalInfo.Keys)
  {
    AdditionalInfo += String.Format("      {0}: {1}\n", key, info.AdditionalInfo[key]);
  }
  MessageBox.Show(String.Format(
                          "Name:                 {0 }\n" +
                          "Description:          {1} \n" +
                          "SupportedAudioFormats:\n" +
                          "{2} " +
                          "Culture:              {3} \n" +
                          "AdditionalInfo:       \n" +
                          " {4}\n",
                          info.Name.ToString(),
                          info.Description.ToString(),
                          AudioFormats,
                          info.Culture.ToString(),
                          AdditionalInfo));
}

See Also

Reference

RecognizerInfo Class
RecognizerInfo Members
Microsoft.Speech.Recognition Namespace
CultureInfo
RecognizerInfo
SpeechRecognitionEngine
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Description Property

[image]

RecognizerInfo..::..Description Property
RecognizerInfo Class Example See Also Send Feedback

Gets the description of a SpeechRecognitionEngine instance.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Description As String
    Get
Visual Basic (Usage)
Dim instance As RecognizerInfo
Dim value As String

value = instance.Description
C#
public string Description { get; }

Property Value

Type: System..::..String

Returns a string that describes the configuration for a specific SpeechRecognitionEngine instance.

Examples

The following example below implements a button click that displays all the information in a RecognizerInfo instance. The example uses the Description property to obtain the description of a speech recognition engine configuration, and then displays it in a MessageBox.

C# Copy image Copy Code
private void recognizerInfoButton_Click(object sender, EventArgs e)
{
  RecognizerInfo info = _recognizer.RecognizerInfo;
  string AudioFormats = "";
  foreach (SpeechAudioFormatInfo fmt in info.SupportedAudioFormats)
  {
    AudioFormats += String.Format("       {0}\n", fmt.EncodingFormat.ToString());
  }
  string AdditionalInfo = "";
  foreach (string key in info.AdditionalInfo.Keys)
  {
    AdditionalInfo += String.Format("      {0}: {1}\n", key, info.AdditionalInfo[key]);
  }
  MessageBox.Show(String.Format(
                     "Name:                 {0 }\n" +
                     "Description:          {1} \n" +
                     "SupportedAudioFormats:\n" +
                     "{2} " +
                     "Culture:              {3} \n" +
                     "AdditionalInfo:       \n" +
                     " {4}\n",
                     info.Name.ToString(),
                     info.Description.ToString(),
                     AudioFormats,
                     info.Culture.ToString(),
                     AdditionalInfo));
}

See Also

Reference

RecognizerInfo Class
RecognizerInfo Members
Microsoft.Speech.Recognition Namespace
RecognizerInfo
SpeechRecognitionEngine
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Id Property

[image]

RecognizerInfo..::..Id Property
RecognizerInfo Class Example See Also Send Feedback

Gets the identifier of a SpeechRecognitionEngine instance.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Id As String
    Get
Visual Basic (Usage)
Dim instance As RecognizerInfo
Dim value As String

value = instance.Id
C#
public string Id { get; }

Property Value

Type: System..::..String

Returns the identifier for a specific SpeechRecognitionEngine instance.

Remarks

The identifier returned by the Id property is the same as the token name of the recognition engine in the registry.

Examples

The following example implements a button click that displays all the information in a RecognizerInfo instance. The example uses the Id property to obtain the identifier string of a recognition engine configuration, and then displays it in a MessageBox.

C# Copy image Copy Code
private void recognizerInfoButton_Click(object sender, EventArgs e)
{
  RecognizerInfo info = _recognizer.RecognizerInfo;
  string AudioFormats = "";
  foreach (SpeechAudioFormatInfo fmt in info.SupportedAudioFormats)
  {
    AudioFormats += String.Format("       {0}\n",
      fmt.EncodingFormat.ToString());
  }
  string AdditionalInfo = "";
  foreach (string key in info.AdditionalInfo.Keys)
  {
    AdditionalInfo += String.Format("      {0}: {1}\n", key, info.AdditionalInfo[key]);
  }
  MessageBox.Show(String.Format(
                          "Name:                 {0 }\n" +
                          "Description:          {1} \n" +
                          "SupportedAudioFormats:\n" +
                          "{2} " +
                          "Culture:              {3} \n" +
                          "AdditionalInfo:       \n" +
                          " {4}\n",
                          info.Name.ToString(),
                          info.Description.ToString(),
                          AudioFormats,
                          info.Culture.ToString(),
                          AdditionalInfo));
}

See Also

Reference

RecognizerInfo Class
RecognizerInfo Members
Microsoft.Speech.Recognition Namespace
RecognizerInfo
SpeechRecognitionEngine
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Name Property

[image]

RecognizerInfo..::..Name Property
RecognizerInfo Class Example See Also Send Feedback

Gets the friendly name of a SpeechRecognitionEngine instance.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Name As String
    Get
Visual Basic (Usage)
Dim instance As RecognizerInfo
Dim value As String

value = instance.Name
C#
public string Name { get; }

Property Value

Type: System..::..String

Returns the friendly name for a specific SpeechRecognitionEngine instance.

Examples

The following example implements a button click that displays all the information in a RecognizerInfo instance. The example uses the Name property to obtain the friendly name of a recognition engine configuration, and then displays it in a MessageBox.

Copy image Copy Code
private void recognizerInfoButton_Click(object sender, EventArgs e)
{
  RecognizerInfo info = _recognizer.RecognizerInfo;
  string AudioFormats = "";
  foreach (SpeechAudioFormatInfo fmt in info.SupportedAudioFormats)
  {
    AudioFormats += String.Format("       {0}\n", fmt.EncodingFormat.ToString());
  }
  string AdditionalInfo = "";
  foreach (string key in info.AdditionalInfo.Keys)
  {
    AdditionalInfo += String.Format("      {0}: {1}\n", key, info.AdditionalInfo[key]);
  }
  MessageBox.Show(String.Format(
                           "Name:                 {0 }\n" +
                           "Description:          {1} \n" +
                           "SupportedAudioFormats:\n" +
                           "{2} " +
                           "Culture:              {3} \n" +
                           "AdditionalInfo:       \n" +
                           " {4}\n",
                           info.Name.ToString(),
                           info.Description.ToString(),
                           AudioFormats,
                           info.Culture.ToString(),
                           AdditionalInfo));
}

See Also

Reference

RecognizerInfo Class
RecognizerInfo Members
Microsoft.Speech.Recognition Namespace
RecognizerInfo
SpeechRecognitionEngine
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SupportedAudioFormats Property

[image]

RecognizerInfo..::..SupportedAudioFormats Property
RecognizerInfo Class Example See Also Send Feedback

Gets the audio formats supported by a SpeechRecognitionEngine instance.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property SupportedAudioFormats As ReadOnlyCollection(Of SpeechAudioFormatInfo)
    Get
Visual Basic (Usage)
Dim instance As RecognizerInfo
Dim value As ReadOnlyCollection(Of SpeechAudioFormatInfo)

value = instance.SupportedAudioFormats
C#
public ReadOnlyCollection<SpeechAudioFormatInfo> SupportedAudioFormats { get; }

Property Value

Type: System.Collections.ObjectModel..::..ReadOnlyCollection <(Of <(<' SpeechAudioFormatInfo >)>)>

Returns a list of audio formats supported by a specific SpeechRecognitionEngine instance.

Examples

The following example implements a button click that displays all the information in a RecognizerInfo instance. The example uses the SupportedAudioFormats property to obtain the encoding formats supported by a recognition engine configuration, and then displays it in a MessageBox.

C# Copy image Copy Code
private void recognizerInfoButton_Click(object sender, EventArgs e)
{
  RecognizerInfo info = _recognizer.RecognizerInfo;
  string AudioFormats = "";
  foreach (SpeechAudioFormatInfo fmt in info.SupportedAudioFormats)
  {
    AudioFormats += String.Format("       {0}\n",
      fmt.EncodingFormat.ToString());
  }
  string AdditionalInfo = "";
  foreach (string key in info.AdditionalInfo.Keys)
  {
    AdditionalInfo += String.Format("      {0}: {1}\n", key, info.AdditionalInfo[key]);
  }
  MessageBox.Show(String.Format(
                          "Name:                 {0 }\n" +
                          "Description:          {1} \n" +
                          "SupportedAudioFormats:\n" +
                          "{2} " +
                          "Culture:              {3} \n" +
                          "AdditionalInfo:       \n" +
                          " {4}\n",
                          info.Name.ToString(),
                          info.Description.ToString(),
                          AudioFormats,
                          info.Culture.ToString(),
                          AdditionalInfo));
}

See Also

Reference

RecognizerInfo Class
RecognizerInfo Members
Microsoft.Speech.Recognition Namespace
RecognizerInfo
[System.Collections.ObjectModel.ReadOnlyCollection]
SpeechRecognitionEngine
SpeechAudioFormatInfo
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizerUpdateReachedEventArgs Class

[image]

RecognizerUpdateReachedEventArgs Class
Members Example See Also Send Feedback

Provides data for the RecognizerUpdateReached event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Recognition..::..RecognizerUpdateReachedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class RecognizerUpdateReachedEventArgs _
    Inherits EventArgs
Visual Basic (Usage)
Dim instance As RecognizerUpdateReachedEventArgs
C#
public class RecognizerUpdateReachedEventArgs : EventArgs

Remarks

An instance of RecognizerUpdateReachedEventArgs is created when the SpeechRecognitionEngine object raises the RecognizerUpdateReached event at the completion of a RequestRecognizerUpdate()()()() method.

You use the RequestRecognizerUpdate()()()() methods to request the SpeechRecognitionEngine to pause. When the RecognizerUpdateReached event is raised, you can use the handler for the event to make modifications to the paused SpeechRecognitionEngine instance.

For example, while the SpeechRecognitionEngine is paused, you can load, unload, enable, and disable Grammar objects, and modify values for the BabbleTimeout, InitialSilenceTimeout, and EndSilenceTimeout properties. When handling SpeechRecognitionEngine..::..RecognizerUpdateReached events, a recognition engine pauses until the event handler returns.

For more information, see the RequestRecognizerUpdate method.

SpeechRecognitionRejectedEventArgs derives from EventArgs.

Examples

The following example shows a console application that loads and unloads Grammar objects. The application uses the RequestRecognizerUpdate()()()() method to request the speech recognition engine to pause so it can receive an update. The application then loads or unloads a Grammar object.

At each update, a handler for SpeechRecognitionEngine..::..RecognizerUpdateReached event writes the name and status of the currently loaded Grammar objects to the console. As grammars are loaded and unloaded, the application first recognizes the names of farm animals, then the names of farm animals and the names of fruits, then only the names of fruits.

C# Copy image Copy Code
using System;
using System.Speech.Recognition;
using System.Collections.Generic;
using System.Threading;

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

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

        // Create the first grammar - Farm.
        Choices animals = new Choices(new string[] { "cow", "pig", "goat" });
        GrammarBuilder farm = new GrammarBuilder(animals);
        Grammar farmAnimals = new Grammar(farm);
        farmAnimals.Name = "Farm";

        // Create the second grammar - Fruit.
        Choices fruit = new Choices(new string[] { "apples", "peaches", "oranges" });
        GrammarBuilder favorite = new GrammarBuilder(fruit);
        Grammar favoriteFruit = new Grammar(favorite);
        favoriteFruit.Name = "Fruit";

        // Attach event handlers.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
        recognizer.RecognizerUpdateReached +=
          new EventHandler<RecognizerUpdateReachedEventArgs>(recognizer_RecognizerUpdateReached);
        recognizer.SpeechRecognitionRejected +=
          new EventHandler<SpeechRecognitionRejectedEventArgs>(recognizer_SpeechRecognitionRejected);

        // Load the Farm grammar.
        recognizer.LoadGrammar(farmAnimals);
        Console.WriteLine("Grammar Farm is loaded");

        // Start asynchronous, continuous recognition.
        recognizer.RecognizeAsync(RecognizeMode.Multiple);
        Console.WriteLine("Starting asynchronous, continuous recognition");

        // Pause to recognize farm animals.
        Thread.Sleep(7000);
        Console.WriteLine();

        // Request an update and load the Fruit grammar.
        recognizer.RequestRecognizerUpdate();
        recognizer.LoadGrammarAsync(favoriteFruit);
        Thread.Sleep(7000);

        // Request an update and unload the Farm grammar.
        recognizer.RequestRecognizerUpdate();
        recognizer.UnloadGrammar(farmAnimals);
        Thread.Sleep(7000);
      }

      // Keep the console window open.
      Console.WriteLine();
      Console.WriteLine("Press any key to exit...");
      Console.ReadKey();
    }

    // At the update, get the names and enabled status of the currently loaded grammars.
    public static void recognizer_RecognizerUpdateReached(
      object sender, RecognizerUpdateReachedEventArgs e)
    {
      Console.WriteLine();
      Console.WriteLine("Update reached:");
      Thread.Sleep(1000);

      string qualifier;
      List<Grammar> grammars = new List<Grammar>(recognizer.Grammars);
      foreach (Grammar g in grammars)
      {
        qualifier = (g.Enabled) ? "enabled" : "disabled";
        Console.WriteLine("  Grammar {0} is loaded and is {1}.",
        g.Name, qualifier);
      }
    }

    // Write the text of the recognized phrase to the console.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine("  Speech recognized: " + e.Result.Text);
    }

    // Write a message to the console when recognition fails.
    static void recognizer_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
    {
      Console.WriteLine("  Recognition attempt failed");
    }
  }
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

RecognizerUpdateReachedEventArgs Members
Microsoft.Speech.Recognition Namespace
RecognizerUpdateReached
RequestRecognizerUpdate
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizerUpdateReachedEventArgs Members

[image] [image]

RecognizerUpdateReachedEventArgs Members
RecognizerUpdateReachedEventArgs Class Methods Properties See Also Send Feedback

Provides data for the RecognizerUpdateReached event.

The RecognizerUpdateReachedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioPosition | Gets the audio position associated with the event.
Public property | UserToken | Gets the UserToken passed to the system when an application calls RequestRecognizerUpdate()()()().
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

RecognizerUpdateReachedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizerUpdateReachedEventArgs Methods

[image] [image]

RecognizerUpdateReachedEventArgs Methods
RecognizerUpdateReachedEventArgs Class See Also Send Feedback

The RecognizerUpdateReachedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

RecognizerUpdateReachedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizerUpdateReachedEventArgs Properties

[image] [image]

RecognizerUpdateReachedEventArgs Properties
RecognizerUpdateReachedEventArgs Class See Also Send Feedback

The RecognizerUpdateReachedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioPosition | Gets the audio position associated with the event.
Public property | UserToken | Gets the UserToken passed to the system when an application calls RequestRecognizerUpdate()()()().
Top

See Also

Reference

RecognizerUpdateReachedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioPosition Property

[image]

RecognizerUpdateReachedEventArgs..::..AudioPosition Property
RecognizerUpdateReachedEventArgs Class See Also Send Feedback

Gets the audio position associated with the event.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioPosition As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As RecognizerUpdateReachedEventArgs
Dim value As TimeSpan

value = instance.AudioPosition
C#
public TimeSpan AudioPosition { get; }

Property Value

Type: System..::..TimeSpan

Returns the location within the speech buffer of a SpeechRecognitionEngine when it pauses and raises a RecognizerUpdateReached event.

Remarks

Applications can use the location indicated by AudioPosition to access audio input that occurred while the recognition engine was paused.

See Also

Reference

RecognizerUpdateReachedEventArgs Class
RecognizerUpdateReachedEventArgs Members
Microsoft.Speech.Recognition Namespace
RecognizerUpdateReached
RequestRecognizerUpdate
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


UserToken Property

[image]

RecognizerUpdateReachedEventArgs..::..UserToken Property
RecognizerUpdateReachedEventArgs Class Example See Also Send Feedback

Gets the UserToken passed to the system when an application calls RequestRecognizerUpdate()()()().

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property UserToken As Object
    Get
Visual Basic (Usage)
Dim instance As RecognizerUpdateReachedEventArgs
Dim value As Object

value = instance.UserToken
C#
public Object UserToken { get; }

Property Value

Type: System..::..Object

Returns an object that contains the UserToken.

Remarks

An application specifies a UserToken when it requests the generation of a RecognizerUpdateReached event by calling one of the SpeechRecognitionEngine..::..RequestRecognizerUpdate methods that take a userToken parameter.

Examples

The following example shows a console application that loads and unloads Grammar objects. The application uses the RequestRecognizerUpdate(Object) method to request the speech recognition engine to pause so it can receive an update. The method passes in a String object for the userToken parameter that describes what the application will recognize after the update. The application then loads or unloads a Grammar object.

At each update, a handler for SpeechRecognitionEngine..::..RecognizerUpdateReached event writes the name and status of the currently loaded Grammar objects to the console, as well as the contents of userToken. As grammars are loaded and unloaded, the application first recognizes the names of farm animals, then the names of farm animals and the names of fruits, then only the names of fruits.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;
using System.Collections.Generic;
using System.Threading;

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

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

      // Create the first grammar - Farm.
      Choices animals = new Choices(new string[] { "cow", "pig", "goat" });
      GrammarBuilder farm = new GrammarBuilder(animals);
      Grammar farmAnimals = new Grammar(farm);
      farmAnimals.Name = "Farm";

      // Create the second grammar - Fruit.
      Choices fruit = new Choices(new string[] { "apples", "peaches", "oranges" });
      GrammarBuilder favorite = new GrammarBuilder(fruit);
      Grammar favoriteFruit = new Grammar(favorite);
      favoriteFruit.Name = "Fruit";

      // Attach event handlers.
      recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
      recognizer.RecognizerUpdateReached += new EventHandler<RecognizerUpdateReachedEventArgs>(recognizer_RecognizerUpdateReached);

      // Load the farmAnimals grammar
      recognizer.LoadGrammar(farmAnimals);

      // Start recognition.
      recognizer.RecognizeAsync(RecognizeMode.Multiple);
      Console.WriteLine("Starting asynchronous recognition...");
      Console.WriteLine("Farm animals will now be recognized.");
      Thread.Sleep(7000);
      Console.WriteLine();

      //Load the Fruit grammar.
      string activeGrammars = "Farm animals and fruits will now be recognized.";
      recognizer.RequestRecognizerUpdate(activeGrammars);
      recognizer.LoadGrammarAsync(favoriteFruit);
      Console.WriteLine();
      Thread.Sleep(7000);
      Console.WriteLine();

      // Unload the Farm grammar.
      string onlyFruit = "Only fruits will now be recognized.";
      recognizer.RequestRecognizerUpdate(onlyFruit);
      recognizer.UnloadGrammar(farmAnimals);

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

    public static void recognizer_RecognizerUpdateReached(object sender, RecognizerUpdateReachedEventArgs e)
    {
      // At the update, describe what the application will recognize next.
      // Display the names and enabled status of the currently loaded grammars.
      Console.WriteLine("Update reached: " + e.UserToken);
      Thread.Sleep(1000);

      string qualifier;
      List<Grammar> grammars = new List<Grammar>(recognizer.Grammars);
      foreach (Grammar g in grammars)
      {
        qualifier = (g.Enabled) ? "enabled" : "disabled";
        Console.WriteLine("  Grammar {0} is loaded and is {1}.",
        g.Name, qualifier);
      }
    }

    // Write the text of the recognized phrase to the console.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine("  Speech recognized: " + e.Result.Text);
    }
  }
}

See Also

Reference

RecognizerUpdateReachedEventArgs Class
RecognizerUpdateReachedEventArgs Members
Microsoft.Speech.Recognition Namespace
RecognizerUpdateReached
RequestRecognizerUpdate
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ReplacementText Class

[image]

ReplacementText Class
Members Example See Also Send Feedback

Contains information about a speech normalization procedure that has been performed on recognition results.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..ReplacementText

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class ReplacementText
Visual Basic (Usage)
Dim instance As ReplacementText
C#
[SerializableAttribute]
public class ReplacementText

Remarks

Speech normalization is the use of special constructs or symbols to express speech in writing.

For example, suppose that this is recognized text:

july fourth at twelve thirty one PM, I bought one point six kilograms of fish for fourteen dollars and six cents, at the pike market in seattle washington nine eight one two two

This is the same text after normalization:

July 4 at 12:31 PM, I bought 1.6 kg of fish for $14.06, at the pike market in Seattle WA 98122

In this example there are five substitutions, each of which would be described by an instance of ReplacementText.

Using the ReplacementText object, an application can determine:

  • The location and number of words replaced by normalization. For more information, see FirstWordIndex or CountOfWords.

  • The replaced text and its display attributes. For more information, see Text, and DisplayAttributes.

Instances of ReplacementText are typically obtained as members of the Collection object returned by the ReplacementWordUnits property on RecognizedPhrase (or classes which inherit from RecognizedPhrase such as RecognitionResult) when returned text has been normalized.

Examples

In the example below, information about a RecognizedPhrase object returned by a recognition engine is displayed to a user interface.

C# Copy image Copy Code
internal static void DisplayBasicPhraseInfo(Label label, RecognizedPhrase result, SpeechRecognitionEngine rec)
{
  if (result != null && label != null)
  { // Blank
    if (rec != null)
    { // Clear
      label.Text += String.Format(
                       "  Recognizer currently at:   {0} mSec\n" +
                       "  Audio Device currently at: {1} mSec\n",
                       rec.RecognizerAudioPosition.TotalMilliseconds,
                       rec.AudioPosition.TotalMilliseconds);
    }

    if (result != null)
    { // Clear
      RecognitionResult recResult = result as RecognitionResult;
      if (recResult != null)
      {
        RecognizedAudio resultAudio = recResult.Audio;
        if (resultAudio == null)
        {
          label.Text += String.Format(
                               "  Emulated input\n");
        }
        else
        {
          label.Text += String.Format(
                            "  Candidate Phrase at:       {0} mSec\n" +
                            "  Phrase Length:             {1} mSec\n" +
                            "  Input State Time:          {2}\n" +
                            "  Input Format:              {3}\n",
                            resultAudio.AudioPosition.TotalMilliseconds,
                            resultAudio.Duration.TotalMilliseconds,
                            resultAudio.StartTime.ToShortTimeString(),
                            resultAudio.Format.EncodingFormat.ToString());
        }
      }

      label.Text += String.Format("  Confidence Level:          {0}\n", result.Confidence);
      if (result.Grammar != null)
      {
        label.Text += String.Format(
                         "  Recognizing Grammar:       {0}\n" +
                         "  Recognizing Rule:          {1}\n",
                         ((result.Grammar.Name != null) ? (result.Grammar.Name) : "None"),
                         ((result.Grammar.RuleName != null) ? (result.Grammar.RuleName) : "None"));
      }

      if  (result.ReplacementWordUnits.Count !=  0)
      {
        label.Text += String.Format("  Replacement text:\n");
        foreach  (ReplacementText rep in result.ReplacementWordUnits)
        {
          string repText = rep.Text;
          // Add trailing spaces
          if ((rep.DisplayAttributes & DisplayAttributes.OneTrailingSpace) !=  0)
          {
            repText += " ";
          }
          if ((rep.DisplayAttributes & DisplayAttributes.TwoTrailingSpaces) != 0)
          {
            repText += "  ";
          }
          if ((rep.DisplayAttributes & DisplayAttributes.ConsumeLeadingSpaces) != 0)
          {
            repText=repText.TrimStart();
          }
          if ((rep.DisplayAttributes & DisplayAttributes.ZeroTrailingSpaces) != 0)
          {
            repText = repText.TrimEnd();
          }
          label.Text += String.Format("      At index {0} for {1} words. Text: \"{2}\"\n",
                                      rep.FirstWordIndex, rep.CountOfWords, repText);

        }
        label.Text += String.Format("\n\n");
      }
    }
  }
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

ReplacementText Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ReplacementText Members

[image] [image]

ReplacementText Members
ReplacementText Class Methods Properties See Also Send Feedback

Contains information about a speech normalization procedure that has been performed on recognition results.

The ReplacementText type exposes the following members.

Properties

 | Name | Description
Public property | CountOfWords | Gets the number of recognized words replaced by the speech normalization procedure.
Public property | DisplayAttributes | Gets information about the leading and trailing spaces for the text replaced by normalization.
Public property | FirstWordIndex | Gets the location of the first recognized word replaced by the speech normalization procedure.
Public property | Text | Gets the recognized text replaced by the speech normalization procedure.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

ReplacementText Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ReplacementText Methods

[image] [image]

ReplacementText Methods
ReplacementText Class See Also Send Feedback

The ReplacementText type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

ReplacementText Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ReplacementText Properties

[image] [image]

ReplacementText Properties
ReplacementText Class See Also Send Feedback

The ReplacementText type exposes the following members.

Properties

 | Name | Description
Public property | CountOfWords | Gets the number of recognized words replaced by the speech normalization procedure.
Public property | DisplayAttributes | Gets information about the leading and trailing spaces for the text replaced by normalization.
Public property | FirstWordIndex | Gets the location of the first recognized word replaced by the speech normalization procedure.
Public property | Text | Gets the recognized text replaced by the speech normalization procedure.
Top

See Also

Reference

ReplacementText Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


CountOfWords Property

[image]

ReplacementText..::..CountOfWords Property
ReplacementText Class Example See Also Send Feedback

Gets the number of recognized words replaced by the speech normalization procedure.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property CountOfWords As Integer
    Get
Visual Basic (Usage)
Dim instance As ReplacementText
Dim value As Integer

value = instance.CountOfWords
C#
public int CountOfWords { get; }

Property Value

Type: System..::..Int32

Returns the number of recognized words replaced by the speech normalization procedure.

Examples

The example below displays information in a user interface about a RecognizedPhrase object returned by a recognition engine.

C# Copy image Copy Code
internal static void DisplayBasicPhraseInfo(Label label, RecognizedPhrase result, SpeechRecognitionEngine rec)
{
  if (result != null && label != null)
  { // Blank
    if (rec != null)
    { // Clear
      label.Text += String.Format(
                       "  Recognizer currently at:   {0} mSec\n" +
                       "  Audio Device currently at: {1} mSec\n",
                       rec.RecognizerAudioPosition.TotalMilliseconds,
                       rec.AudioPosition.TotalMilliseconds);
    }

    if (result != null)
    { // Clear
      RecognitionResult recResult = result as RecognitionResult;
      if (recResult != null)
      {
        RecognizedAudio resultAudio = recResult.Audio;
        if (resultAudio == null)
        {
          label.Text += String.Format(
                               "  Emulated input\n");
        }
        else
        {
          label.Text += String.Format(
                            "  Candidate Phrase at:       {0} mSec\n" +
                            "  Phrase Length:             {1} mSec\n" +
                            "  Input State Time:          {2}\n" +
                            "  Input Format:              {3}\n",
                            resultAudio.AudioPosition.TotalMilliseconds,
                            resultAudio.Duration.TotalMilliseconds,
                            resultAudio.StartTime.ToShortTimeString(),
                            resultAudio.Format.EncodingFormat.ToString());
        }
      }

      label.Text += String.Format("  Confidence Level:          {0}\n", result.Confidence);
      if (result.Grammar != null)
      {
        label.Text += String.Format(
                         "  Recognizing Grammar:       {0}\n" +
                         "  Recognizing Rule:          {1}\n",
                         ((result.Grammar.Name != null) ? (result.Grammar.Name) : "None"),
                         ((result.Grammar.RuleName != null) ? (result.Grammar.RuleName) : "None"));
      }

      if  (result.ReplacementWordUnits.Count !=  0)
      {
        label.Text += String.Format("  Replacement text:\n");
        foreach  (ReplacementText rep in result.ReplacementWordUnits)
        {
          string repText = rep.Text;
          // Add trailing spaces
          if ((rep.DisplayAttributes & DisplayAttributes.OneTrailingSpace) !=  0)
          {
            repText += " ";
          }
          if ((rep.DisplayAttributes & DisplayAttributes.TwoTrailingSpaces) != 0)
          {
            repText += "  ";
          }
          if ((rep.DisplayAttributes & DisplayAttributes.ConsumeLeadingSpaces) != 0)
          {
            repText=repText.TrimStart();
          }
          if ((rep.DisplayAttributes & DisplayAttributes.ZeroTrailingSpaces) != 0)
          {
            repText = repText.TrimEnd();
          }
          label.Text += String.Format("      At index {0} for {1} words. Text: \"{2}\"\n",
                                      rep.FirstWordIndex, rep.CountOfWords, repText);

        }
        label.Text += String.Format("\n\n");
      }
    }
  }
}

See Also

Reference

ReplacementText Class
ReplacementText Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


DisplayAttributes Property

[image]

ReplacementText..::..DisplayAttributes Property
ReplacementText Class Example See Also Send Feedback

Gets information about the leading and trailing spaces for the text replaced by normalization.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property DisplayAttributes As DisplayAttributes
    Get
Visual Basic (Usage)
Dim instance As ReplacementText
Dim value As DisplayAttributes

value = instance.DisplayAttributes
C#
public DisplayAttributes DisplayAttributes { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..DisplayAttributes

Returns a DisplayAttributes object that specifies the use of white space to display text replaced by normalization.

Examples

The example below displays information in a user interface about a RecognizedPhrase object returned by a recognition engine.

Copy image Copy Code
internal static void DisplayBasicPhraseInfo(Label label, RecognizedPhrase result, SpeechRecognitionEngine rec)
{
  if (result != null && label != null)
  { // Blank
    if (rec != null)
    { // Clear
      label.Text += String.Format(
                       "  Recognizer currently at:   {0} mSec\n" +
                       "  Audio Device currently at: {1} mSec\n",
                       rec.RecognizerAudioPosition.TotalMilliseconds,
                       rec.AudioPosition.TotalMilliseconds);
    }

    if (result != null)
    { // Clear
      RecognitionResult recResult = result as RecognitionResult;
      if (recResult != null)
      {
        RecognizedAudio resultAudio = recResult.Audio;
        if (resultAudio == null)
        {
          label.Text += String.Format(
                               "  Emulated input\n");
        }
        else
        {
          label.Text += String.Format(
                            "  Candidate Phrase at:       {0} mSec\n" +
                            "  Phrase Length:             {1} mSec\n" +
                            "  Input State Time:          {2}\n" +
                            "  Input Format:              {3}\n",
                            resultAudio.AudioPosition.TotalMilliseconds,
                            resultAudio.Duration.TotalMilliseconds,
                            resultAudio.StartTime.ToShortTimeString(),
                            resultAudio.Format.EncodingFormat.ToString());
        }
      }

      label.Text += String.Format("  Confidence Level:          {0}\n", result.Confidence);
      if (result.Grammar != null)
      {
        label.Text += String.Format(
                         "  Recognizing Grammar:       {0}\n" +
                         "  Recognizing Rule:          {1}\n",
                         ((result.Grammar.Name != null) ? (result.Grammar.Name) : "None"),
                         ((result.Grammar.RuleName != null) ? (result.Grammar.RuleName) : "None"));
      }

      if  (result.ReplacementWordUnits.Count !=  0)
      {
        label.Text += String.Format("  Replacement text:\n");
        foreach  (ReplacementText rep in result.ReplacementWordUnits)
        {
          string repText = rep.Text;
          // Add trailing spaces
          if ((rep.DisplayAttributes & DisplayAttributes.OneTrailingSpace) !=  0)
          {
            repText += " ";
          }
          if ((rep.DisplayAttributes & DisplayAttributes.TwoTrailingSpaces) != 0)
          {
            repText += "  ";
          }
          if ((rep.DisplayAttributes & DisplayAttributes.ConsumeLeadingSpaces) != 0)
          {
            repText=repText.TrimStart();
          }
          if ((rep.DisplayAttributes & DisplayAttributes.ZeroTrailingSpaces) != 0)
          {
            repText = repText.TrimEnd();
          }
          label.Text += String.Format("      At index {0} for {1} words. Text: \"{2}\"\n",
                                      rep.FirstWordIndex, rep.CountOfWords, repText);

        }
        label.Text += String.Format("\n\n");
      }
    }
  }
}

See Also

Reference

ReplacementText Class
ReplacementText Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


FirstWordIndex Property

[image]

ReplacementText..::..FirstWordIndex Property
ReplacementText Class Example See Also Send Feedback

Gets the location of the first recognized word replaced by the speech normalization procedure.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property FirstWordIndex As Integer
    Get
Visual Basic (Usage)
Dim instance As ReplacementText
Dim value As Integer

value = instance.FirstWordIndex
C#
public int FirstWordIndex { get; }

Property Value

Type: System..::..Int32

Returns the location of the first recognized word replaced by the speech normalization procedure.

Examples

The example below displays information in a user interface about a RecognizedPhrase object returned by a recognition engine.

Copy image Copy Code
internal static void DisplayBasicPhraseInfo(Label label, RecognizedPhrase result, SpeechRecognitionEngine rec)
{
  if (result != null && label != null)
  { // Blank
    if (rec != null)
    { // Clear
      label.Text += String.Format(
                       "  Recognizer currently at:   {0} mSec\n" +
                       "  Audio Device currently at: {1} mSec\n",
                       rec.RecognizerAudioPosition.TotalMilliseconds,
                       rec.AudioPosition.TotalMilliseconds);
    }

    if (result != null)
    { // Clear
      RecognitionResult recResult = result as RecognitionResult;
      if (recResult != null)
      {
        RecognizedAudio resultAudio = recResult.Audio;
        if (resultAudio == null)
        {
          label.Text += String.Format(
                               "  Emulated input\n");
        }
        else
        {
          label.Text += String.Format(
                            "  Candidate Phrase at:       {0} mSec\n" +
                            "  Phrase Length:             {1} mSec\n" +
                            "  Input State Time:          {2}\n" +
                            "  Input Format:              {3}\n",
                            resultAudio.AudioPosition.TotalMilliseconds,
                            resultAudio.Duration.TotalMilliseconds,
                            resultAudio.StartTime.ToShortTimeString(),
                            resultAudio.Format.EncodingFormat.ToString());
        }
      }

      label.Text += String.Format("  Confidence Level:          {0}\n", result.Confidence);
      if (result.Grammar != null)
      {
        label.Text += String.Format(
                         "  Recognizing Grammar:       {0}\n" +
                         "  Recognizing Rule:          {1}\n",
                         ((result.Grammar.Name != null) ? (result.Grammar.Name) : "None"),
                         ((result.Grammar.RuleName != null) ? (result.Grammar.RuleName) : "None"));
      }

      if  (result.ReplacementWordUnits.Count !=  0)
      {
        label.Text += String.Format("  Replacement text:\n");
        foreach  (ReplacementText rep in result.ReplacementWordUnits)
        {
          string repText = rep.Text;
          // Add trailing spaces
          if ((rep.DisplayAttributes & DisplayAttributes.OneTrailingSpace) !=  0)
          {
            repText += " ";
          }
          if ((rep.DisplayAttributes & DisplayAttributes.TwoTrailingSpaces) != 0)
          {
            repText += "  ";
          }
          if ((rep.DisplayAttributes & DisplayAttributes.ConsumeLeadingSpaces) != 0)
          {
            repText=repText.TrimStart();
          }
          if ((rep.DisplayAttributes & DisplayAttributes.ZeroTrailingSpaces) != 0)
          {
            repText = repText.TrimEnd();
          }
          label.Text += String.Format("      At index {0} for {1} words. Text: \"{2}\"\n",
                                      rep.FirstWordIndex, rep.CountOfWords, repText);

        }
        label.Text += String.Format("\n\n");
      }
    }
  }
}

See Also

Reference

ReplacementText Class
ReplacementText Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Text Property

[image]

ReplacementText..::..Text Property
ReplacementText Class Example See Also Send Feedback

Gets the recognized text replaced by the speech normalization procedure.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Text As String
    Get
Visual Basic (Usage)
Dim instance As ReplacementText
Dim value As String

value = instance.Text
C#
public string Text { get; }

Property Value

Type: System..::..String

Returns the recognized text replaced by the speech normalization procedure.

Examples

The example below displays information in a user interface about a RecognizedPhrase object returned by a recognition engine.

Copy image Copy Code
internal static void DisplayBasicPhraseInfo(Label label, RecognizedPhrase result, SpeechRecognitionEngine rec)
{
  if (result != null && label != null)
  { // Blank
    if (rec != null)
    { // Clear
      label.Text += String.Format(
                       "  Recognizer currently at:   {0} mSec\n" +
                       "  Audio Device currently at: {1} mSec\n",
                       rec.RecognizerAudioPosition.TotalMilliseconds,
                       rec.AudioPosition.TotalMilliseconds);
    }

    if (result != null)
    { // Clear
      RecognitionResult recResult = result as RecognitionResult;
      if (recResult != null)
      {
        RecognizedAudio resultAudio = recResult.Audio;
        if (resultAudio == null)
        {
          label.Text += String.Format(
                               "  Emulated input\n");
        }
        else
        {
          label.Text += String.Format(
                            "  Candidate Phrase at:       {0} mSec\n" +
                            "  Phrase Length:             {1} mSec\n" +
                            "  Input State Time:          {2}\n" +
                            "  Input Format:              {3}\n",
                            resultAudio.AudioPosition.TotalMilliseconds,
                            resultAudio.Duration.TotalMilliseconds,
                            resultAudio.StartTime.ToShortTimeString(),
                            resultAudio.Format.EncodingFormat.ToString());
        }
      }

      label.Text += String.Format("  Confidence Level:          {0}\n", result.Confidence);
      if (result.Grammar != null)
      {
        label.Text += String.Format(
                         "  Recognizing Grammar:       {0}\n" +
                         "  Recognizing Rule:          {1}\n",
                         ((result.Grammar.Name != null) ? (result.Grammar.Name) : "None"),
                         ((result.Grammar.RuleName != null) ? (result.Grammar.RuleName) : "None"));
      }

      if  (result.ReplacementWordUnits.Count !=  0)
      {
        label.Text += String.Format("  Replacement text:\n");
        foreach  (ReplacementText rep in result.ReplacementWordUnits)
        {
          string repText = rep.Text;
          // Add trailing spaces
          if ((rep.DisplayAttributes & DisplayAttributes.OneTrailingSpace) !=  0)
          {
            repText += " ";
          }
          if ((rep.DisplayAttributes & DisplayAttributes.TwoTrailingSpaces) != 0)
          {
            repText += "  ";
          }
          if ((rep.DisplayAttributes & DisplayAttributes.ConsumeLeadingSpaces) != 0)
          {
            repText=repText.TrimStart();
          }
          if ((rep.DisplayAttributes & DisplayAttributes.ZeroTrailingSpaces) != 0)
          {
            repText = repText.TrimEnd();
          }
          label.Text += String.Format("      At index {0} for {1} words. Text: \"{2}\"\n",
                                      rep.FirstWordIndex, rep.CountOfWords, repText);

        }
        label.Text += String.Format("\n\n");
      }
    }
  }
}

See Also

Reference

ReplacementText Class
ReplacementText Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultKey Class

[image]

SemanticResultKey Class
Members Example See Also Send Feedback

Associates a key string with SemanticResultValue values to define the SemanticValue objects.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..SemanticResultKey

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

Syntax

Visual Basic (Declaration)
Public Class SemanticResultKey
Visual Basic (Usage)
Dim instance As SemanticResultKey
C#
public class SemanticResultKey

Remarks

The basic unit of semantic expression under the Microsoft Speech Platform SDK 11 is the SemanticValue, which is a key-value pair.

The SemanticResultKey object tags SemanticResultValue instances contained in GrammarBuilder objects and strings so that the values can readily be accessed from SemanticValue instances following recognition.

You can use SemanticResultValue and SemanticResultKey objects, in conjunction with GrammarBuilder and Choices objects, to define the semantic structure for a speech recognition grammar. To access the semantic information in a recognition result, obtain a SemanticValue instance through the Semantics property on RecognizedPhrase.

For more information about using SemanticResultValue and SemanticResultKey objects, see Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech) and Use a SemanticResultKey to Extract a SemanticResultValue (Microsoft.Speech).

Examples

The following example creates a Grammar to recognize password input of the form "My password is …", where the actual input is matched with a wildcard.

The wildcard is tagged with a semantic key, and the SpeechRecognized handler checks for the presence of this tag to verify that a password input has occurred.

C# Copy image Copy Code
private void pwdGrammar()
{
  GrammarBuilder pwdBuilder = new GrammarBuilder("My Password is");
  GrammarBuilder wildcardBuilder = new GrammarBuilder();
  wildcardBuilder.AppendWildcard();
  SemanticResultKey wildcardKey= new SemanticResultKey("Password", wildcardBuilder);
  pwdBuilder+=wildcardKey;
  Grammar grammar = new Grammar(pwdBuilder);
  grammar.Name = "Password input";

  grammar.SpeechRecognized +=
    delegate(object sender, SpeechRecognizedEventArgs eventArgs)
    {
      SemanticValue semantics = eventArgs.Result.Semantics;
      RecognitionResult result=eventArgs.Result;

      if (!semantics.ContainsKey("Password"))
      {
        SpeechUI.SendTextFeedback(eventArgs.Result, "No Password Provided", false);
      }
      else
      {
        RecognizedAudio pwdAudio =
            result.GetAudioForWordRange(result.Words[3],
            result.Words[result.Words.Count - 1]);
        MemoryStream pwdMemoryStream = new MemoryStream();
        pwdAudio.WriteToAudioStream(pwdMemoryStream);
        if (!IsValidPwd(pwdMemoryStream))
        {
          string badPwd = System.IO.Path.GetTempPath() +
                   "BadPwd" +
                   (new Random()).Next().ToString() +
                   ".wav";
          FileStream waveStream = new FileStream(badPwd, FileMode.Create);
          pwdAudio.WriteToWaveStream(waveStream);
          waveStream.Flush();
          waveStream.Close();
          SpeechUI.SendTextFeedback(eventArgs.Result, "Invalid Password", false);

        }
      }
    };

  grammar.Enabled = true;
  _recognizer.LoadGrammar(grammar);
  UpdateGrammarTree(_grammarTreeView, _recognizer);
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SemanticResultKey Members
Microsoft.Speech.Recognition Namespace
SemanticValue
SemanticResultValue

Other Resources

Add Semantics to a GrammarBuilder Grammar (Microsoft.Speech)
Use a SemanticResultKey to Extract a SemanticResultValue (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultKey Members

[image] [image]

SemanticResultKey Members
SemanticResultKey Class Constructors Methods See Also Send Feedback

Associates a key string with SemanticResultValue values to define the SemanticValue objects.

The SemanticResultKey type exposes the following members.

Constructors

 | Name | Description
Public method | SemanticResultKey(String, array<GrammarBuilder>[]()[][]) | Assigns a semantic key to one or more GrammarBuilder objects used to create a speech recognition grammar.
Public method | SemanticResultKey(String, array<String>[]()[][]) | Assigns a semantic key to one or more String instances used to create a speech recognition grammar.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToGrammarBuilder | Returns an instance of GrammarBuilder constructed from the current SemanticResultKey instance.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SemanticResultKey Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultKey Constructor

[image] [image]

SemanticResultKey Constructor
SemanticResultKey Class See Also Send Feedback

Constructs a new instance of the SemanticResultKey class and associates the key with grammar components.

Overload List

 | Name | Description
Public method | SemanticResultKey(String, array<GrammarBuilder>[]()[][]) | Assigns a semantic key to one or more GrammarBuilder objects used to create a speech recognition grammar.
Public method | SemanticResultKey(String, array<String>[]()[][]) | Assigns a semantic key to one or more String instances used to create a speech recognition grammar.
Top

Remarks

The constructors for SemanticResultKey specify a text tag (the semantic key) and a set of grammar components to add to a speech recognition grammar.

The grammar components can be specified either as an array of GrammarBuilder objects, or as an array of String instances.

If the grammar components are used in recognition, you can access the returned SemanticValue using the text tag provided to the constructor of SemanticResultKey as a semantic key. The Value property of the SemanticValue instance will be determined by the grammar components used in the definition of SemanticResultKey.

See Also

Reference

SemanticResultKey Class
SemanticResultKey Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultKey Constructor (String, GrammarBuilder[])

[image]

SemanticResultKey Constructor (String, array<GrammarBuilder>[]()[][])
SemanticResultKey Class Example See Also Send Feedback

Assigns a semantic key to one or more GrammarBuilder objects used to create a speech recognition grammar.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    semanticResultKey As String, _
    ParamArray builders As GrammarBuilder() _
)
Visual Basic (Usage)
Dim semanticResultKey As String
Dim builders As GrammarBuilder()

Dim instance As New SemanticResultKey(semanticResultKey, _
    builders)
C#
public SemanticResultKey(
    string semanticResultKey,
    params GrammarBuilder[] builders
)

Parameters

semanticResultKey
Type: System..::..String

The tag to be used as a semantic key to access the SemanticValue instance associated with the GrammarBuilder objects specified by the builders argument.

builders
Type: array< Microsoft.Speech.Recognition..::..GrammarBuilder >[]()[][]

An array of grammar components that will be associated with a SemanticValue object accessible with the tag defined in semanticResultKey.

Remarks

Because of implicit conversions, the builders argument supports SemanticResultValue, SemanticResultKey, and Choices objects. For more information on implicit conversions, see ImplicitWideningImplicitImplicitImplicit.

When performing a recognition operation, the GrammarBuilder objects provided in the builders argument are treated as sequential. For example, if the following SemanticResultValue is used to construct a Grammar, input to the recognition engine must contain "the quick brown fox" to be recognized.

C# Copy image Copy Code
SemanticResultKey stringTest=new SemanticResultKey(
          "stringTest", new GrammarBuilder[] {
    new GrammarBuilder("the"),
    new GrammarBuilder("quick"),
    new GrammarBuilder("brown"),
    new GrammarBuilder("fox")});

The semanticResultKey argument contains the tag used to access the SemanticValue which might be returned.

The Value of the SemanticValue is determined by the GrammarBuilder instances provided by the builders parameter.

If the GrammarBuilder objects contain no defining instances of SemanticResultValue, the value of the SemanticValue is nullNothingnullptrunita null reference (Nothing in Visual Basic).

If the GrammarBuilder objects provided in the builders parameter provide an untagged (not associated with a SemanticResultKey object) SemanticResultValue instance that is used by the recognition logic, that instance of SemanticResultValue will define the Value property of the SemanticValue that is produced.

There should be one, and only one, untagged SemanticResultValue instance in the GrammarBuilder objects specified by the builders parameter. If multiple instances of untagged SemanticResultValue are associated with the SemanticResultKey, each will attempt to the set the value of the SemanticValue produced in the recognition result. This is not permitted, and the recognizer will generate an exception when it attempts to use a Grammar created using such a SemanticResultKey instance.

Instances of SemanticResultValue contained in the GrammarBuilder objects specified by the builders parameter and already associated with another SemanticResultKey have no effect on the current SemanticResultKey instance.

Examples

The example below creates a Grammar to recognize password input of the form "My password is …", where the actual input is matched with a wildcard.

The wildcard is tagged by a speech recognizer whose key value is "Password". The SpeechRecognized handler checks for the presence of this tag, obtains the audio input of the password, and verifies the password.

C# Copy image Copy Code
private void pwdGrammar()
{
  GrammarBuilder pwdBuilder = new GrammarBuilder("My Password is");
  GrammarBuilder wildcardBuilder = new GrammarBuilder();
  wildcardBuilder.AppendWildcard();
  SemanticResultKey wildcardKey= new SemanticResultKey("Password", wildcardBuilder);
  pwdBuilder+=wildcardKey;
  Grammar grammar = new Grammar(pwdBuilder);
  grammar.Name = "Password input";
  grammar.SpeechRecognized +=
    delegate(object sender, SpeechRecognizedEventArgs eventArgs)
    {
      SemanticValue semantics = eventArgs.Result.Semantics;
      RecognitionResult result=eventArgs.Result;

      if (!semantics.ContainsKey("Password"))
      {
        SpeechUI.SendTextFeedback(eventArgs.Result, "No Password Provided", false);
      }
      else
      {
        RecognizedAudio pwdAudio = result.GetAudioForWordRange(
              result.Words[3],
              result.Words[result.Words.Count - 1]);
        MemoryStream pwdMemoryStream = new MemoryStream();
        pwdAudio.WriteToAudioStream(pwdMemoryStream);
        if (!IsValidPwd(pwdMemoryStream))
        {
          string badPwd = System.IO.Path.GetTempPath() +
                         "BadPwd" +
                         (new Random()).Next().ToString() +
                         ".wav";
          FileStream waveStream = new FileStream(badPwd, FileMode.Create);
          pwdAudio.WriteToWaveStream(waveStream);
          waveStream.Flush();
          waveStream.Close();
          SpeechUI.SendTextFeedback(eventArgs.Result, "Invalid Password", false);

        }
      }
    };

  grammar.Enabled = true;
  _recognizer.LoadGrammar(grammar);
  UpdateGrammarTree(_grammarTreeView, _recognizer);

}

See Also

Reference

SemanticResultKey Class
SemanticResultKey Members
SemanticResultKey Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultKey Constructor (String, String[])

[image]

SemanticResultKey Constructor (String, array<String>[]()[][])
SemanticResultKey Class Example See Also Send Feedback

Assigns a semantic key to one or more String instances used to create a speech recognition grammar.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    semanticResultKey As String, _
    ParamArray phrases As String() _
)
Visual Basic (Usage)
Dim semanticResultKey As String
Dim phrases As String()

Dim instance As New SemanticResultKey(semanticResultKey, _
    phrases)
C#
public SemanticResultKey(
    string semanticResultKey,
    params string[] phrases
)

Parameters

semanticResultKey
Type: System..::..String

The tag to be used to access the SemanticValue instance associated with the Stringobjects specified by the phrases argument.

phrases
Type: array< System..::..String >[]()[][]

One or more String objects whose concatenated text will be associated with a SemanticValue object accessible with the tag defined in semanticResultKey.

Remarks

When performing a recognition operation, the String instances referred to in the phrases argument are treated as sequential. For example, if the following SemanticResultValue is used to construct a Grammar, input to the recognition engine must contain "the quick brown fox" to be recognized.

C# Copy image Copy Code
SemanticResultKey stringTest=new SemanticResultKey("stringTest",
                                new string[] {
                                               "the",
                                               "quick",
                                               "brown",
                                               "fox"});

The semanticResultKey argument determines the key used to access the SemanticValue.

If you construct a Grammar using a GrammarBuilder object that contains a semantic key with an array of string objects, the Value of the SemanticValue produced by a recognition operation will be the string used in recognition. In the preceding example, this means that Value would be "the quick brown fox".

Examples

The following example creates a Grammar from a GrammarBuilder object that uses a SemanticResultKey, which is defined by an array of String objects.

A recognition engine using the Grammar created will recognize the phrase "color red green blue zero". The semantics of the RecognizedPhrase returned by recognition will contain a SemanticValue with a Value of "red green blue". You can access the SemanticValue using the "code" tag.

Because of the SemanticResultValue("zero", 5) appended to the GrammarBuilder, the root SemanticValue object in the RecognizedPhrase will have a value of 5.

C# Copy image Copy Code
private void keyTest()
  {
  //Say "color red green blue zero"
  GrammarBuilder gb = new GrammarBuilder("color") +
                        new SemanticResultKey("code",
                          (new string[] {"red", "green", "blue"})) +
                        new SemanticResultValue("zero", 5);
  Grammar g = new Grammar(gb);
  g.Name = "keyTest";
  _recognizer.LoadGrammar(g);
}

See Also

Reference

SemanticResultKey Class
SemanticResultKey Members
SemanticResultKey Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultKey Methods

[image] [image]

SemanticResultKey Methods
SemanticResultKey Class See Also Send Feedback

The SemanticResultKey type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToGrammarBuilder | Returns an instance of GrammarBuilder constructed from the current SemanticResultKey instance.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SemanticResultKey Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ToGrammarBuilder Method

[image]

SemanticResultKey..::..ToGrammarBuilder Method
SemanticResultKey Class Example See Also Send Feedback

Returns an instance of GrammarBuilder constructed from the current SemanticResultKey instance.

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

Syntax

Visual Basic (Declaration)
Public Function ToGrammarBuilder As GrammarBuilder
Visual Basic (Usage)
Dim instance As SemanticResultKey
Dim returnValue As GrammarBuilder

returnValue = instance.ToGrammarBuilder()
C#
public GrammarBuilder ToGrammarBuilder()

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

Remarks

The use of ToGrammarBuilder is equivalent to using the GrammarBuilder constructor that takes a SemanticResultKey object as an argument (GrammarBuilder(SemanticResultKey)).

Examples

The following example creates a Grammar object that supports commands to change the background color.

A Choices object (colorChoice) containing the list of options for background colors is filled using the Add(array<GrammarBuilder>[]()[][]) method with GrammarBuilder instances. The GrammarBuilder instances are obtained through the ToGrammarBuilder()()()() method on the SemanticResultValue objects created from color strings.

A GrammarBuilder is then obtained by calling ToGrammarBuilder()()()() on a SemanticResultKey instance, which will be used to key the semantic choices in colorChoice.

C# Copy image Copy Code
private Grammar CreateGrammarBuilderRGBSemantics()
{
  // Create a set of choices, each a lookup from a color name to the RGB value.
  // Choices constructors do not take SemanticResultValue arguments,
  // so cast SemanticResultValue to GramarBuilder.
  Choices colorChoice = new Choices();
  foreach (string colorName in System.Enum.GetNames(typeof(KnownColor)))
  {
    SemanticResultValue colorValue=new SemanticResultValue(colorName, Color.FromName(colorName).ToArgb());
    // Uses implicit conversion of SemanticResultValue to GrammarBuilder
    colorChoice.Add(colorValue.ToGrammarBuilder());
  }
  SemanticResultKey choiceKey = new SemanticResultKey("rgb", colorChoice);
  GrammarBuilder choiceBuilder = choiceKey.ToGrammarBuilder();

  // Create two intermediate grammars with introductory phrase and the color choice.
  GrammarBuilder makeBackgroundBuilder = "Make background";
  makeBackgroundBuilder.Append(choiceBuilder);

  GrammarBuilder configureBackgroundBuilder = new GrammarBuilder("Configure background as");
  configureBackgroundBuilder.Append((new SemanticResultKey("rgb", colorChoice)).ToGrammarBuilder());

  // Create the final grammar, which recognizes either intermediate grammar.
  Grammar grammar = new Grammar(new Choices(makeBackgroundBuilder, configureBackgroundBuilder));
  grammar.Name = "Make Background /Configure background as";

  return grammar;
}

See Also

Reference

SemanticResultKey Class
SemanticResultKey Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultValue Class

[image]

SemanticResultValue Class
Members Example See Also Send Feedback

Represents a semantic value and optionally associates the value with a component of a speech recognition grammar.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..SemanticResultValue

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

Syntax

Visual Basic (Declaration)
Public Class SemanticResultValue
Visual Basic (Usage)
Dim instance As SemanticResultValue
C#
public class SemanticResultValue

Remarks

You can use SemanticResultValue and SemanticResultKey objects, in conjunction with GrammarBuilder and Choices objects, to define the semantic structure for a speech recognition grammar. To access the semantic information in a recognition result, obtain a SemanticValue instance through the Semantics property on RecognizedPhrase.

Note Note

Values managed by SemanticResultValue objects are defined by Object instances passed to their constructors. The underlying type of this Object must be bool, int, float, or string. Any other type will prevent construction of a Grammar instance with the SemanticResultValue.

Typical use associates the semantic value specified by a SemanticResultValue instance with a recognizable component of a Grammar object, such as a phrase, a rule, or a Choices object. If the associated grammar component is used in a recognition operation, the value specified by SemanticResultValue is assigned to the Semantics property of the RecognizedPhrase.

You can associate a SemanticResultValue instance with a grammar component in one of two ways, depending on the constructor used to create the SemanticResultValue.

  1. Construct a SemanticResultValue and specify only a value. Incorporate the SemanticResultValue in a GrammarBuilder object. The value is associated with the grammar component that preceded it, in addition to a GrammarBuilder object.

    For instance, in the code fragment below, if a Grammar constructed using this GrammarBuilder instance recognizes the word "background", a value of true is set in the recognized phrase semantics.

    Copy image Copy Code
    GrammarBuilder backgroundGB=new GrammarBuilder("background");
backgroundGB.Append(new SemanticResultValue(true));

    For more information, see the description of SemanticResultValue(Object).

  2. Construct a SemanticResultValue and specify a grammar component as well as a value. The value will be associated with the specified grammar component. If the grammar component is used during speech recognition, the value specified by SemanticResultValue will be assigned to the Semantics property of the RecognizedPhrase object.

    The code fragment below illustrates this, and is functionally equivalent to the fragment above, which used explicit calls to Append(SemanticResultValue) and SemanticResultValue(Object). If the recognition logic uses the word "background", the value true will be added to the recognized semantics.

    Copy image Copy Code
    fgOrbgChoice.Add((GrammarBuilder)new SemanticResultValue("background", true));

    For more information, see the description of SemanticResultValue(GrammarBuilder, Object) and SemanticResultValue(String, Object).

To be used by a Grammar in recognition, all SemanticResultValue instances must be associated with one of the SemanticResultValue objects used by that Grammar. This is done by associating a semantic key with the SemanticResultValue.

Semantic keys can be explicitly attached to a SemanticResultValue using a SemanticResultKey object. SemanticResultValue instances not explicitly attached to a key are attached to the root key of the default SemanticValue.

Once an SemanticResultValue has been used to set the Value, whether it is tagged with the default root key or by any particular SemanticResultValue, that value must not be modified or an exception will occur during recognition operations.

The following example will cause an exception because it sets and then modifies the root Value of a Grammar.

Copy image Copy Code
GrammarBuilder gb=new GrammarBuilder();
gb.Append(new SemanticResultValue("One"));
gb.Append(new SemanticResultValue("Two"));

On the other hand, the code in the following example is permitted. Although it defines multiple instances of SemanticResultValue, they are included in a Choices object, and only one will ever be used to set the value of the key BgOrFgText.

Copy image Copy Code
Choices fgOrbgChoice = new Choices();
fgOrbgChoice.Add((GrammarBuilder)new SemanticResultValue("background"));
fgOrbgChoice.Add((GrammarBuilder)new SemanticResultValue("foreground"));
SemanticResultKey fgOrbgChoiceKey = new SemanticResultKey("BgOrFgText", fgOrbgChoice);

Examples

The example below returns a Grammar for recognizing the command "Set/Change/Alter Foreground/Background … [color list]". SemanticResultValue and SemanticResultKey instances (along with Choices and GrammarBuilder objects) are used to define semantics that can be parsed on recognition. The parsed semantics will determine which color was requested and whether the foreground or background is to be modified.

Copy image Copy Code
private Grammar FgBgColorGrammar() {
    Grammar grammar = null;
    //Allow command to begin with set, alter, change.
    Choices introChoices = new Choices();
    foreach (string introString in new string[] { "Change", "Set", "Alter" }) {
        GrammarBuilder introGB = new GrammarBuilder(introString);
        introChoices.Add(new SemanticResultValue(introGB,
                            String.Format("Command: {0}", introString)));
    }
    GrammarBuilder cmdIntro = new GrammarBuilder(introChoices);
    //Now define the arguments to the command for Foreground or background and color as sementic Values
    Choices fgOrbgChoice = new Choices();
    GrammarBuilder backgroundGB=new GrammarBuilder("background");
    backgroundGB.Append(new SemanticResultValue(true));
    fgOrbgChoice.Add(backgroundGB);
    fgOrbgChoice.Add((GrammarBuilder)new SemanticResultValue("foreground", false));
    SemanticResultKey fgOrbgChoiceKey = new SemanticResultKey("BgOrFgBool", fgOrbgChoice);
    Choices colorChoice = new Choices();
    foreach (string colorName in System.Enum.GetNames(typeof(KnownColor))) {
        colorChoice.Add((GrammarBuilder)
                                        (new SemanticResultValue(colorName, (Color.FromName(colorName)).Name)));
        //Uses implicit conversion of SemanticResultValue to GrammarBuilder
    }

    //Create GrammarBuilder for CmdArgs to be appended to CmdInto using Semantic keys.
    GrammarBuilder cmdArgs = new GrammarBuilder();
    cmdArgs.Append(new SemanticResultKey("BgOrFgBool", fgOrbgChoice));
    cmdArgs.AppendWildcard();
    cmdArgs.Append(new SemanticResultKey("colorStringList", colorChoice));

    GrammarBuilder cmds = GrammarBuilder.Add(cmdIntro,
                                             new GrammarBuilder(new SemanticResultKey("Cmd Args", cmdArgs)));
    grammar = new Grammar(cmds);
    grammar.Name = "Tree [Set,change,alter] [foreground,background] * color";
    return grammar;
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SemanticResultValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultValue Members

[image] [image]

SemanticResultValue Members
SemanticResultValue Class Constructors Methods See Also Send Feedback

Represents a semantic value and optionally associates the value with a component of a speech recognition grammar.

The SemanticResultValue type exposes the following members.

Constructors

 | Name | Description
Public method | SemanticResultValue(Object) | Initializes a new instance of the SemanticResultValue class and specifies a semantic value.
Public method | SemanticResultValue(String, Object) | Initializes a new instance of the SemanticResultValue class and associates a semantic value with a String object.
Public method | SemanticResultValue(GrammarBuilder, Object) | Initializes a new instance of the SemanticResultValue class and associates a semantic value with a GrammarBuilder object.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToGrammarBuilder | Returns an instance of GrammarBuilder constructed from the current SemanticResultValue instance.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SemanticResultValue Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultValue Constructor

[image] [image]

SemanticResultValue Constructor
SemanticResultValue Class See Also Send Feedback

Initializes a new instance of the SemanticResultValue class.

Overload List

 | Name | Description
Public method | SemanticResultValue(Object) | Initializes a new instance of the SemanticResultValue class and specifies a semantic value.
Public method | SemanticResultValue(String, Object) | Initializes a new instance of the SemanticResultValue class and associates a semantic value with a String object.
Public method | SemanticResultValue(GrammarBuilder, Object) | Initializes a new instance of the SemanticResultValue class and associates a semantic value with a GrammarBuilder object.
Top

Remarks

Using these constructors you can build SemanticResultValue objects in any of three ways:

  • Specify only a semantic value. To associate the value with a grammar component, you must incorporate the SemanticResultValue in a GrammarBuilder object. The semantic value will be returned in the recognition result when the grammar component used to match speech input.

  • Specify a semantic value and associate it with a String object. The semantic value will be returned in the recognition result when the contents of the String object are used to match speech input.

  • Specify a semantic value and associate it with a GrammarBuilder object. The semantic value will be returned in the recognition result when the contents of the GrammarBuilder object are used to match speech input.

Note Note

Values managed by SemanticResultValue objects are defined by Object instances passed to their constructors. The underlying type of this Object must be bool, int, float, or string. Any other type will prevent construction of a Grammar instance with the SemanticResultValue.

See Also

Reference

SemanticResultValue Class
SemanticResultValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultValue Constructor (Object)

[image]

SemanticResultValue Constructor (Object)
SemanticResultValue Class Example See Also Send Feedback

Initializes a new instance of the SemanticResultValue class and specifies a semantic value.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    value As Object _
)
Visual Basic (Usage)
Dim value As Object

Dim instance As New SemanticResultValue(value)
C#
public SemanticResultValue(
    Object value
)

Parameters

value
Type: System..::..Object

The value managed by SemanticResultValue. Must be of type bool, int, float, or string.

Remarks

The SemanticResultValue created by this constructor contains only a semantic value, and does not associate the value with any particular grammar component. To associate the value with a grammar component, you must incorporate the SemanticResultValue instance in a GrammarBuilder object. The value is associated with the grammar component that preceded it, in addition to a GrammarBuilder object.

For instance, in the code fragment below, if a Grammar constructed using this GrammarBuilder instance recognizes the word "background", a value of true is set in the recognized phrase semantics.

Copy image Copy Code
GrammarBuilder backgroundGB=new GrammarBuilder("background");
backgroundGB.Append(new SemanticResultValue(true));
Note Note

Values managed by SemanticResultValue objects are defined by Object instances passed to their constructors. The underlying type of this Object must be bool, int, float, or string. Any other type will prevent construction of a Grammar instance with the SemanticResultValue.

Examples

The example below returns a Grammar for recognizing the command "Set/Change/Alter Foreground/Background … [color list]". SemanticResultValue and SemanticResultKey instances (along with Choices and GrammarBuilder objects) are used to define semantics that can be parsed on recognition. The parsed semantics will determine which color was requested and whether the foreground or background is to be modified.

The use of the SemanticResultValue constructor is highlighted, as is the explicit association of returned SemanticResultValue instances with grammar elements.

Copy image Copy Code
private Grammar FgBgColorGrammar() {
    Grammar grammar = null;
    //Allow command to begin with set, alter, change.
    Choices introChoices = new Choices();
    foreach (string introString in new string[] { "Change", "Set", "Alter" }) {
        GrammarBuilder introGB = new GrammarBuilder(introString);
        introChoices.Add(new SemanticResultValue(introGB,
                            String.Format("Command: {0}", introString)));
    }
    GrammarBuilder cmdIntro = new GrammarBuilder(introChoices);
    //Now define the arguments to the command for Foreground or background and color as sementic Values
    Choices fgOrbgChoice = new Choices();    GrammarBuilder backgroundGB=new GrammarBuilder("background");    backgroundGB.Append(new SemanticResultValue(true));    fgOrbgChoice.Add(backgroundGB);
    fgOrbgChoice.Add((GrammarBuilder)new SemanticResultValue("foreground", false));
    SemanticResultKey fgOrbgChoiceKey = new SemanticResultKey("BgOrFgBool", fgOrbgChoice);
    Choices colorChoice = new Choices();
    foreach (string colorName in System.Enum.GetNames(typeof(KnownColor))) {
        colorChoice.Add((GrammarBuilder)
                                        (new SemanticResultValue(colorName, (Color.FromName(colorName)).Name)));
        //Uses implicit conversion of SemanticResultValue to GrammarBuilder
    }

    //Create GrammarBuilder for CmdArgs to be appended to CmdInto using Semantic keys.
    GrammarBuilder cmdArgs = new GrammarBuilder();
    cmdArgs.Append(new SemanticResultKey("BgOrFgBool", fgOrbgChoice));
    cmdArgs.AppendWildcard();
    cmdArgs.Append(new SemanticResultKey("colorStringList", colorChoice));

    GrammarBuilder cmds = GrammarBuilder.Add(cmdIntro,
                                             new GrammarBuilder(new SemanticResultKey("Cmd Args", cmdArgs)));
    grammar = new Grammar(cmds);
    grammar.Name = "Tree [Set,change,alter] [foreground,background] * color";
    return grammar;
}

See Also

Reference

SemanticResultValue Class
SemanticResultValue Members
SemanticResultValue Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultValue Constructor (String, Object)

[image]

SemanticResultValue Constructor (String, Object)
SemanticResultValue Class Example See Also Send Feedback

Initializes a new instance of the SemanticResultValue class and associates a semantic value with a String object.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    phrase As String, _
    value As Object _
)
Visual Basic (Usage)
Dim phrase As String
Dim value As Object

Dim instance As New SemanticResultValue(phrase, _
    value)
C#
public SemanticResultValue(
    string phrase,
    Object value
)

Parameters

phrase
Type: System..::..String

A phrase to be used in recognition.

value
Type: System..::..Object

The value managed by SemanticResultValue. Must be of type bool, int, float, or string.

Remarks

If the String specified by phrase is used in the logic of recognition, the contents of value will be set in the Semantics property of the RecognizedPhrase object.

In the code fragment below, if the recognition logic constructed with the GrammarBuilder instance (myGb) uses the string "my mortgage" to identify input, the value true will be added to the recognized semantics.

Copy image Copy Code
myGb.Append(new SemanticResultValue("my mortgage", true);

Examples

The example below returns a Grammar for recognizing the command "Set/Change/Alter Foreground/Background … [color list]". SemanticResultValue, and SemanticResultKey instances (along with Choices and GrammarBuilder objects) are used to define semantics that can be parsed on recognition. The parsed semantics will determine which color was requested and whether the foreground or background is to be modified.

The use of the SemanticResultValue constructor is highlighted.

Copy image Copy Code
private Grammar FgBgColorGrammar() {
    Grammar grammar = null;
    //Allow command to begin with set, alter, change.
    Choices introChoices = new Choices();
    foreach (string introString in new string[] { "Change", "Set", "Alter" }) {
        GrammarBuilder introGB = new GrammarBuilder(introString);
        introChoices.Add(new SemanticResultValue(introGB,
                            String.Format("Command: {0}", introString)));
    }
    GrammarBuilder cmdIntro = new GrammarBuilder(introChoices);
    //Now define the arguments to the command for Foreground or background and color as sementic Values
    Choices fgOrbgChoice = new Choices();
    GrammarBuilder backgroundGB=new GrammarBuilder("background");
    backgroundGB.Append(new SemanticResultValue(true));
    fgOrbgChoice.Add(backgroundGB);
    fgOrbgChoice.Add((GrammarBuilder)new SemanticResultValue("foreground", false));
    SemanticResultKey fgOrbgChoiceKey = new SemanticResultKey("BgOrFgBool", fgOrbgChoice);
    Choices colorChoice = new Choices();
    foreach (string colorName in System.Enum.GetNames(typeof(KnownColor))) {        colorChoice.Add((GrammarBuilder)                                        (new SemanticResultValue(colorName, (Color.FromName(colorName)).Name)));        //Uses implicit conversion of SemanticResultValue to GrammarBuilder        }

    //Create GrammarBuilder for CmdArgs to be appended to CmdInto using Semantic keys.
    GrammarBuilder cmdArgs = new GrammarBuilder();
    cmdArgs.Append(new SemanticResultKey("BgOrFgBool", fgOrbgChoice));
    cmdArgs.AppendWildcard();
    cmdArgs.Append(new SemanticResultKey("colorStringList", colorChoice));

    GrammarBuilder cmds = GrammarBuilder.Add(cmdIntro,
                                             new GrammarBuilder(new SemanticResultKey("Cmd Args", cmdArgs)));
    grammar = new Grammar(cmds);
    grammar.Name = "Tree [Set,change,alter] [foreground,background] * color";
    return grammar;
}

See Also

Reference

SemanticResultValue Class
SemanticResultValue Members
SemanticResultValue Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultValue Constructor (GrammarBuilder, Object)

[image]

SemanticResultValue Constructor (GrammarBuilder, Object)
SemanticResultValue Class Example See Also Send Feedback

Initializes a new instance of the SemanticResultValue class and associates a semantic value with a GrammarBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    builder As GrammarBuilder, _
    value As Object _
)
Visual Basic (Usage)
Dim builder As GrammarBuilder
Dim value As Object

Dim instance As New SemanticResultValue(builder, _
    value)
C#
public SemanticResultValue(
    GrammarBuilder builder,
    Object value
)

Parameters

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

A grammar component to be used in recognition.

value
Type: System..::..Object

The value managed by SemanticResultValue. Must be of type bool, int, float, or string.

Remarks

If the grammar component specified by GrammarBuilder is used in the logic of recognition, the contents of value will be set in the Semantics property of the RecognizedPhrase object.

In the code fragment below, if the recognition logic constructed with the GrammarBuilder instance (myGb) uses the Choices object (myChoice) to identify input, the value true will be added to the recognized semantics.

Copy image Copy Code
myGb.Append(new SemanticResultValue(myChoice, true);

As GrammarBuilder supports implicit conversion for Choices, SemanticResultValue, and SemanticResultKey, this constructor may use those objects as well.

Examples

The example below returns a Grammar for recognizing the command "Set/Change/Alter Foreground/Background … [color list]". SemanticResultValue and SemanticResultKey instances (along with Choices and GrammarBuilder objects) are used to define semantics that can be parsed on recognition. The parsed semantics will determine which color was requested and whether the foreground or background is to be modified.

The use of the SemanticResultValue constructor is highlighted.

Copy image Copy Code
private Grammar FgBgColorGrammar() {
    Grammar grammar = null;
    //Allow command to begin with set, alter, change.
    Choices introChoices = new Choices();
    foreach (string introString in new string[] { "Change", "Set", "Alter" }) {        GrammarBuilder introGB = new GrammarBuilder(introString);        introChoices.Add(new SemanticResultValue(introGB,                            String.Format("Command: {0}", introString)));    }
    GrammarBuilder cmdIntro = new GrammarBuilder(introChoices);
    //Now define the arguments to the command for Foreground or background and color as sementic Values
    Choices fgOrbgChoice = new Choices();
    GrammarBuilder backgroundGB=new GrammarBuilder("background");
    backgroundGB.Append(new SemanticResultValue(true));
    fgOrbgChoice.Add(backgroundGB);
    fgOrbgChoice.Add((GrammarBuilder)new SemanticResultValue("foreground", false));
    SemanticResultKey fgOrbgChoiceKey = new SemanticResultKey("BgOrFgBool", fgOrbgChoice);
    Choices colorChoice = new Choices();
    foreach (string colorName in System.Enum.GetNames(typeof(KnownColor))) {
        colorChoice.Add((GrammarBuilder)
                                        (new SemanticResultValue(colorName, (Color.FromName(colorName)).Name)));
        //Uses implicit conversion of SemanticResultValue to GrammarBuilder
    }

    //Create GrammarBuilder for CmdArgs to be appended to CmdInto using Semantic keys.
    GrammarBuilder cmdArgs = new GrammarBuilder();
    cmdArgs.Append(new SemanticResultKey("BgOrFgBool", fgOrbgChoice));
    cmdArgs.AppendWildcard();
    cmdArgs.Append(new SemanticResultKey("colorStringList", colorChoice));

    GrammarBuilder cmds = GrammarBuilder.Add(cmdIntro,
                                             new GrammarBuilder(new SemanticResultKey("Cmd Args", cmdArgs)));
    grammar = new Grammar(cmds);
    grammar.Name = "Tree [Set,change,alter] [foreground,background] * color";
    return grammar;
}

See Also

Reference

SemanticResultValue Class
SemanticResultValue Members
SemanticResultValue Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticResultValue Methods

[image] [image]

SemanticResultValue Methods
SemanticResultValue Class See Also Send Feedback

The SemanticResultValue type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToGrammarBuilder | Returns an instance of GrammarBuilder constructed from the current SemanticResultValue instance.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SemanticResultValue Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ToGrammarBuilder Method

[image]

SemanticResultValue..::..ToGrammarBuilder Method
SemanticResultValue Class Example See Also Send Feedback

Returns an instance of GrammarBuilder constructed from the current SemanticResultValue instance.

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

Syntax

Visual Basic (Declaration)
Public Function ToGrammarBuilder As GrammarBuilder
Visual Basic (Usage)
Dim instance As SemanticResultValue
Dim returnValue As GrammarBuilder

returnValue = instance.ToGrammarBuilder()
C#
public GrammarBuilder ToGrammarBuilder()

Return Value

Type: Microsoft.Speech.Recognition..::..GrammarBuilder

Returns an instance of GrammarBuilder constructed from the current SemanticResultValue instance.

Remarks

The use of ToGrammarBuilder is equivalent to using the GrammarBuilder constructor which takes SemanticResultValue as an argument (GrammarBuilder(SemanticResultValue)).

Examples

The example below creates Grammar objects that support commands which change background color.

A Choices object (colorChoice) containing the list of options for background colors is filled using the Add(array<GrammarBuilder>[]()[][]) method with instances of GrammarBuilder, which had been obtained through the ToGrammarBuilder()()()() method on the SemanticResultValue objects that were created from color strings.

A GrammarBuilder is then obtained by calling ToGrammarBuilder()()()() on an instance of SemanticResultKey, which will be used to key the semantic choices in the colorChoice instance.

Copy image Copy Code
private Grammar CreateGrammarBuilderRGBSemantics() {
    //Create a set of choices, each  a lookup from a color name to rgb
    //Choices constructors do not take SematicResultValue, so cast SematicResultValue to GramarBuilder
    Choices colorChoice = new Choices();
    foreach (string colorName in System.Enum.GetNames(typeof(KnownColor))) {
        SemanticResultValue colorValue=new SemanticResultValue(colorName, Color.FromName(colorName).ToArgb());
        colorChoice.Add(colorValue.ToGrammarBuilder());
        //Uses implicit conversion of SemanticResultValue to GrammarBuilder
    }
    SemanticResultKey choiceKey = new SemanticResultKey("rgb", colorChoice);
    GrammarBuilder choiceBuilder = choiceKey.ToGrammarBuilder();

    //Create two intermediate grammars with introductory phrase and the color choice
    GrammarBuilder makeBackgroundBuilder = "Make background";
    makeBackgroundBuilder.Append(choiceBuilder);

    GrammarBuilder configureBackgroundBuilder = new GrammarBuilder("Configure background as");
    configureBackgroundBuilder.Append((new SemanticResultKey("rgb", colorChoice)).ToGrammarBuilder());

    //Create the final grammar, which recognizes either intermediate grammar
    Grammar grammar = new Grammar(new Choices(makeBackgroundBuilder, configureBackgroundBuilder));
    grammar.Name = "Make Background /Configure background as";

    return grammar;
}

See Also

Reference

SemanticResultValue Class
SemanticResultValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticValue Class

[image]

SemanticValue Class
Members Example See Also Send Feedback

Represents the semantic organization of a recognized phrase.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..SemanticValue

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class SemanticValue _
    Implements IDictionary(Of String, SemanticValue),  _
    ICollection(Of KeyValuePair(Of String, SemanticValue)), IEnumerable(Of KeyValuePair(Of String, SemanticValue)),  _
    IEnumerable
Visual Basic (Usage)
Dim instance As SemanticValue
C#
[SerializableAttribute]
public sealed class SemanticValue : IDictionary<string, SemanticValue>,
    ICollection<KeyValuePair<string, SemanticValue>>, IEnumerable<KeyValuePair<string, SemanticValue>>,
    IEnumerable

Remarks

SemanticValue is the primary object that implements the semantic technology in the Microsoft Speech Platform SDK 11. Semantic interpretation allows grammars to define rules for use by a recognition engine to correctly interpret audio input. Semantic interpretation also enables recognition engines to organize their results so that they can be more easily processed, rather than returning only recognized words and sequences of words.

For example, the recognition engine output "Change background to red" would have to be parsed and interpreted by an application before it could be acted upon. A Grammar object can specify a semantic interpretation to make processing clearer by specifying that the phrase has two semantic substructures, one for selecting background or foreground (represented by the text "background"), and the other for selecting color (represented by the text "red").

The Speech Platform SDK 11 represents the semantics of a recognition operation in a tree of SemanticValue objects.

Each SemanticValue instance includes the following:

  • An Object, accessed by means of the Value property, used to key the instance of the SemanticValue.

  • A measure of the accuracy of semantic parsing, returned by the Confidence property.

  • A collection of name/value pairs ([T:System.Collections.Generic.KeyValuePair<TKey,TValue>]) of child objects, which are also SemanticValue instances. Child nodes are accessible through the SemanticValue implementation of [T:System.Collections.Generic.IDictionary(TKey,TValue)] using a string lookup key and a SemanticValue instance, as in the following example.

    C# Copy image Copy Code
    foreach (KeyValuePair<String, SemanticValue> child in semantics)
{
  Utils.CreateSemanticsTreeNodes(semanticsNode.Nodes, child.Value, child.Key);
}

Recognition engines based on Microsoft.Speech provide valid instances of SemanticValue for all output from recognition, even for phrases with no explicit semantic structure.

The SemanticValue instance for a phrase is obtained using the Semantics property on the RecognizedPhrase object (or objects that inherit from it, such as RecognitionResult).

SemanticValue objects obtained for recognized phrases without semantic structure are characterized by:

  • The lack of children (Count is 0).

  • The Value property is nullNothingnullptrunita null reference (Nothing in Visual Basic).

  • An artificial semantic confidence level of 1.0 (returned by Confidence).

Typically, applications create SemanticValue instances indirectly, adding them to Grammar objects by using SemanticResultValue and SemanticResultKey instances, in conjunction with Choices and GrammarBuilder objects.

Direct construction of a SemanticValue instance is useful during the creation of strongly-typed grammars.

SemanticValue implements the [T:System#Collections#Generic#IDictionary<TKey,TValue>], [T:System#Collections#Generic#ICollection(T)], and [T:System.Collections.Generic.IEnumerable<T>] interfaces.

Examples

The example below shows a handler for a SpeechRecognized event designed to handle commands to change foreground and background color.

Cases where phrases are recognized, but have no semantic structure, are identified by the handler by having Count of zero and a Value of nullNothingnullptrunita null reference (Nothing in Visual Basic). This recognition output is then processed directly from the parsing the raw text.

In other cases, the handler obtains specific information about whether the command is to set the foreground or background color, and the RGB of official name of a color setting based on keys, or indicates that no valid key was found.

Copy image Copy Code
newGrammar.SpeechRecognized +=
    delegate(object sender, SpeechRecognizedEventArgs eventArgs) {
        // Retrieve the value of the semantic property.
        bool changeBackGround = true;
        string errorString = "";
        SemanticValue semantics = eventArgs.Result.Semantics;

        Color newColor = Color.Empty;

        try {
            if (semantics.Count == 0 && semantics.Value==null){

                //This signature of recognition by grammar with no semantic
                ////We have to parse the string. hope last word is color, search for background or forground in input
                if (eventArgs.Result.Text.Contains("foreground")) {
                    changeBackGround = false;
                }
                string cName = eventArgs.Result.Words[eventArgs.Result.Words.Count - 1].Text;
                newColor = Color.FromName(cName);

            }else if (semantics.ContainsKey("colorStringList") ^ semantics.ContainsKey("colorRGBValueList")) {
                //Check background vs foreground

                if (semantics.ContainsKey("applyChgToBackground")) {
                    changeBackGround = semantics["applyChgToBackground"].Value is bool;
                }

                //Get color value
                if (semantics.ContainsKey("colorStringList")) {
                    newColor = Color.FromName((string)semantics["colorStringList"].Value);
                }
                if (semantics.ContainsKey("colorRGBValueList")) {
                    newColor = System.Drawing.Color.FromArgb((int)semantics["colorRGBValueList"].Value);
                }
            } else {
                //we have a semantics that does not contain the keys we support, throw an exception.
                throw(new Exception("Unsupported semantics keys found."));
            }

        } catch (Exception exp) {
            MessageBox.Show(String.Format("Unable to process color semantics.:\n{0}\n", exp.Message));
            return;
        }
        //Change colors, either foreground or background.
        if (changeBackGround) {
            BackColor = newColor;
            float Bright = BackColor.GetBrightness();
            float Hue = BackColor.GetHue();
            float Sat = BackColor.GetSaturation();
            //Make sure the text is readable regardless of background.
            if (BackColor.GetBrightness() <= .50) {
                ForeColor = Color.White;
            } else {
                ForeColor = Color.Black;
            }
        } else {
            ForeColor = newColor;
            float Bright = ForeColor.GetBrightness();
            float Hue = ForeColor.GetHue();
            float Sat = ForeColor.GetSaturation();
            //Make sure the text is readable regardless of Foreground.
            if (ForeColor.GetBrightness() <= .50) {
                BackColor = Color.White;
            } else {
                BackColor = Color.Black;
            }
        }
        Return;
    };

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SemanticValue Members
Microsoft.Speech.Recognition Namespace
SemanticResultValue
SemanticResultKey
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticValue Members

[image] [image]

SemanticValue Members
SemanticValue Class Constructors Methods Properties Explicit Interface Implementations See Also Send Feedback

Represents the semantic organization of a recognized phrase.

The SemanticValue type exposes the following members.

Constructors

 | Name | Description
Public method | SemanticValue(Object) | Initializes a new instance of the SemanticValue class and specifies a semantic value.
Public method | SemanticValue(String, Object, Single) | Initializes a new instance of the SemanticValue class and specifies a semantic value, a key name, and a confidence level.
Top

Properties

 | Name | Description
Public property | Confidence | Returns a relative measure of the certainty as to the correctness of the semantic parsing that returned the current instance of SemanticValue.
Public property | Count | Returns the number of child SemanticValue objects under the current SemanticValue instance.
Public property | Item | Returns child SemanticValue instances that belong to the current SemanticValue.
Public property | Value | Gets the information contained in the current SemanticValue.
Top

Methods

 | Name | Description
Public method | Contains | Indicates whether the current SemanticValue instance collection contains a specific key and specific instance of SemanticValue expressed as a key value pair.
Public method | ContainsKey | Indicates whether the current SemanticValue instance collection contains a child SemanticValue instance with a given key string.
Public method | Equals | (Overrides Object..::..Equals(Object).)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Overrides Object..::..GetHashCode()()()().)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

Explicit Interface Implementations

 | Name | Description
Explicit interface implemetation | ICollection<(Of <<'(KeyValuePair<(Of <<'(String, SemanticValue>)>>)>)>>)..::..Add | Adds the specified key and SemanticValue to the collection.
Explicit interface implemetation | IDictionary<(Of <<'(String, SemanticValue>)>>)..::..Add | Adds the specified key and SemanticValue to the dictionary.
Explicit interface implemetation | ICollection<(Of <<'(KeyValuePair<(Of <<'(String, SemanticValue>)>>)>)>>)..::..Clear | Removes all key/value pairs from the collection.
Explicit interface implemetation | ICollection<(Of <<'(KeyValuePair<(Of <<'(String, SemanticValue>)>>)>)>>)..::..CopyTo | Copies a key/value pair to a specific location in a targeted array.
Explicit interface implemetation | IEnumerable<(Of <<'(KeyValuePair<(Of <<'(String, SemanticValue>)>>)>)>>)..::..GetEnumerator | Returns an enumerator that iterates through a collection.
Explicit interface implemetation | IEnumerable..::..GetEnumerator | Returns an enumerator that iterates through a collection.
Explicit interface implemetation | ICollection<(Of <<'(KeyValuePair<(Of <<'(String, SemanticValue>)>>)>)>>)..::..IsReadOnly | Gets a value that indicates whether the collection is read-only.
Explicit interface implemetation | IDictionary<(Of <<'(String, SemanticValue>)>>)..::..Keys | Gets a collection that contains the keys from a dictionary of key/value pairs.
Explicit interface implemetation | ICollection<(Of <<'(KeyValuePair<(Of <<'(String, SemanticValue>)>>)>)>>)..::..Remove | Removes the specified key and SemanticValue from the collection.
Explicit interface implemetation | IDictionary<(Of <<'(String, SemanticValue>)>>)..::..Remove | Removes the specified key and SemanticValue from the dictionary.
Explicit interface implemetation | IDictionary<(Of <<'(String, SemanticValue>)>>)..::..TryGetValue | Gets the SemanticValue associated with the specified key.
Explicit interface implemetation | IDictionary<(Of <<'(String, SemanticValue>)>>)..::..Values | Gets a collection that contains the values from a dictionary of key/value pairs.
Top

See Also

Reference

SemanticValue Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticValue Constructor

[image] [image]

SemanticValue Constructor
SemanticValue Class See Also Send Feedback

Initializes a new instance of the SemanticValue class.

Overload List

 | Name | Description
Public method | SemanticValue(Object) | Initializes a new instance of the SemanticValue class and specifies a semantic value.
Public method | SemanticValue(String, Object, Single) | Initializes a new instance of the SemanticValue class and specifies a semantic value, a key name, and a confidence level.
Top

Remarks

Typically, you will not create SemanticValue objects explicitly, except to support the building of strongly-typed grammars.

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticValue Constructor (Object)

[image]

SemanticValue Constructor (Object)
SemanticValue Class See Also Send Feedback

Initializes a new instance of the SemanticValue class and specifies a semantic value.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    value As Object _
)
Visual Basic (Usage)
Dim value As Object

Dim instance As New SemanticValue(value)
C#
public SemanticValue(
    Object value
)

Parameters

value
Type: System..::..Object

The information to be stored in the SemanticValue object.

Remarks

There are no restrictions on the type of value to be stored.

An application can retrieve value by using the Value property on a SemanticValue instance.

The value of the Confidence property for the SemanticValue instance will be set to -1.

A SemanticValue constructed with this method cannot be referenced by key name.

See Also

Reference

SemanticValue Class
SemanticValue Members
SemanticValue Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticValue Constructor (String, Object, Single)

[image]

SemanticValue Constructor (String, Object, Single)
SemanticValue Class See Also Send Feedback

Initializes a new instance of the SemanticValue class and specifies a semantic value, a key name, and a confidence level.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    keyName As String, _
    value As Object, _
    confidence As Single _
)
Visual Basic (Usage)
Dim keyName As String
Dim value As Object
Dim confidence As Single

Dim instance As New SemanticValue(keyName, _
    value, confidence)
C#
public SemanticValue(
    string keyName,
    Object value,
    float confidence
)

Parameters

keyName
Type: System..::..String

A key that can be used to reference this SemanticValue instance.

value
Type: System..::..Object

An object containing information to be stored in the SemanticValue object.

confidence
Type: System..::..Single

A float containing an estimate of the certainty of semantic analysis.

Remarks

There are no restrictions on the type of value to be stored.

An application can retrieve value by using the Value property on a SemanticValue instance.

The confidence parameter (returned by the Confidence property on a SemanticValue instance), should be between 0.0 and 1.0.

See Also

Reference

SemanticValue Class
SemanticValue Members
SemanticValue Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticValue Methods

[image] [image]

SemanticValue Methods
SemanticValue Class See Also Send Feedback

The SemanticValue type exposes the following members.

Methods

 | Name | Description
Public method | Contains | Indicates whether the current SemanticValue instance collection contains a specific key and specific instance of SemanticValue expressed as a key value pair.
Public method | ContainsKey | Indicates whether the current SemanticValue instance collection contains a child SemanticValue instance with a given key string.
Public method | Equals | (Overrides Object..::..Equals(Object).)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Overrides Object..::..GetHashCode()()()().)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

Explicit Interface Implementations

 | Name | Description
Explicit interface implemetation | ICollection<(Of <<'(KeyValuePair<(Of <<'(String, SemanticValue>)>>)>)>>)..::..Add | Adds the specified key and SemanticValue to the collection.
Explicit interface implemetation | IDictionary<(Of <<'(String, SemanticValue>)>>)..::..Add | Adds the specified key and SemanticValue to the dictionary.
Explicit interface implemetation | ICollection<(Of <<'(KeyValuePair<(Of <<'(String, SemanticValue>)>>)>)>>)..::..Clear | Removes all key/value pairs from the collection.
Explicit interface implemetation | ICollection<(Of <<'(KeyValuePair<(Of <<'(String, SemanticValue>)>>)>)>>)..::..CopyTo | Copies a key/value pair to a specific location in a targeted array.
Explicit interface implemetation | IEnumerable<(Of <<'(KeyValuePair<(Of <<'(String, SemanticValue>)>>)>)>>)..::..GetEnumerator | Returns an enumerator that iterates through a collection.
Explicit interface implemetation | IEnumerable..::..GetEnumerator | Returns an enumerator that iterates through a collection.
Explicit interface implemetation | ICollection<(Of <<'(KeyValuePair<(Of <<'(String, SemanticValue>)>>)>)>>)..::..Remove | Removes the specified key and SemanticValue from the collection.
Explicit interface implemetation | IDictionary<(Of <<'(String, SemanticValue>)>>)..::..Remove | Removes the specified key and SemanticValue from the dictionary.
Explicit interface implemetation | IDictionary<(Of <<'(String, SemanticValue>)>>)..::..TryGetValue | Gets the SemanticValue associated with the specified key.
Top

See Also

Reference

SemanticValue Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ICollection(KeyValuePair(String, SemanticValue)).Add Method

[image]

SemanticValue..::..ICollection<(Of <(<'KeyValuePair<(Of <(<'String, SemanticValue>)>)>>)>)>..::..Add Method
SemanticValue Class See Also Send Feedback

Adds the specified key and SemanticValue to the collection.

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

Syntax

Visual Basic (Declaration)
Private Sub Add ( _
    key As KeyValuePair(Of String, SemanticValue) _
) Implements ICollection(Of KeyValuePair(Of String, SemanticValue)).Add
Visual Basic (Usage)
Dim instance As SemanticValue
Dim key As KeyValuePair(Of String, SemanticValue)

CType(instance, ICollection(Of KeyValuePair(Of String, SemanticValue))).Add(key)
C#
void ICollection<KeyValuePair<string, SemanticValue>>.Add(
    KeyValuePair<string, SemanticValue> key
)

Parameters

key
Type: System.Collections.Generic..::..KeyValuePair <(Of <(<' String, SemanticValue >)>)>

A key for a SemanticValue.

Implements

ICollection<(Of <(<'T>)>)>..::..Add(T)

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


IDictionary(String, SemanticValue).Add Method

[image]

SemanticValue..::..IDictionary<(Of <(<'String, SemanticValue>)>)>..::..Add Method
SemanticValue Class See Also Send Feedback

Adds the specified key and SemanticValue to the dictionary.

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

Syntax

Visual Basic (Declaration)
Private Sub Add ( _
    key As String, _
    value As SemanticValue _
) Implements IDictionary(Of String, SemanticValue).Add
Visual Basic (Usage)
Dim instance As SemanticValue
Dim key As String
Dim value As SemanticValue

CType(instance, IDictionary(Of String, SemanticValue)).Add(key, _
    value)
C#
void IDictionary<string, SemanticValue>.Add(
    string key,
    SemanticValue value
)

Parameters

key
Type: System..::..String

A key for a SemanticValue.

value
Type: Microsoft.Speech.Recognition..::..SemanticValue

The SemanticValue to add.

Implements

IDictionary<(Of <(<'TKey, TValue>)>)>..::..Add(TKey, TValue)

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ICollection(KeyValuePair(String, SemanticValue)).Clear Method

[image]

SemanticValue..::..ICollection<(Of <(<'KeyValuePair<(Of <(<'String, SemanticValue>)>)>>)>)>..::..Clear Method
SemanticValue Class See Also Send Feedback

Removes all key/value pairs from the collection.

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

Syntax

Visual Basic (Declaration)
Private Sub Clear Implements ICollection(Of KeyValuePair(Of String, SemanticValue)).Clear
Visual Basic (Usage)
Dim instance As SemanticValue

CType(instance, ICollection(Of KeyValuePair(Of String, SemanticValue))).Clear()
C#
void ICollection<KeyValuePair<string, SemanticValue>>.Clear()

Implements

ICollection<(Of <(<'T>)>)>..::..Clear()()()()

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ICollection(KeyValuePair(String, SemanticValue)).CopyTo Method

[image]

SemanticValue..::..ICollection<(Of <(<'KeyValuePair<(Of <(<'String, SemanticValue>)>)>>)>)>..::..CopyTo Method
SemanticValue Class See Also Send Feedback

Copies a key/value pair to a specific location in a targeted array.

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

Syntax

Visual Basic (Declaration)
Private Sub CopyTo ( _
    array As KeyValuePair(Of String, SemanticValue)(), _
    index As Integer _
) Implements ICollection(Of KeyValuePair(Of String, SemanticValue)).CopyTo
Visual Basic (Usage)
Dim instance As SemanticValue
Dim array As KeyValuePair(Of String, SemanticValue)()
Dim index As Integer

CType(instance, ICollection(Of KeyValuePair(Of String, SemanticValue))).CopyTo(array, _
    index)
C#
void ICollection<KeyValuePair<string, SemanticValue>>.CopyTo(
    KeyValuePair<string, SemanticValue>[] array,
    int index
)

Parameters

array
Type: array< System.Collections.Generic..::..KeyValuePair <(Of <(<' String, SemanticValue >)>)>>[]()[][]

The array of key/value pairs that is the target of the operation.

index
Type: System..::..Int32

An integer that specifies the location in the array to which the key/value pair will be copied.

Implements

ICollection<(Of <(<'T>)>)>..::..CopyTo(array<T>[]()[][], Int32)

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


IEnumerable(KeyValuePair(String, SemanticValue)).GetEnumerator Method

[image]

SemanticValue..::..IEnumerable<(Of <(<'KeyValuePair<(Of <(<'String, SemanticValue>)>)>>)>)>..::..GetEnumerator Method
SemanticValue Class See Also Send Feedback

Returns an enumerator that iterates through a collection.

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

Syntax

Visual Basic (Declaration)
Private Function GetEnumerator As IEnumerator(Of KeyValuePair(Of String, SemanticValue))
    Implements IEnumerable(Of KeyValuePair(Of String, SemanticValue)).GetEnumerator
Visual Basic (Usage)
Dim instance As SemanticValue
Dim returnValue As IEnumerator(Of KeyValuePair(Of String, SemanticValue))

returnValue = CType(instance, IEnumerable(Of KeyValuePair(Of String, SemanticValue))).GetEnumerator()
C#
IEnumerator<KeyValuePair<string, SemanticValue>> IEnumerable<KeyValuePair<string, SemanticValue>>.GetEnumerator()

Return Value

Type: System.Collections.Generic..::..IEnumerator <(Of <(<' KeyValuePair <(Of <(<' String, SemanticValue >)>)>>)>)>

Returns an enumerator that iterates through a collection.

Implements

IEnumerable<(Of <(<'T>)>)>..::..GetEnumerator()()()()

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


IEnumerable.GetEnumerator Method

[image]

SemanticValue..::..IEnumerable..::..GetEnumerator Method
SemanticValue Class See Also Send Feedback

Returns an enumerator that iterates through a collection.

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

Syntax

Visual Basic (Declaration)
Private Function GetEnumerator As IEnumerator
    Implements IEnumerable.GetEnumerator
Visual Basic (Usage)
Dim instance As SemanticValue
Dim returnValue As IEnumerator

returnValue = CType(instance, IEnumerable).GetEnumerator()
C#
IEnumerator IEnumerable.GetEnumerator()

Return Value

Type: System.Collections..::..IEnumerator

Returns an enumerator that iterates through a collection.

Implements

IEnumerable..::..GetEnumerator()()()()

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ICollection(KeyValuePair(String, SemanticValue)).Remove Method

[image]

SemanticValue..::..ICollection<(Of <(<'KeyValuePair<(Of <(<'String, SemanticValue>)>)>>)>)>..::..Remove Method
SemanticValue Class See Also Send Feedback

Removes the specified key and SemanticValue from the collection.

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

Syntax

Visual Basic (Declaration)
Private Function Remove ( _
    key As KeyValuePair(Of String, SemanticValue) _
) As Boolean Implements ICollection(Of KeyValuePair(Of String, SemanticValue)).Remove
Visual Basic (Usage)
Dim instance As SemanticValue
Dim key As KeyValuePair(Of String, SemanticValue)
Dim returnValue As Boolean

returnValue = CType(instance, ICollection(Of KeyValuePair(Of String, SemanticValue))).Remove(key)
C#
bool ICollection<KeyValuePair<string, SemanticValue>>.Remove(
    KeyValuePair<string, SemanticValue> key
)

Parameters

key
Type: System.Collections.Generic..::..KeyValuePair <(Of <(<' String, SemanticValue >)>)>

A key for a SemanticValue.

Return Value

Type: System..::..Boolean

Returns true if the key/value pair was successfully removed from the collection; otherwise the method returns false. This method also returns false if the key/value pair is not found in the collection.

Implements

ICollection<(Of <(<'T>)>)>..::..Remove(T)

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


IDictionary(String, SemanticValue).Remove Method

[image]

SemanticValue..::..IDictionary<(Of <(<'String, SemanticValue>)>)>..::..Remove Method
SemanticValue Class See Also Send Feedback

Removes the specified key and SemanticValue from the dictionary.

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

Syntax

Visual Basic (Declaration)
Private Function Remove ( _
    key As String _
) As Boolean Implements IDictionary(Of String, SemanticValue).Remove
Visual Basic (Usage)
Dim instance As SemanticValue
Dim key As String
Dim returnValue As Boolean

returnValue = CType(instance, IDictionary(Of String, SemanticValue)).Remove(key)
C#
bool IDictionary<string, SemanticValue>.Remove(
    string key
)

Parameters

key
Type: System..::..String

A key for a SemanticValue.

Return Value

Type: System..::..Boolean

Returns true if the key/value pair was successfully removed from the dictionary; otherwise the method returns false. This method also returns false if the key/value pair is not found in the dictionary.

Implements

IDictionary<(Of <(<'TKey, TValue>)>)>..::..Remove(TKey)

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


IDictionary(String, SemanticValue).TryGetValue Method

[image]

SemanticValue..::..IDictionary<(Of <(<'String, SemanticValue>)>)>..::..TryGetValue Method
SemanticValue Class See Also Send Feedback

Gets the SemanticValue associated with the specified key.

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

Syntax

Visual Basic (Declaration)
Private Function TryGetValue ( _
    key As String, _
    <OutAttribute> ByRef value As SemanticValue _
) As Boolean Implements IDictionary(Of String, SemanticValue).TryGetValue
Visual Basic (Usage)
Dim instance As SemanticValue
Dim key As String
Dim value As SemanticValue
Dim returnValue As Boolean

returnValue = CType(instance, IDictionary(Of String, SemanticValue)).TryGetValue(key, _
    value)
C#
bool IDictionary<string, SemanticValue>.TryGetValue(
    string key,
    out SemanticValue value
)

Parameters

key
Type: System..::..String

A key for a SemanticValue.

value
Type: Microsoft.Speech.Recognition..::..SemanticValue %

The SemanticValue to get.

Return Value

Type: System..::..Boolean

Returns true if the dictionary contains a key/value pair with the specified key; otherwise the method returns false.

Implements

IDictionary<(Of <(<'TKey, TValue>)>)>..::..TryGetValue(TKey, TValue%)

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Contains Method

[image]

SemanticValue..::..Contains Method
SemanticValue Class See Also Send Feedback

Indicates whether the current SemanticValue instance collection contains a specific key and specific instance of SemanticValue expressed as a key value pair.

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

Syntax

Visual Basic (Declaration)
Public Function Contains ( _
    item As KeyValuePair(Of String, SemanticValue) _
) As Boolean
Visual Basic (Usage)
Dim instance As SemanticValue
Dim item As KeyValuePair(Of String, SemanticValue)
Dim returnValue As Boolean

returnValue = instance.Contains(item)
C#
public bool Contains(
    KeyValuePair<string, SemanticValue> item
)

Parameters

item
Type: System.Collections.Generic..::..KeyValuePair <(Of <(<' String, SemanticValue >)>)>

An instance of SemanticValue instantiated for given value of a key string and a SemanticValue instance.

Return Value

Type: System..::..Boolean

Returns a bool which is true if the current SemanticValue contains an instance of KeyValuePare<String,SemanticValue> for a specified value of the key string and the SemanticValue. Otherwise, false is returned.

Implements

ICollection<(Of <(<'T>)>)>..::..Contains(T)

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ContainsKey Method

[image]

SemanticValue..::..ContainsKey Method
SemanticValue Class Example See Also Send Feedback

Indicates whether the current SemanticValue instance collection contains a child SemanticValue instance with a given key string.

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

Syntax

Visual Basic (Declaration)
Public Function ContainsKey ( _
    key As String _
) As Boolean
Visual Basic (Usage)
Dim instance As SemanticValue
Dim key As String
Dim returnValue As Boolean

returnValue = instance.ContainsKey(key)
C#
public bool ContainsKey(
    string key
)

Parameters

key
Type: System..::..String

String containing the key string used to identify a child instance of SemanticValue under the current SemanticValue.

Return Value

Type: System..::..Boolean

Returns a bool, true if a child instance SemanticValue tagged with the string key is found, false if not.

Implements

IDictionary<(Of <(<'TKey, TValue>)>)>..::..ContainsKey(TKey)

Remarks

Because accessing data by key value, for instance semantic["myKey"].Value, can only be checked at run time, and generates an exception, it is recommended that before using Item with a given instance of SemanticValue, the object should be queried with ContainsKey.

Examples

The example below shows a handler for a SpeechRecognized event designed to handle commands to change foreground and background color.

After dealing with the case of phrase that are recognized, but have no semantic structure, the handler checks for the presence of appropriate keys using ContainsKey (applyChgToBackground, colorRGBValueList, or colorStringList) and then processes the semantically organized data.

The use of ContainsKey is highlighted below.

Copy image Copy Code
newGrammar.SpeechRecognized +=
    delegate(object sender, SpeechRecognizedEventArgs eventArgs) {
        // Retrieve the value of the semantic property.
        bool changeBackGround = true;
        string errorString = "";
        SemanticValue semantics = eventArgs.Result.Semantics;

        Color newColor = Color.Empty;

        try {
            if (semantics.Count == 0 && semantics.Value==null){

                //This signature of recognition by grammar with no semantic
                ////We have to parse the string. hope last word is color, search for background or forground in input
                if (eventArgs.Result.Text.Contains("foreground")) {
                    changeBackGround = false;
                }
                string cName = eventArgs.Result.Words[eventArgs.Result.Words.Count - 1].Text;
                newColor = Color.FromName(cName);

            }else if (semantics.ContainsKey("colorStringList") ^ semantics.ContainsKey("colorRGBValueList")) {
                //Check background vs foreground

                if (semantics.ContainsKey("applyChgToBackground")) {
                    changeBackGround = semantics["applyChgToBackground"].Value is bool;
                }

                //Get color value
                if (semantics.ContainsKey("colorStringList")) {
                    newColor = Color.FromName((string)semantics["colorStringList"].Value);
                }
                if (semantics.ContainsKey("colorRGBValueList")) {
                    newColor = System.Drawing.Color.FromArgb((int)semantics["colorRGBValueList"].Value);
                } // end featured code
            } else {
                //we have a semantics that does not contain the keys we support, throw an exception.
                throw(new Exception("Unsupported semantics keys found."));
            }

        } catch (Exception exp) {
            MessageBox.Show(String.Format("Unable to process color semantics.:\n{0}\n", exp.Message));
            return;
        }
        //Change colors, either foreground or background.
        if (changeBackGround) {
            BackColor = newColor;
            float Bright = BackColor.GetBrightness();
            float Hue = BackColor.GetHue();
            float Sat = BackColor.GetSaturation();
            //Make sure the text is readable regardless of background.
            if (BackColor.GetBrightness() <= .50) {
                ForeColor = Color.White;
            } else {
                ForeColor = Color.Black;
            }
        } else {
            ForeColor = newColor;
            float Bright = ForeColor.GetBrightness();
            float Hue = ForeColor.GetHue();
            float Sat = ForeColor.GetSaturation();
            //Make sure the text is readable regardless of Foreground.
            if (ForeColor.GetBrightness() <= .50) {
                BackColor = Color.White;
            } else {
                BackColor = Color.Black;
            }
        }
        Return;

};

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Equals Method

[image]

SemanticValue..::..Equals Method
SemanticValue Class See Also Send Feedback

This member overrides Object..::..Equals(Object).

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

Syntax

Visual Basic (Declaration)
Public Overrides Function Equals ( _
    obj As Object _
) As Boolean
Visual Basic (Usage)
Dim instance As SemanticValue
Dim obj As Object
Dim returnValue As Boolean

returnValue = instance.Equals(obj)
C#
public override bool Equals(
    Object obj
)

Parameters

obj
Type: System..::..Object

Return Value

Type: System..::..Boolean

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetHashCode Method

[image]

SemanticValue..::..GetHashCode Method
SemanticValue Class See Also Send Feedback

This member overrides Object..::..GetHashCode()()()().

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

Syntax

Visual Basic (Declaration)
Public Overrides Function GetHashCode As Integer
Visual Basic (Usage)
Dim instance As SemanticValue
Dim returnValue As Integer

returnValue = instance.GetHashCode()
C#
public override int GetHashCode()

Return Value

Type: System..::..Int32

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticValue Properties

[image] [image]

SemanticValue Properties
SemanticValue Class See Also Send Feedback

The SemanticValue type exposes the following members.

Properties

 | Name | Description
Public property | Confidence | Returns a relative measure of the certainty as to the correctness of the semantic parsing that returned the current instance of SemanticValue.
Public property | Count | Returns the number of child SemanticValue objects under the current SemanticValue instance.
Public property | Item | Returns child SemanticValue instances that belong to the current SemanticValue.
Public property | Value | Gets the information contained in the current SemanticValue.
Top

Explicit Interface Implementations

 | Name | Description
Explicit interface implemetation | ICollection<(Of <<'(KeyValuePair<(Of <<'(String, SemanticValue>)>>)>)>>)..::..IsReadOnly | Gets a value that indicates whether the collection is read-only.
Explicit interface implemetation | IDictionary<(Of <<'(String, SemanticValue>)>>)..::..Keys | Gets a collection that contains the keys from a dictionary of key/value pairs.
Explicit interface implemetation | IDictionary<(Of <<'(String, SemanticValue>)>>)..::..Values | Gets a collection that contains the values from a dictionary of key/value pairs.
Top

See Also

Reference

SemanticValue Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ICollection(KeyValuePair(String, SemanticValue)).IsReadOnly Property

[image]

SemanticValue..::..ICollection<(Of <(<'KeyValuePair<(Of <(<'String, SemanticValue>)>)>>)>)>..::..IsReadOnly Property
SemanticValue Class See Also Send Feedback

Gets a value that indicates whether the collection is read-only.

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

Syntax

Visual Basic (Declaration)
Private ReadOnly Property IsReadOnly As Boolean
    Implements ICollection(Of KeyValuePair(Of String, SemanticValue)).IsReadOnly
    Get
Visual Basic (Usage)
Dim instance As SemanticValue
Dim value As Boolean

value = CType(instance, ICollection(Of KeyValuePair(Of String, SemanticValue))).IsReadOnly
C#
bool ICollection<KeyValuePair<string, SemanticValue>>.IsReadOnly { get; }

Property Value

Type: System..::..Boolean

Returns a value that indicates whether the collection is read-only.

Implements

ICollection<(Of <(<'T>)>)>..::..IsReadOnly

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


IDictionary(String, SemanticValue).Keys Property

[image]

SemanticValue..::..IDictionary<(Of <(<'String, SemanticValue>)>)>..::..Keys Property
SemanticValue Class See Also Send Feedback

Gets a collection that contains the keys from a dictionary of key/value pairs.

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

Syntax

Visual Basic (Declaration)
Private ReadOnly Property Keys As ICollection(Of String)
    Implements IDictionary(Of String, SemanticValue).Keys
    Get
Visual Basic (Usage)
Dim instance As SemanticValue
Dim value As ICollection(Of String)

value = CType(instance, IDictionary(Of String, SemanticValue)).Keys
C#
ICollection<string> IDictionary<string, SemanticValue>.Keys { get; }

Property Value

Type: System.Collections.Generic..::..ICollection <(Of <(<' String >)>)>

Returns a collection that contains the keys from a dictionary of key/value pairs.

Implements

IDictionary<(Of <(<'TKey, TValue>)>)>..::..Keys

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


IDictionary(String, SemanticValue).Values Property

[image]

SemanticValue..::..IDictionary<(Of <(<'String, SemanticValue>)>)>..::..Values Property
SemanticValue Class See Also Send Feedback

Gets a collection that contains the values from a dictionary of key/value pairs.

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

Syntax

Visual Basic (Declaration)
Private ReadOnly Property Values As ICollection(Of SemanticValue)
    Implements IDictionary(Of String, SemanticValue).Values
    Get
Visual Basic (Usage)
Dim instance As SemanticValue
Dim value As ICollection(Of SemanticValue)

value = CType(instance, IDictionary(Of String, SemanticValue)).Values
C#
ICollection<SemanticValue> IDictionary<string, SemanticValue>.Values { get; }

Property Value

Type: System.Collections.Generic..::..ICollection <(Of <(<' SemanticValue >)>)>

Returns a collection that contains the values from a dictionary of key/value pairs.

Implements

IDictionary<(Of <(<'TKey, TValue>)>)>..::..Values

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Confidence Property

[image]

SemanticValue..::..Confidence Property
SemanticValue Class Example See Also Send Feedback

Returns a relative measure of the certainty as to the correctness of the semantic parsing that returned the current instance of SemanticValue.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Confidence As Single
    Get
Visual Basic (Usage)
Dim instance As SemanticValue
Dim value As Single

value = instance.Confidence
C#
public float Confidence { get; }

Property Value

Type: System..::..Single

Returns a float that is a relative measure of the certainty as to the correctness of the semantic parsing that returned the current instance of SemanticValue.

Remarks

The SemanticValue..::..Confidence property, which returns a measure of the correctness of semantic parsing, should not be confused with the RecognizedPhrase..::..Confidence property, which returns a measure of the accuracy of speech recognition.

Examples

The following example is used to recursively traverse and then display information (including confidence) as a TreeNodeCollection, or as the nodes making up the tree structure of the semantics used to recognize a phrase.

Copy image Copy Code
internal static void CreateSemanticsTreeNodes(
        TreeNodeCollection nodes,
        SemanticValue semantics,
        String name)
{
  string semanticsText =
      String.Format("  {0}  (Confidence {1})", name,semantics.Confidence);

  // Format integers as hexadecimal.
  if (semantics.Value == null )
  {
    semanticsText = semanticsText + " = null";
  }
  else if (semantics.Value.GetType() == typeof(int))
  {
    semanticsText = String.Format("{0} = {1:X} ", semanticsText, semantics.Value);
  }
  else
  {
    semanticsText = semanticsText + " = " + semantics.Value.ToString();
  }

  TreeNode semanticsNode = new TreeNode(semanticsText);
  foreach (KeyValuePair<String, SemanticValue> child in semantics)
  {
    CreateSemanticsTreeNodes(semanticsNode.Nodes, child.Value, child.Key);
  }
  nodes.Add(semanticsNode);
}

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Count Property

[image]

SemanticValue..::..Count Property
SemanticValue Class Example See Also Send Feedback

Returns the number of child SemanticValue objects under the current SemanticValue instance.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Count As Integer
    Get
Visual Basic (Usage)
Dim instance As SemanticValue
Dim value As Integer

value = instance.Count
C#
public int Count { get; }

Property Value

Type: System..::..Int32

The number of child SemanticValue objects under the current SemanticValue.

Implements

ICollection<(Of <(<'T>)>)>..::..Count

Remarks

Recognition results which do not make use of semantic parsing always have a Count property of zero, as well as a Value of nullNothingnullptrunita null reference (Nothing in Visual Basic).

Examples

The following example shows a handler for a SpeechRecognized event designed to handle commands to change foreground and background color.

The handler identifies recognized phrases that have no underlying semantic structure by detecting a Count of zero and a Value of nullNothingnullptrunita null reference (Nothing in Visual Basic). This recognition output is then processed directly by parsing the raw text.

In other cases, the handler uses keys to obtain the RGB components of a color name, to determine whether the command will change the foreground or background, or to indicate that no valid key was found.

Copy image Copy Code
newGrammar.SpeechRecognized +=
  delegate(object sender, SpeechRecognizedEventArgs eventArgs)
  {

    // Retrieve the value of the semantic property.
    bool changeBackGround = true;
    string errorString = "";
    SemanticValue semantics = eventArgs.Result.Semantics;

    Color newColor = Color.Empty;

    try
    {
      if (semantics.Count == 0 && semantics.Value==null)
      {
        // Signifies recognition by a grammar with no semantics.
        // Parse the string, assuming that the last word is color,
        //  searching for background or foreground in input.
        if (eventArgs.Result.Text.Contains("foreground"))
        {
          changeBackGround = false;
        }
        string cName = eventArgs.Result.Words[eventArgs.Result.Words.Count - 1].Text;
        newColor = Color.FromName(cName);

      }
      else if (semantics.ContainsKey("colorStringList") ^ semantics.ContainsKey("colorRGBValueList"))
      {

        // Determine whether to change background or foreground.
        if (semantics.ContainsKey("applyChgToBackground"))
        {
          changeBackGround = semantics["applyChgToBackground"].Value is bool;
        }

        // Get the RGB color value.
        if (semantics.ContainsKey("colorStringList"))
        {
          newColor = Color.FromName((string)semantics["colorStringList"].Value);
        }
        if (semantics.ContainsKey("colorRGBValueList"))
        {
          newColor = System.Drawing.Color.FromArgb((int)semantics["colorRGBValueList"].Value);
        }
      }
      else
      {

        // Throw an exception if the semantics do not contain the keys we
        // support.
        throw(new Exception("Unsupported semantics keys found."));
      }
    }

    catch (Exception exp)
    {
      MessageBox.Show(String.Format("Unable to process color semantics.:\n{0}\n", exp.Message));
      return;
    }

    // Change colors, either foreground or background.
    if (changeBackGround)
    {
      BackColor = newColor;
      float Bright = BackColor.GetBrightness();
      float Hue = BackColor.GetHue();
      float Sat = BackColor.GetSaturation();
      // Make sure that text is readable regardless of background.
      if (BackColor.GetBrightness() <= .50)
      {
        ForeColor = Color.White;
      }
      else
      {
        ForeColor = Color.Black;
      }
    }
    else
    {
      ForeColor = newColor;
      float Bright = ForeColor.GetBrightness();
      float Hue = ForeColor.GetHue();
      float Sat = ForeColor.GetSaturation();

      // Make sure that text is readable regardless of Foreground.
      if (ForeColor.GetBrightness() <= .50)
      {
        BackColor = Color.White;
      }
      else
      {
        BackColor = Color.Black;
      }
    }
    return;
  };

};

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Item Property

[image]

SemanticValue..::..Item Property
SemanticValue Class Example See Also Send Feedback

Returns child SemanticValue instances that belong to the current SemanticValue.

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

Syntax

Visual Basic (Declaration)
Public Default Property Item ( _
    key As String _
) As SemanticValue
    Get
    Set
Visual Basic (Usage)
Dim instance As SemanticValue
Dim key As String
Dim value As SemanticValue

value = instance(key)

instance(key) = value
C#
public SemanticValue this[
    string key
] { get; set; }

Parameters

key
Type: System..::..String

A key for a KeyValuePair<String, SemanticValue> contained in the current instance of SemanticValue.

Property Value

Type: Microsoft.Speech.Recognition..::..SemanticValue

Returns a child of the current SemanticValue that can be indexed as part of a key value pair: KeyValuePair<String,SemanticValue>.

Implements

IDictionary<(Of <(<'TKey, TValue>)>)>..::..Item[([( TKey])])

Exceptions

Exception | Condition
KeyNotFoundException | Thrown if no child member of the current instance of SemanticValue has the key matching the key parameter.
InvalidOperationException | Thrown if code attempts to change the SemanticValue at a given index.

Remarks

The Item is read-only and generates exceptions if members are modified.

You can only access data by key value at run-time, not at compile-time, for example to check semantic["myKey"].Value. Specifying a key that is not present generates an exception.

To detect the presence of a given key, use the ContainsKey property on an SemanticValue instance.

Examples

The following example shows a handler for a SpeechRecognized event designed to handle commands to change foreground and background color.

After handling recognized phrases that have no semantic structure, the handler checks for the presence of appropriate keys using ContainsKey (applyChgToBackground, colorRGBValueList, or colorStringList), and then uses the Item property to obtain the nodes with needed information.

The use of Item is highlighted below.

Copy image Copy Code
newGrammar.SpeechRecognized +=
  delegate(object sender, SpeechRecognizedEventArgs eventArgs)
  {

    // Retrieve the value of the semantic property.
    bool changeBackGround = true;
    string errorString = "";
    SemanticValue semantics = eventArgs.Result.Semantics;

    Color newColor = Color.Empty;

    try
    {
      if (semantics.Count == 0 && semantics.Value==null)
      {
        // Signifies recognition by a grammar with no semantics.
        // Parse the string, assuming that the last word is color,
        //  searching for background or foreground in input.
        if (eventArgs.Result.Text.Contains("foreground"))
        {
          changeBackGround = false;
        }
        string cName = eventArgs.Result.Words[eventArgs.Result.Words.Count - 1].Text;
        newColor = Color.FromName(cName);

      }
      else if (semantics.ContainsKey("colorStringList") ^ semantics.ContainsKey("colorRGBValueList"))
      {

        // Determine whether to change background or foreground.
        if (semantics.ContainsKey("applyChgToBackground"))
        {
          changeBackGround = semantics["applyChgToBackground"].Value is bool;
        }

        // Get the RGB color value.
        if (semantics.ContainsKey("colorStringList"))
        {
          newColor =Color.FromName((string)semantics["colorStringList"].Value);
        }
        if (semantics.ContainsKey("colorRGBValueList"))
        {
          newColor =System.Drawing.Color.FromArgb((int)semantics["colorRGBValueList"].Value);
        }
      }
      else
      {

        // Throw an exception if the semantics do not contain the keys we
        // support.
        throw(new Exception("Unsupported semantic keys found."));
      }
    }

    catch (Exception exp)
    {
      MessageBox.Show(String.Format("Unable to process color semantics.:\n{0}\n", exp.Message));
      return;
    }

    // Change colors, either foreground or background.
    if (changeBackGround)
    {
      BackColor = newColor;
      float Bright = BackColor.GetBrightness();
      float Hue = BackColor.GetHue();
      float Sat = BackColor.GetSaturation();
      // Make sure that text is readable regardless of background.
      if (BackColor.GetBrightness() <= .50)
      {
        ForeColor = Color.White;
      }
      else
      {
        ForeColor = Color.Black;
      }
    }
    else
    {
      ForeColor = newColor;
      float Bright = ForeColor.GetBrightness();
      float Hue = ForeColor.GetHue();
      float Sat = ForeColor.GetSaturation();

      // Make sure that text is readable regardless of the foreground.
      if (ForeColor.GetBrightness() <= .50)
      {
        BackColor = Color.White;
      }
      else
      {
        BackColor = Color.Black;
      }
    }
    return;
  };

};

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Value Property

[image]

SemanticValue..::..Value Property
SemanticValue Class Example See Also Send Feedback

Gets the information contained in the current SemanticValue.

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

Syntax

Visual Basic (Declaration)
Public Property Value As Object
    Get
    Friend Set
Visual Basic (Usage)
Dim instance As SemanticValue
Dim value As Object

value = instance.Value
C#
public Object Value { get; internal set; }

Property Value

Type: System..::..Object

Returns a Object instance containing the information stored in the current SemanticValue instance.

Remarks

Recognition results which do not make use of semantic parsing always have a Value of nullNothingnullptrunita null reference (Nothing in Visual Basic) and a Count property of zero.

Examples

The example below is used to recursively traverse and then display (as a TreeNodeCollection) information, including confidence, or the nodes making up the tree structure of the semantics used to recognize a phrase. The use of Value is highlighted.

Copy image Copy Code
internal static void CreateSemanticsTreeNodes(TreeNodeCollection nodes,
                                              SemanticValue semantics,
                                              String name) {
    string semanticsText = String.Format("  {0} ( Confidence {1})",
                                         name,semantics.Confidence);
       //Put integers as hex
    if (semantics.Value == null ){semanticsText = semanticsText + " = null";}else if (semantics.Value.GetType() == typeof(int)) {semanticsText = String.Format("{0} = {1:X} ", semanticsText, semantics.Value);} else {semanticsText = semanticsText + " = "+ semantics.Value.ToString();}
    TreeNode semanticsNode = new TreeNode(semanticsText);
    foreach (KeyValuePair<String, SemanticValue> child in semantics) {
        CreateSemanticsTreeNodes(semanticsNode.Nodes, child.Value, child.Key);
    }
    nodes.Add(semanticsNode);
    //   }
}

See Also

Reference

SemanticValue Class
SemanticValue Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechDetectedEventArgs Class

[image]

SpeechDetectedEventArgs Class
Members Example See Also Send Feedback

Provides data for the SpeechDetected event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Recognition..::..SpeechDetectedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class SpeechDetectedEventArgs _
    Inherits EventArgs
Visual Basic (Usage)
Dim instance As SpeechDetectedEventArgs
C#
public class SpeechDetectedEventArgs : EventArgs

Remarks

An instance of SpeechDetectedEventArgs is created when the SpeechRecognitionEngine object raises the SpeechDetected event. To obtain the location in the audio stream where the event was raised, access the AudioPosition property in the handler for the event.

SpeechDetected events are generated when a recognition engine can identify audio input as human speech.

SpeechDetectedEventArgs derives from EventArgs.

Examples

In the example below, a handler is created for SpeechDetected events which initializes a display every time speech is detected and displays status information, including audio position.

Copy image Copy Code
_recognizer.SpeechDetected +=
  delegate(object sender, SpeechDetectedEventArgs eventArgs)
  {

    // Clear previous recognition information.
    _audioDeviceStatusLabel.Enabled = true;
    _audioDeviceStatusLabel.Visible = true;
    Utils.DisplayAudioInputFormat(_audioStateLabel, _recognizer);
    Utils.DisplayRecognizerState(_recognizerStateLabel, _recognizer.State);
    Utils.DisplaySpeechDetected(_speechDetectedLabel, eventArgs.AudioPosition);
  };

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SpeechDetectedEventArgs Members
Microsoft.Speech.Recognition Namespace
AudioStateChanged
SpeechDetected
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechDetectedEventArgs Members

[image] [image]

SpeechDetectedEventArgs Members
SpeechDetectedEventArgs Class Methods Properties See Also Send Feedback

Provides data for the SpeechDetected event.

The SpeechDetectedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioPosition | Gets the position in the audio stream where speech was detected.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeechDetectedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechDetectedEventArgs Methods

[image] [image]

SpeechDetectedEventArgs Methods
SpeechDetectedEventArgs Class See Also Send Feedback

The SpeechDetectedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeechDetectedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechDetectedEventArgs Properties

[image] [image]

SpeechDetectedEventArgs Properties
SpeechDetectedEventArgs Class See Also Send Feedback

The SpeechDetectedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioPosition | Gets the position in the audio stream where speech was detected.
Top

See Also

Reference

SpeechDetectedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioPosition Property

[image]

SpeechDetectedEventArgs..::..AudioPosition Property
SpeechDetectedEventArgs Class Example See Also Send Feedback

Gets the position in the audio stream where speech was detected.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioPosition As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As SpeechDetectedEventArgs
Dim value As TimeSpan

value = instance.AudioPosition
C#
public TimeSpan AudioPosition { get; }

Property Value

Type: System..::..TimeSpan

Returns the location of a detected phrase within the speech buffer of a recognition engine.

Examples

In the example below, a handler is created for SpeechDetected events which initializes a display every time speech is detected and displays status information, including audio position.

Copy image Copy Code
_recognizer.SpeechDetected +=
  delegate(object sender, SpeechDetectedEventArgs eventArgs)
  {

    // Clear previous recognition information.
    _audioDeviceStatusLabel.Enabled = true;
    _audioDeviceStatusLabel.Visible = true;
    Utils.DisplayAudioInputFormat(_audioStateLabel, _recognizer);
    Utils.DisplayRecognizerState(_recognizerStateLabel, _recognizer.State);
    Utils.DisplaySpeechDetected(_speechDetectedLabel, eventArgs.AudioPosition);
  };

See Also

Reference

SpeechDetectedEventArgs Class
SpeechDetectedEventArgs Members
Microsoft.Speech.Recognition Namespace
SpeechDetectedEventArgs
AudioStateChanged
SpeechDetected
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechHypothesizedEventArgs Class

[image]

SpeechHypothesizedEventArgs Class
Members Example See Also Send Feedback

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

Provides data for the SpeechHypothesized event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Recognition..::..RecognitionEventArgs
Microsoft.Speech.Recognition..::..SpeechHypothesizedEventArgs

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class SpeechHypothesizedEventArgs _
    Inherits RecognitionEventArgs
Visual Basic (Usage)
Dim instance As SpeechHypothesizedEventArgs
C#
[SerializableAttribute]
public class SpeechHypothesizedEventArgs : RecognitionEventArgs

Remarks

An instance of SpeechHypothesizedEventArgs is created when the SpeechRecognitionEngine object raises the SpeechHypothesized event. To obtain detailed information about a tentatively recognized phrase, access the Result property in the handler for the event.

Numerous SpeechHypothesized events are generated as a recognition engine attempts to identify an input phrase. Typically, handling these events is only useful for debugging.

SpeechHypothesizedEventArgs derives from RecognitionEventArgs.

Examples

In the example below, a delegate is defined to use the instance of SpeechHypothesizedEventArgs passed to the handler for SpeechHypothesized events to display information about a tentatively recognized phrase.

Copy image Copy Code
// Create a handler for the SpeechHypothesized event.
recognizer.SpeechHypothesized += new EventHandler<SpeechHypothesizedEventArgs>(recognizer_SpeechHypothesized);

// Handle the event and display the hypothesized result.
void recognizer_SpeechHypothesized (object sender, SpeechHypothesizedEventArgs e)
  {
    Console.WriteLine("Hypothesized text: " + e.Result.Text);
  }

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SpeechHypothesizedEventArgs Members
Microsoft.Speech.Recognition Namespace
RecognitionEventArgs
Result
SpeechRecognized
SpeechRecognizedEventArgs
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechHypothesizedEventArgs Members

[image] [image]

SpeechHypothesizedEventArgs Members
SpeechHypothesizedEventArgs Class Methods Properties See Also Send Feedback

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

Provides data for the SpeechHypothesized event.

The SpeechHypothesizedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Result | Gets the results of the speech or DTMF recognition operation. (Inherited from RecognitionEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeechHypothesizedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechHypothesizedEventArgs Methods

[image] [image]

SpeechHypothesizedEventArgs Methods
SpeechHypothesizedEventArgs Class See Also Send Feedback

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

The SpeechHypothesizedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeechHypothesizedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechHypothesizedEventArgs Properties

[image] [image]

SpeechHypothesizedEventArgs Properties
SpeechHypothesizedEventArgs Class See Also Send Feedback

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

The SpeechHypothesizedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Result | Gets the results of the speech or DTMF recognition operation. (Inherited from RecognitionEventArgs.)
Top

See Also

Reference

SpeechHypothesizedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionEngine Class

[image]

SpeechRecognitionEngine Class
Members Example See Also Send Feedback

Provides the means to access and manage a speech recognition engine.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition..::..SpeechRecognitionEngine

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

Syntax

Visual Basic (Declaration)
Public Class SpeechRecognitionEngine _
    Implements IDisposable
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
C#
public class SpeechRecognitionEngine : IDisposable

Remarks

You can create an instance of this class for any installed speech recognition engine. To get information about which speech recognition engines are installed, use the static InstalledRecognizers()()()() method. See SpeechRecognitionEngine(CultureInfo) for information about downloading additional speech recognition engines for specific languages.

Applications using SpeechRecognitionEngine can be constructed as clients of a particular recognition engine, as standalone speech recognition applications using an in-process recognition engine, and as servers that provide access to a recognition engine for clients.

Using the functionality provided by the SpeechRecognitionEngine class, you can do the following:

  • Construct an instance of SpeechRecognitionEngine and specify the speech recognition engine to use. See SpeechRecognitionEngine, InstalledRecognizers()()()(), and RecognizerInfo.

  • Configure the input to the speech recognition engine. See SetInputToWaveFile, SetInputToAudioStream, SetInputToNull, SetInputToWaveStream, and SetInputToDefaultAudioDevice.

  • Manage grammars used for speech recognition. See LoadGrammar, UnloadGrammar, UnloadAllGrammars, Grammars, and LoadGrammarCompleted.

  • Set parameters for speech recognition operations. See BabbleTimeout, InitialSilenceTimeout, EndSilenceTimeout, EndSilenceTimeoutAmbiguous, QueryRecognizerSetting, and MaxAlternates.

  • Monitor the input to the speech recognition engine. See AudioStateChanged, AudioSignalProblemOccurred, and AudioLevelUpdated.

  • Create handlers that provide access to the results of speech recognition operations. See SpeechDetected, SpeechHypothesized, SpeechRecognitionRejected, and SpeechRecognized.

  • Manage synchronous and asynchronous recognition operations. See Recognize, RecognizeAsync, RecognizeAsyncStop, RecognizeAsyncCancel, RecognizeCompleted, and RequestRecognizerUpdate()()()().

  • Test the effectiveness of speech recognition grammars using emulated recognition. See EmulateRecognize, EmulateRecognizeAsync, and EmulateRecognizeCompleted.

Note Note

Always call Dispose before you release your last reference to the SpeechRecognitionEngine object. Otherwise, the resources it is using will not be freed until the garbage collector calls the object's Finalize method.

Examples

The following example shows part of a console application that demonstrates basic speech recognition. Because this example uses the Multiple mode of the RecognizeAsync(RecognizeMode) method, it performs recognition until you close the console window or stop debugging.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

      // Create a SpeechRecognitionEngine object for the default recognizer in the en-US locale.
      using (
      SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(
          new System.Globalization.CultureInfo("en-US")))
      {

        // Create a grammar for finding services in different cities.
        Choices services = new Choices(new string[] { "restaurants", "hotels", "gas stations" });
        Choices cities = new Choices(new string[] { "Seattle", "Boston", "Dallas" });

        GrammarBuilder findServices = new GrammarBuilder("Find");
        findServices.Append(services);
        findServices.Append("near");
        findServices.Append(cities);

        // Create a Grammar object from the GrammarBuilder and load it to the recognizer.
        Grammar servicesGrammar = new Grammar(findServices);
        recognizer.LoadGrammarAsync(servicesGrammar);

        // Add a handler for the speech recognized event.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

        // Configure the input to the speech recognizer.
        recognizer.SetInputToDefaultAudioDevice();

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

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

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

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionEngine Members

[image] [image]

SpeechRecognitionEngine Members
SpeechRecognitionEngine Class Constructors Methods Properties Events See Also Send Feedback

Provides the means to access and manage a speech recognition engine.

The SpeechRecognitionEngine type exposes the following members.

Constructors

 | Name | Description
Public method | SpeechRecognitionEngine()()()() | Initializes a new instance of the SpeechRecognitionEngine class using the default speech recognizer for the system.
Public method | SpeechRecognitionEngine(CultureInfo) | Initializes a new instance of the SpeechRecognitionEngine class using the default speech recognizer for a specified locale.
Public method | SpeechRecognitionEngine(String) | Initializes a new instance of the SpeechRecognitionEngine class with a string parameter that specifies the name of the recognizer to use.
Public method | SpeechRecognitionEngine(RecognizerInfo) | Initializes a new instance of the SpeechRecognitionEngine using the information in a RecognizerInfo object to specify the recognizer to use.
Top

Properties

 | Name | Description
Public property | AudioFormat | Gets the format of the audio being received by the SpeechRecognitionEngine.
Public property | AudioLevel | Gets the level of the audio being received by the SpeechRecognitionEngine.
Public property | AudioPosition | Gets the current location in the audio stream being generated by the device that is providing input to the SpeechRecognitionEngine.
Public property | AudioState | Gets the state of the audio being received by the SpeechRecognitionEngine.
Public property | BabbleTimeout | Gets or sets the interval of time that a SpeechRecognitionEngine accepts input containing only background noise before finalizing recognition.
Public property | EndSilenceTimeout | Gets or sets the interval of silence that the SpeechRecognitionEngine will accept at the end of unambiguous input before finalizing a recognition operation.
Public property | EndSilenceTimeoutAmbiguous | Gets or sets the interval of silence that the SpeechRecognitionEngine will accept at the end of ambiguous input before finalizing a recognition operation.
Public property | Grammars | Gets a collection of the Grammar objects that are loaded in this SpeechRecognitionEngine instance.
Public property | InitialSilenceTimeout | Gets or sets the time interval during which a SpeechRecognitionEngine accepts input containing only silence before finalizing recognition.
Public property | MaxAlternates | Gets or sets the maximum number of alternate recognition results that the SpeechRecognitionEngine returns for each recognition operation.
Public property | NormalizerCollection | Gets the normalizer collection.
Public property | RecognizerAudioPosition | Gets the current location of the SpeechRecognitionEngine in the audio input that it is processing.
Public property | RecognizerInfo | Gets information about the current instance of SpeechRecognitionEngine.
Top

Methods

 | Name | Description
Public method | Dispose()()()() | Disposes the SpeechRecognitionEngine object.
Protected method | Dispose(Boolean) | Disposes the SpeechRecognitionEngine object and releases resources used during the session.
Public method | EmulateRecognize(String) | Emulates input of a phrase to the speech recognizer, using text in place of audio for synchronous speech recognition.
Public method | EmulateRecognize(String, EmulateOptions) | Emulates input of a phrase to the speech recognizer, using text in place of audio for synchronous speech recognition, and specifies the type of recognition operation to perform.
Public method | EmulateRecognize(String, CompareOptions) | Emulates audio input to the recognition engine, using text in place of audio for synchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars
Public method | EmulateRecognize(array<RecognizedWordUnit>[]()[][], CompareOptions) | Emulates input of specific words to the speech recognizer, using an array of RecognizedWordUnit objects in place of audio for synchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars.
Public method | EmulateRecognize(String, CompareOptions, EmulateOptions) | Emulates audio input to the recognition engine, using text in place of audio for synchronous speech recognition, specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.
Public method | EmulateRecognize(array<RecognizedWordUnit>[]()[][], CompareOptions, EmulateOptions) | Emulates input of specific words to the speech recognizer, using an array of RecognizedWordUnit objects in place of audio for synchronous speech recognition, specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.
Public method | EmulateRecognizeAsync(String) | Emulates input of a phrase to the speech recognizer, using text in place of audio for asynchronous speech recognition.
Public method | EmulateRecognizeAsync(String, EmulateOptions) | Emulates input of a phrase to the speech recognizer, using text in place of audio for asynchronous speech recognition, and specifies the type of recognition operation to perform.
Public method | EmulateRecognizeAsync(String, CompareOptions) | Emulates input of a phrase to the speech recognizer, using text in place of audio for asynchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars.
Public method | EmulateRecognizeAsync(array<RecognizedWordUnit>[]()[][], CompareOptions) | Emulates input of specific words to the speech recognizer, using text in place of audio for asynchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars.
Public method | EmulateRecognizeAsync(String, CompareOptions, EmulateOptions) | Emulates audio input to the recognition engine, using text in place of audio for asynchronous speech recognition, specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.
Public method | EmulateRecognizeAsync(array<RecognizedWordUnit>[]()[][], CompareOptions, EmulateOptions) | Emulates input of specific words to the speech recognizer, using an array of RecognizedWordUnit objects in place of audio for asynchronous speech recognition, specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
 | InstalledRecognizers | Returns information for all of the installed speech recognizers on the current system.
Public method | LoadGrammar | Synchronously loads a Grammar object.
Public method | LoadGrammarAsync | Asynchronously loads a Grammar object.
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | QueryRecognizerSetting | Returns the values of the current settings for a speech recognition engine managed by a SpeechRecognitionEngine object.
Public method | Recognize()()()() | Performs a synchronous speech recognition operation.
Public method | Recognize(TimeSpan) | Performs a synchronous speech recognition operation with a specified initial silence timeout period.
Public method | RecognizeAsync()()()() | Performs a single, asynchronous speech recognition operation.
Public method | RecognizeAsync(RecognizeMode) | Performs one or more asynchronous speech recognition operations.
Public method | RecognizeAsyncCancel | Terminates asynchronous recognition without waiting for the current recognition operation to complete.
Public method | RecognizeAsyncStop | Stops asynchronous recognition after the current recognition operation completes.
Public method | RequestRecognizerUpdate()()()() | Requests that the recognizer pauses to update its state.
Public method | RequestRecognizerUpdate(Object) | Requests that the recognizer pauses to update its state and provides a user token for the associated event.
Public method | RequestRecognizerUpdate(Object, TimeSpan) | Requests that the recognizer pauses to update its state and provides an offset and a user token for the associated event.
Public method | SetInputToAudioStream | Configures the SpeechRecognitionEngine object to receive input from an audio stream.
Public method | SetInputToDefaultAudioDevice | Configures the SpeechRecognitionEngine object to receive input from the default audio device.
Public method | SetInputToNull | Disables the input to the speech recognizer.
Public method | SetInputToWaveFile | Configures the SpeechRecognitionEngine object to receive input from a Waveform audio format (.wav) file.
Public method | SetInputToWaveStream | Configures the SpeechRecognitionEngine object to receive input from a stream that contains Waveform audio format (.wav) data.
Public method | SimulateRecognize | Simulates recognition of the specified string.
Public method | ToString | (Inherited from Object.)
Public method | UnloadAllGrammars | Unloads all Grammar objects from the recognizer.
Public method | UnloadGrammar | Unloads a specified Grammar object from the SpeechRecognitionEngine instance.
Public method | UpdateRecognizerSetting(String, Int32) | Updates the specified setting for the SpeechRecognitionEngine with the specified integer value.
Public method | UpdateRecognizerSetting(String, String) | Updates the specified setting for the SpeechRecognitionEngine with the specified integer value.
Top

Events

 | Name | Description
Public event | AudioLevelUpdated | Raised when the SpeechRecognitionEngine reports the level of its audio input.
Public event | AudioSignalProblemOccurred | Raised when the SpeechRecognitionEngine detects a problem in the audio signal.
Public event | AudioStateChanged | Raised when the state changes in the audio being received by the SpeechRecognitionEngine.
Public event | EmulateRecognizeCompleted | Raised when the SpeechRecognitionEngine finalizes an asynchronous recognition operation of emulated input.
Public event | LoadGrammarCompleted | Raised when the SpeechRecognitionEngine finishes the asynchronous loading of a Grammar object.
Public event | RecognizeCompleted | Raised when the SpeechRecognitionEngine finalizes an asynchronous recognition operation.
Public event | RecognizerUpdateReached | Raised when a running SpeechRecognitionEngine pauses to accept modifications.
Public event | SpeechDetected | Raised when the SpeechRecognitionEngine detects input that it can identify as speech.
Public event | SpeechHypothesized | Raised when the SpeechRecognitionEngine has recognized a word or words that may be a component of multiple complete phrases in a grammar.
Public event | SpeechRecognitionRejected | Raised when the SpeechRecognitionEngine receives input that does not match any of its loaded and enabled Grammar objects.
Public event | SpeechRecognized | Raised when the SpeechRecognitionEngine receives input that matches any of its loaded and enabled Grammar objects.
Top

See Also

Reference

SpeechRecognitionEngine Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionEngine Constructor

[image] [image]

SpeechRecognitionEngine Constructor
SpeechRecognitionEngine Class See Also Send Feedback

Initializes a new instance of the SpeechRecognitionEngine class.

Overload List

 | Name | Description
Public method | SpeechRecognitionEngine()()()() | Initializes a new instance of the SpeechRecognitionEngine class using the default speech recognizer for the system.
Public method | SpeechRecognitionEngine(CultureInfo) | Initializes a new instance of the SpeechRecognitionEngine class using the default speech recognizer for a specified locale.
Public method | SpeechRecognitionEngine(String) | Initializes a new instance of the SpeechRecognitionEngine class with a string parameter that specifies the name of the recognizer to use.
Public method | SpeechRecognitionEngine(RecognizerInfo) | Initializes a new instance of the SpeechRecognitionEngine using the information in a RecognizerInfo object to specify the recognizer to use.
Top

Remarks

You can construct a SpeechRecognitionEngine instance from any of the following:

  • The default speech recognition engine for the system

  • A specific speech recognition engine that you specify by name

  • The default speech recognition engine for a locale that you specify

  • A specific recognition engine that meets the criteria that you specify in a RecognizerInfo object

Before the speech recognizer can begin recognition, you must load at least one speech recognition grammar and configure the input for the recognizer.

To load a grammar, call the LoadGrammar or LoadGrammarAsync method.

To configure the audio input, use one of the following methods:

  • SetInputToAudioStream

  • SetInputToDefaultAudioDevice

  • SetInputToNull

  • SetInputToWaveFile

  • SetInputToWaveStream

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionEngine Constructor

[image]

SpeechRecognitionEngine Constructor
SpeechRecognitionEngine Class See Also Send Feedback

Initializes a new instance of the SpeechRecognitionEngine class using the default speech recognizer for the system.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New SpeechRecognitionEngine()
C#
public SpeechRecognitionEngine()

Remarks

Before the speech recognizer can begin recognition, you must load at least one speech recognition grammar and configure the input for the recognizer.

To load a grammar, call the LoadGrammar or LoadGrammarAsync method.

To configure the audio input, use one of the following methods:

  • SetInputToAudioStream

  • SetInputToDefaultAudioDevice

  • SetInputToNull

  • SetInputToWaveFile

  • SetInputToWaveStream

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
SpeechRecognitionEngine Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionEngine Constructor (CultureInfo)

[image]

SpeechRecognitionEngine Constructor (CultureInfo)
SpeechRecognitionEngine Class Example See Also Send Feedback

Initializes a new instance of the SpeechRecognitionEngine class using the default speech recognizer for a specified locale.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    culture As CultureInfo _
)
Visual Basic (Usage)
Dim culture As CultureInfo

Dim instance As New SpeechRecognitionEngine(culture)
C#
public SpeechRecognitionEngine(
    CultureInfo culture
)

Parameters

culture
Type: System.Globalization..::..CultureInfo

The locale that the speech recognizer must support.

Remarks

If the system does not support the locale defined by culture, an exception will be generated on construction.

Before the speech recognizer can begin recognition, you must load at least one speech recognition grammar and configure the input for the recognizer.

To load a grammar, call the LoadGrammar or LoadGrammarAsync method.

To configure the audio input, use one of the following methods:

  • SetInputToAudioStream

  • SetInputToDefaultAudioDevice

  • SetInputToNull

  • SetInputToWaveFile

  • SetInputToWaveStream

The Microsoft Speech Platform Runtime 11 and Microsoft Speech Platform SDK 11 do not include any engines for speech recognition in a specific language. You must download a language pack (an engine for speech recognition in a specific language) for each language in which you want to perform speech recognition.

The language packs are different for each version of the Speech Platform Runtime. You must download the language pack version that matches the version of the Speech Platform Runtime that you have installed. The language packs for the Speech Platform SDK 11 are for server-based applications and are different than the languages that ship with Windows Vista or Windows 7. Use the following links to download the version of the server language packs that match your Speech Platform Runtime version:

  • Server Language Packs v11.0

  • Server Language Packs v10.2

  • Server Language Packs v10.1

  • Server Language Packs v10.0

See Language Support for a list of languages for which you can download language packs.

Examples

The following example initializes a SpeechRecognitionEngine object that selects the default speech recognition engine for US English (en-US).

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

      // Create a SpeechRecognitionEngine instance that selects
      // the default speech recognition engine for US English.
      using (SpeechRecognitionEngine recognizer =
         new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US")))
      {

        // Create a grammar.
        // Create lists of alternative choices.
        Choices listTypes = new Choices(new string[] { "albums", "artists" });
        Choices genres = new Choices(new string[] {
          "blues", "classical", "gospel", "jazz", "rock" });

        // Create a GrammarBuilder object and assemble the grammar components.
        GrammarBuilder mediaMenu = new GrammarBuilder("Display");
        mediaMenu.Append("the list of", 0, 1);
        mediaMenu.Append(listTypes);
        mediaMenu.Append("in the", 0, 1);
        mediaMenu.Append(genres);
        mediaMenu.Append("category", 0, 1);

        // Build a Grammar object from the GrammarBuilder.
        Grammar mediaMenuGrammar = new Grammar(mediaMenu);
        mediaMenuGrammar.Name = "Media Chooser";

        // Load the Grammar object to the SpeechRecognitionEngine.
        recognizer.LoadGrammarAsync(mediaMenuGrammar);

        // Add a handler for the speech recognized event.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

        // Configure input to the speech recognizer.
        recognizer.SetInputToDefaultAudioDevice();

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

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

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

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
SpeechRecognitionEngine Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionEngine Constructor (String)

[image]

SpeechRecognitionEngine Constructor (String)
SpeechRecognitionEngine Class Example See Also Send Feedback

Initializes a new instance of the SpeechRecognitionEngine class with a string parameter that specifies the name of the recognizer to use.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    recognizerId As String _
)
Visual Basic (Usage)
Dim recognizerId As String

Dim instance As New SpeechRecognitionEngine(recognizerId)
C#
public SpeechRecognitionEngine(
    string recognizerId
)

Parameters

recognizerId
Type: System..::..String

The token name of the speech recognizer to use.

Exceptions

Exception | Condition
NullArgumentException | Thrown if recognizerId is nullNothingnullptrunita null reference (Nothing in Visual Basic) or an empty string.
ArgumentException | Thrown if recognizerId does not match any installed speech recognizers.

Remarks

The token name of the recognizer is the value of the Id property of the RecognizerInfo object returned by the RecognizerInfo property of the SpeechRecognitionEngine object. To get a collection of all the installed recognizers, use the static InstalledRecognizers()()()() method.

Before the speech recognizer can begin recognition, you must load at least one speech recognition grammar and configure the input for the recognizer.

To load a grammar, call the LoadGrammar or LoadGrammarAsync method.

To configure the audio input, use one of the following methods:

  • SetInputToAudioStream

  • SetInputToDefaultAudioDevice

  • SetInputToNull

  • SetInputToWaveFile

  • SetInputToWaveStream

Examples

The following example creates an instance of SpeechRecognitionEngine by specifying the precise name of the speech recognition engine to use.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

      // Create a SpeechRecognitionEngine instance for the installed
      // speech recognition engine named SR_MS_en-US_TELE_10.0.
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine("SR_MS_en-US_TELE_10.0"))
      {

        // Create a grammar.
        // Create lists of alternative choices.
        Choices listTypes = new Choices(new string[] { "albums", "artists" });
        Choices genres = new Choices(new string[] {
          "blues", "classical", "gospel", "jazz", "rock" });

        // Create a GrammarBuilder object and assemble the grammar components.
        GrammarBuilder mediaMenu = new GrammarBuilder("Display");
        mediaMenu.Append("the list of", 0, 1);
        mediaMenu.Append(listTypes);
        mediaMenu.Append("in the", 0, 1);
        mediaMenu.Append(genres);
        mediaMenu.Append("category", 0, 1);

        // Build a Grammar object from the GrammarBuilder.
        Grammar mediaMenuGrammar = new Grammar(mediaMenu);
        mediaMenuGrammar.Name = "Media Chooser";

        // Load the Grammar object to the SpeechRecognitionEngine.
        recognizer.LoadGrammarAsync(mediaMenuGrammar);

        // Add a handler for the speech recognized event.
        recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

        // Configure input to the speech recognizer.
        recognizer.SetInputToDefaultAudioDevice();

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

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

    // Handle the SpeechRecognized event.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {

      Console.WriteLine("Recognized text: " + e.Result.Text);
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
SpeechRecognitionEngine Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionEngine Constructor (RecognizerInfo)

[image]

SpeechRecognitionEngine Constructor (RecognizerInfo)
SpeechRecognitionEngine Class Example See Also Send Feedback

Initializes a new instance of the SpeechRecognitionEngine using the information in a RecognizerInfo object to specify the recognizer to use.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    recognizerInfo As RecognizerInfo _
)
Visual Basic (Usage)
Dim recognizerInfo As RecognizerInfo

Dim instance As New SpeechRecognitionEngine(recognizerInfo)
C#
public SpeechRecognitionEngine(
    RecognizerInfo recognizerInfo
)

Parameters

recognizerInfo
Type: Microsoft.Speech.Recognition..::..RecognizerInfo

The information for the specific speech recognizer.

Remarks

You can create an instance of this class for any of the installed speech recognition engines. To get information about which speech recognition engines are installed, use the InstalledRecognizers()()()() method. See SpeechRecognitionEngine(CultureInfo) for information about downloading additional speech recognition engines for specific languages.

Before the speech recognizer can begin recognition, you must load at least one speech recognition grammar and configure the input for the recognizer.

To load a grammar, call the LoadGrammar or LoadGrammarAsync method.

To configure the audio input, use one of the following methods:

  • SetInputToAudioStream

  • SetInputToDefaultAudioDevice

  • SetInputToNull

  • SetInputToWaveFile

  • SetInputToWaveStream

Examples

The following example uses the InstalledRecognizers()()()() method to query for installed recognition engines that support English. The results of the query populate a RecognizerInfo object, which is used to initialize the SpeechRecognitionEngineobject.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

      // Select a speech recognizer that supports English.
      RecognizerInfo info = null;
      foreach (RecognizerInfo ri in SpeechRecognitionEngine.InstalledRecognizers())
      {
        if (ri.Culture.TwoLetterISOLanguageName.Equals("en"))
        {
          info = ri;
          break;
        }
      }
      if (info == null) return;

      // Create the selected recognizer.
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(info))
      {

        // Create a grammar, construct a Grammar object, and load it to the recognizer.
        Choices animals = new Choices(new string[] { "cow", "pig", "goat" });
        GrammarBuilder farm = new GrammarBuilder("On this farm he had a");
        farm.Append(animals);

        Grammar farmAnimals = new Grammar(farm);
        farmAnimals.Name = "Farm";

        recognizer.LoadGrammar(farmAnimals);

        // Add a handler for the speech recognized event.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

        // Configure input to the speech recognizer.
        recognizer.SetInputToDefaultAudioDevice();

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

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

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

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
SpeechRecognitionEngine Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionEngine Methods

[image] [image]

SpeechRecognitionEngine Methods
SpeechRecognitionEngine Class See Also Send Feedback

The SpeechRecognitionEngine type exposes the following members.

Methods

 | Name | Description
Public method | Dispose()()()() | Disposes the SpeechRecognitionEngine object.
Protected method | Dispose(Boolean) | Disposes the SpeechRecognitionEngine object and releases resources used during the session.
Public method | EmulateRecognize(String) | Emulates input of a phrase to the speech recognizer, using text in place of audio for synchronous speech recognition.
Public method | EmulateRecognize(String, EmulateOptions) | Emulates input of a phrase to the speech recognizer, using text in place of audio for synchronous speech recognition, and specifies the type of recognition operation to perform.
Public method | EmulateRecognize(String, CompareOptions) | Emulates audio input to the recognition engine, using text in place of audio for synchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars
Public method | EmulateRecognize(array<RecognizedWordUnit>[]()[][], CompareOptions) | Emulates input of specific words to the speech recognizer, using an array of RecognizedWordUnit objects in place of audio for synchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars.
Public method | EmulateRecognize(String, CompareOptions, EmulateOptions) | Emulates audio input to the recognition engine, using text in place of audio for synchronous speech recognition, specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.
Public method | EmulateRecognize(array<RecognizedWordUnit>[]()[][], CompareOptions, EmulateOptions) | Emulates input of specific words to the speech recognizer, using an array of RecognizedWordUnit objects in place of audio for synchronous speech recognition, specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.
Public method | EmulateRecognizeAsync(String) | Emulates input of a phrase to the speech recognizer, using text in place of audio for asynchronous speech recognition.
Public method | EmulateRecognizeAsync(String, EmulateOptions) | Emulates input of a phrase to the speech recognizer, using text in place of audio for asynchronous speech recognition, and specifies the type of recognition operation to perform.
Public method | EmulateRecognizeAsync(String, CompareOptions) | Emulates input of a phrase to the speech recognizer, using text in place of audio for asynchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars.
Public method | EmulateRecognizeAsync(array<RecognizedWordUnit>[]()[][], CompareOptions) | Emulates input of specific words to the speech recognizer, using text in place of audio for asynchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars.
Public method | EmulateRecognizeAsync(String, CompareOptions, EmulateOptions) | Emulates audio input to the recognition engine, using text in place of audio for asynchronous speech recognition, specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.
Public method | EmulateRecognizeAsync(array<RecognizedWordUnit>[]()[][], CompareOptions, EmulateOptions) | Emulates input of specific words to the speech recognizer, using an array of RecognizedWordUnit objects in place of audio for asynchronous speech recognition, specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
 | InstalledRecognizers | Returns information for all of the installed speech recognizers on the current system.
Public method | LoadGrammar | Synchronously loads a Grammar object.
Public method | LoadGrammarAsync | Asynchronously loads a Grammar object.
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | QueryRecognizerSetting | Returns the values of the current settings for a speech recognition engine managed by a SpeechRecognitionEngine object.
Public method | Recognize()()()() | Performs a synchronous speech recognition operation.
Public method | Recognize(TimeSpan) | Performs a synchronous speech recognition operation with a specified initial silence timeout period.
Public method | RecognizeAsync()()()() | Performs a single, asynchronous speech recognition operation.
Public method | RecognizeAsync(RecognizeMode) | Performs one or more asynchronous speech recognition operations.
Public method | RecognizeAsyncCancel | Terminates asynchronous recognition without waiting for the current recognition operation to complete.
Public method | RecognizeAsyncStop | Stops asynchronous recognition after the current recognition operation completes.
Public method | RequestRecognizerUpdate()()()() | Requests that the recognizer pauses to update its state.
Public method | RequestRecognizerUpdate(Object) | Requests that the recognizer pauses to update its state and provides a user token for the associated event.
Public method | RequestRecognizerUpdate(Object, TimeSpan) | Requests that the recognizer pauses to update its state and provides an offset and a user token for the associated event.
Public method | SetInputToAudioStream | Configures the SpeechRecognitionEngine object to receive input from an audio stream.
Public method | SetInputToDefaultAudioDevice | Configures the SpeechRecognitionEngine object to receive input from the default audio device.
Public method | SetInputToNull | Disables the input to the speech recognizer.
Public method | SetInputToWaveFile | Configures the SpeechRecognitionEngine object to receive input from a Waveform audio format (.wav) file.
Public method | SetInputToWaveStream | Configures the SpeechRecognitionEngine object to receive input from a stream that contains Waveform audio format (.wav) data.
Public method | SimulateRecognize | Simulates recognition of the specified string.
Public method | ToString | (Inherited from Object.)
Public method | UnloadAllGrammars | Unloads all Grammar objects from the recognizer.
Public method | UnloadGrammar | Unloads a specified Grammar object from the SpeechRecognitionEngine instance.
Public method | UpdateRecognizerSetting(String, Int32) | Updates the specified setting for the SpeechRecognitionEngine with the specified integer value.
Public method | UpdateRecognizerSetting(String, String) | Updates the specified setting for the SpeechRecognitionEngine with the specified integer value.
Top

See Also

Reference

SpeechRecognitionEngine Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Dispose Method

[image] [image]

SpeechRecognitionEngine..::..Dispose Method
SpeechRecognitionEngine Class See Also Send Feedback

Disposes the SpeechRecognitionEngine object.

Overload List

 | Name | Description
Public method | Dispose()()()() | Disposes the SpeechRecognitionEngine object.
Protected method | Dispose(Boolean) | Disposes the SpeechRecognitionEngine object and releases resources used during the session.
Top

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Dispose Method

[image]

SpeechRecognitionEngine..::..Dispose Method
SpeechRecognitionEngine Class See Also Send Feedback

Disposes the SpeechRecognitionEngine object.

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

Syntax

Visual Basic (Declaration)
Public Sub Dispose
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine

instance.Dispose()
C#
public void Dispose()

Implements

IDisposable..::..Dispose()()()()

Remarks

The Dispose()()()() method will block execution of disposing the SpeechRecognitionEngine object until either all pending event handlers have returned or until 30 seconds have elapsed, whichever occurs first. Be aware that if you call Dispose()()()() in an event handler, that this will create a circular wait for the full 30 seconds, during which execution of the method will be blocked. Typically, calling Dispose()()()() in an event handler is not advised.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Dispose Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Dispose Method (Boolean)

[image]

SpeechRecognitionEngine..::..Dispose Method (Boolean)
SpeechRecognitionEngine Class See Also Send Feedback

Disposes the SpeechRecognitionEngine object and releases resources used during the session.

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

Syntax

Visual Basic (Declaration)
Protected Overridable Sub Dispose ( _
    disposing As Boolean _
)
Visual Basic (Usage)
Dim disposing As Boolean

Me.Dispose(disposing)
C#
protected virtual void Dispose(
    bool disposing
)

Parameters

disposing
Type: System..::..Boolean

Remarks

The Dispose(Boolean) method will block execution of disposing the SpeechRecognitionEngine object until either all pending event handlers have returned or until 30 seconds have elapsed, whichever occurs first. Be aware that if you call Dispose(Boolean) in an event handler, that this will create a circular wait for the full 30 seconds, during which execution of the method will be blocked. Typically, calling Dispose(Boolean) in an event handler is not advised.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Dispose Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognize Method

[image] [image]

SpeechRecognitionEngine..::..EmulateRecognize Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Emulates input to the speech recognizer, using text in place of audio for synchronous speech recognition.

Overload List

 | Name | Description
Public method | EmulateRecognize(String) | Emulates input of a phrase to the speech recognizer, using text in place of audio for synchronous speech recognition.
Public method | EmulateRecognize(String, EmulateOptions) | Emulates input of a phrase to the speech recognizer, using text in place of audio for synchronous speech recognition, and specifies the type of recognition operation to perform.
Public method | EmulateRecognize(String, CompareOptions) | Emulates audio input to the recognition engine, using text in place of audio for synchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars
Public method | EmulateRecognize(array<RecognizedWordUnit>[]()[][], CompareOptions) | Emulates input of specific words to the speech recognizer, using an array of RecognizedWordUnit objects in place of audio for synchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars.
Public method | EmulateRecognize(String, CompareOptions, EmulateOptions) | Emulates audio input to the recognition engine, using text in place of audio for synchronous speech recognition, specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.
Public method | EmulateRecognize(array<RecognizedWordUnit>[]()[][], CompareOptions, EmulateOptions) | Emulates input of specific words to the speech recognizer, using an array of RecognizedWordUnit objects in place of audio for synchronous speech recognition, specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.
Top

Remarks

These methods bypass the system audio input and provide text to the recognizer as String objects or as an array of RecognizedWordUnit objects. The SpeechRecognitionEngine matches the input text to its loaded Grammar objects, and returns a RecognitionResult object.

Using the EmulateOptions parameter, you can specify one of three types of recognition operation:

  • Emulation. Uses text instead of audio as input to the speech recognition engine to perform recognition.

  • IdentifyConfusion. Identifies phrases in a grammar that may generate false acceptances on recognition because of similarity to other phrases in the grammar.

  • Simulation. Creates an 'idealized' audio representation of the input phrase (based on the speech recognition engine's lexicon and acoustic model), and then performs recognition on the idealized audio.

See EmulateOptions for more information.

Use the SetInputToNull()()()() method to disable audio input to the speech recognition engine during emulation operations.

The speech recognizer raises the SpeechDetected, SpeechHypothesized, SpeechRecognitionRejected, and SpeechRecognized events as if the recognition operation is not emulated. The recognizer ignores new lines and extra white space and treats punctuation as literal input.

Note Note

The RecognitionResult object generated by the speech recognizer in response to emulated input has a value of nullNothingnullptrunita null reference (Nothing in Visual Basic) for its Audio property.

To emulate asynchronous recognition, use the EmulateRecognizeAsync method.

Examples

In the following example, an application obtains text input through a Textbox, and uses it to emulate speech input.

Copy image Copy Code
private void EmulateTextBox_KeyPress(object sender, KeyPressEventArgs eventArgs)
{
  if ((Keys)eventArgs.KeyChar == Keys.Enter)
  {
    RecognitionResult result = _recognitionEngine.EmulateRecognize(_emulateTextBox.Text);
  }
}

// Emulate a button click in the emulateTextBox.
private void _emulateButton_Click(object sender, EventArgs e)
{
  RecognitionResult result = _recognitionEngine.EmulateRecognize(_emulateTextBox.Text);
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SpeechRecognized
EmulateRecognizeAsync
RecognizedWordUnit
EmulateOptions

Other Resources

Microsoft Grammar Development Tools
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognize Method (String)

[image]

SpeechRecognitionEngine..::..EmulateRecognize Method (String)
SpeechRecognitionEngine Class Example See Also Send Feedback

Emulates input of a phrase to the speech recognizer, using text in place of audio for synchronous speech recognition.

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

Syntax

Visual Basic (Declaration)
Public Function EmulateRecognize ( _
    inputText As String _
) As RecognitionResult
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim inputText As String
Dim returnValue As RecognitionResult

returnValue = instance.EmulateRecognize(inputText)
C#
public RecognitionResult EmulateRecognize(
    string inputText
)

Parameters

inputText
Type: System..::..String

The text to use as the input phrase.

Return Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

The result for the recognition operation, or nullNothingnullptrunita null reference (Nothing in Visual Basic) if the operation is not successful.

Remarks

The speech recognizer raises the SpeechDetected, SpeechHypothesized, SpeechRecognitionRejected, and SpeechRecognized events as if the recognition operation is not emulated. The recognizer ignores new lines and extra white space and treats punctuation as literal input.

Examples

The code example below is part of a console application that demonstrates emulated input, the associated recognition results, and the associated events raised by the speech recognizer. The example generates the following output.

Copy image Copy Code
TestRecognize("Smith")...
 SpeechDetected event raised.
 SpeechRecognized event raised.
  Grammar = Smith; Text = Smith
...Recognition result text = Smith

TestRecognize("Jones")...
 SpeechDetected event raised.
 SpeechRecognized event raised.
  Grammar = Jones; Text = Jones
...Recognition result text = Jones

TestRecognize("Mister")...
 SpeechDetected event raised.
 SpeechHypothesized event raised.
  Grammar = Smith; Text = mister
 SpeechRecognitionRejected event raised.
  Grammar = <not available>; Text =
...No recognition result.

TestRecognize("Mister Smith")...
 SpeechDetected event raised.
 SpeechRecognized event raised.
  Grammar = Smith; Text = mister Smith
...Recognition result text = mister Smith

press any key to exit...
C# Copy image Copy Code
using System;
using System.Globalization;
using Microsoft.Speech.Recognition;

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

      // Create an in-process speech recognizer for the en-US locale.
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(new CultureInfo("en-US")))
      {

        // Load grammars.
        recognizer.LoadGrammar(CreateNameGrammar("Smith"));
        recognizer.LoadGrammar(CreateNameGrammar("Jones"));

        // Disable audio input to the recognizer.
        recognizer.SetInputToNull();

        // Add handlers for events raised by the EmulateRecognize method.
        recognizer.SpeechDetected +=
          new EventHandler<SpeechDetectedEventArgs>(
            SpeechDetectedHandler);
        recognizer.SpeechHypothesized +=
          new EventHandler<SpeechHypothesizedEventArgs>(
            SpeechHypothesizedHandler);
        recognizer.SpeechRecognitionRejected +=
          new EventHandler<SpeechRecognitionRejectedEventArgs>(
            SpeechRecognitionRejectedHandler);
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(
            SpeechRecognizedHandler);

        // Start four synchronous emulated recognition operations.
        TestRecognize(recognizer, "Smith");
        TestRecognize(recognizer, "Jones");
        TestRecognize(recognizer, "Mister");
        TestRecognize(recognizer, "Mister Smith");
      }

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

    // Create a simple name grammar.
    // Set the grammar name to the surname.
    private static Grammar CreateNameGrammar(string surname)
    {
      GrammarBuilder builder = new GrammarBuilder("mister", 0, 1);
      builder.Append(surname);

      Grammar nameGrammar = new Grammar(builder);
      nameGrammar.Name = surname;

      return nameGrammar;
    }

    // Send emulated input to the recognizer for synchronous recognition.
    private static void TestRecognize(
      SpeechRecognitionEngine recognizer, string input)
    {
      Console.WriteLine("TestRecognize(\"{0}\")...", input);
      RecognitionResult result =
        recognizer.EmulateRecognize(input,CompareOptions.IgnoreCase);
      if (result != null)
      {
        Console.WriteLine("...Recognition result text = {0}",
          result.Text ?? "<null>");
      }
      else
      {
        Console.WriteLine("...No recognition result.");
      }
      Console.WriteLine();
    }

    static void SpeechDetectedHandler(
      object sender, SpeechDetectedEventArgs e)
    {
      Console.WriteLine(" SpeechDetected event raised.");
    }

    // Handle events.
    static void SpeechHypothesizedHandler(
      object sender, SpeechHypothesizedEventArgs e)
    {
      Console.WriteLine(" SpeechHypothesized event raised.");
      if (e.Result != null)
      {
        Console.WriteLine("  Grammar = {0}; Text = {1}",
          e.Result.Grammar.Name ?? "<none>", e.Result.Text);
      }
      else
      {
        Console.WriteLine("  No recognition result available.");
      }
    }

    static void SpeechRecognitionRejectedHandler(
      object sender, SpeechRecognitionRejectedEventArgs e)
    {
      Console.WriteLine(" SpeechRecognitionRejected event raised.");
      if (e.Result != null)
      {
        string grammarName;
        if (e.Result.Grammar != null)
        {
          grammarName = e.Result.Grammar.Name ?? "<none>";
        }
        else
        {
          grammarName = "<not available>";
        }
        Console.WriteLine("  Grammar = {0}; Text = {1}",
          grammarName, e.Result.Text);
      }
      else
      {
        Console.WriteLine("  No recognition result available.");
      }
    }

    static void SpeechRecognizedHandler(
      object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine(" SpeechRecognized event raised.");
      if (e.Result != null)
      {
        Console.WriteLine("  Grammar = {0}; Text = {1}",
          e.Result.Grammar.Name ?? "<none>", e.Result.Text);
      }
      else
      {
        Console.WriteLine("  No recognition result available.");
      }
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
EmulateRecognize Overload
Microsoft.Speech.Recognition Namespace
SpeechRecognized
EmulateRecognize
EmulateRecognizeAsync
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognize Method (String, EmulateOptions)

[image]

SpeechRecognitionEngine..::..EmulateRecognize Method (String, EmulateOptions)
SpeechRecognitionEngine Class See Also Send Feedback

Emulates input of a phrase to the speech recognizer, using text in place of audio for synchronous speech recognition, and specifies the type of recognition operation to perform.

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

Syntax

Visual Basic (Declaration)
Public Function EmulateRecognize ( _
    inputText As String, _
    emulateOptions As EmulateOptions _
) As RecognitionResult
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim inputText As String
Dim emulateOptions As EmulateOptions
Dim returnValue As RecognitionResult

returnValue = instance.EmulateRecognize(inputText, _
    emulateOptions)
C#
public RecognitionResult EmulateRecognize(
    string inputText,
    EmulateOptions emulateOptions
)

Parameters

inputText
Type: System..::..String

The text to use as the input phrase.

emulateOptions
Type: Microsoft.Speech.Recognition..::..EmulateOptions

The type of recognition operation to perform.

Return Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

Returns RecognitionResult.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
EmulateRecognize Overload
Microsoft.Speech.Recognition Namespace
EmulateOptions
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognize Method (String, CompareOptions)

[image]

SpeechRecognitionEngine..::..EmulateRecognize Method (String, CompareOptions)
SpeechRecognitionEngine Class Example See Also Send Feedback

Emulates audio input to the recognition engine, using text in place of audio for synchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars

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

Syntax

Visual Basic (Declaration)
Public Function EmulateRecognize ( _
    inputText As String, _
    compareOptions As CompareOptions _
) As RecognitionResult
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim inputText As String
Dim compareOptions As CompareOptions
Dim returnValue As RecognitionResult

returnValue = instance.EmulateRecognize(inputText, _
    compareOptions)
C#
public RecognitionResult EmulateRecognize(
    string inputText,
    CompareOptions compareOptions
)

Parameters

inputText
Type: System..::..String

The text to use as the input phrase.

compareOptions
Type: System.Globalization..::..CompareOptions

A bitwise combination of the enumeration values that describe the type of comparison to use for the emulated recognition operation.

Return Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

The result for the recognition operation, or nullNothingnullptrunita null reference (Nothing in Visual Basic) if the operation is not successful.

Remarks

The speech recognizer raises the SpeechDetected, SpeechHypothesized, SpeechRecognitionRejected, and SpeechRecognized events as if the recognition operation is not emulated. The recognizer ignores new lines and extra white space and treats punctuation as literal input.

The only supported values of the compareOptions argument are the OrdinalIgnoreCase and IgnoreCase members of the CompareOptions enumerated type. All other members will generate a NotSupportedException exception or return a nullNothingnullptrunita null reference (Nothing in Visual Basic).

Examples

In the following example, an application obtains text input through a Textbox, and uses it to emulate speech recognition. The recognition emulation is performed ignoring case and performing an ordinal comparison.

Copy image Copy Code
private void EmulateTextBox_KeyPress(object sender, KeyPressEventArgs eventArgs)
{
  if ((Keys)eventArgs.KeyChar == Keys.Enter)
  {
    _recognitionEngine.EmulateRecognize(_emulateTextBox.Text, System.Globalization.CompareOptions.OrdinalIgnoreCase);
  }
}

// Emulate a button click in the emulateTextBox.
private void _emulateButton_Click(object sender, EventArgs e)
{
  RecognitionResult result = _recognitionEngine.EmulateRecognize(_emulateTextBox.Text);
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
EmulateRecognize Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognize Method (RecognizedWordUnit[], CompareOptions)

[image]

SpeechRecognitionEngine..::..EmulateRecognize Method (array<RecognizedWordUnit>[]()[][], CompareOptions)
SpeechRecognitionEngine Class Example See Also Send Feedback

Emulates input of specific words to the speech recognizer, using an array of RecognizedWordUnit objects in place of audio for synchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars.

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

Syntax

Visual Basic (Declaration)
Public Function EmulateRecognize ( _
    wordUnits As RecognizedWordUnit(), _
    compareOptions As CompareOptions _
) As RecognitionResult
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim wordUnits As RecognizedWordUnit()
Dim compareOptions As CompareOptions
Dim returnValue As RecognitionResult

returnValue = instance.EmulateRecognize(wordUnits, _
    compareOptions)
C#
public RecognitionResult EmulateRecognize(
    RecognizedWordUnit[] wordUnits,
    CompareOptions compareOptions
)

Parameters

wordUnits
Type: array< Microsoft.Speech.Recognition..::..RecognizedWordUnit >[]()[][]

An array of word units that contains the input for the recognition operation.

compareOptions
Type: System.Globalization..::..CompareOptions

A bitwise combination of the enumeration values that describe the type of comparison to use for the emulated recognition operation.

Return Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

The result for the recognition operation, or nullNothingnullptrunita null reference (Nothing in Visual Basic) if the operation is not successful.

Remarks

The speech recognizer raises the SpeechDetected, SpeechHypothesized, SpeechRecognitionRejected, and SpeechRecognized events as if the recognition operation is not emulated. The recognizer ignores new lines and extra white space and treats punctuation as literal input.

The only supported values of the compareOptions argument are the OrdinalIgnoreCase and IgnoreCase members of the CompareOptions enumerated type. All other members will generate a NotSupportedException exception or return a nullNothingnullptrunita null reference (Nothing in Visual Basic).

Examples

In the example below, an array of RecognizedWordUnit objects is obtained from a recognized candidate and tested against the other grammars the recognition engine supports.

Copy image Copy Code
private void checkOtherGrammars(RecognizedPhrase candidate)
{
  string msg = "";
  if (candidate != null && candidate.Grammar != null)
  {
    //Unload successful grammar and try again, see if other grammars
    Collection<Grammar> unloadList= new Collection<Grammar>(); //keep track of unloaded grammars and reload.
    _recognitionEngine.UnloadGrammar(candidate.Grammar);
    unloadList.Add(candidate.Grammar);
    RecognizedWordUnit[] words = new RecognizedWordUnit[candidate.Words.Count];
    candidate.Words.CopyTo(words, 0);

    //Iterate over remaining grammars
    msg = String.Format("Candidate \"{0}\"\nSelected by Grammar: \"{1}\"\n\n",
        candidate.Text, candidate.Grammar);
    while (_recognitionEngine.Grammars.Count != 0)
    {
      RecognitionResult emResult = _recognitionEngine.EmulateRecognize(
                words, System.Globalization.CompareOptions.OrdinalIgnoreCase);
      if (emResult == null)
      {
        break;
      }
      else
      {
        msg += String.Format("Emulation returns \"{0}\"\nSelected by Grammar: \"{1}\" \n",
               emResult.Text, emResult.Grammar.Name);
        _recognitionEngine.UnloadGrammar(emResult.Grammar);
        unloadList.Add(emResult.Grammar);
      }
    }

    MessageBox.Show(msg);
    // restore grammars
    for (int i=0;i<unloadList.Count;i++)
    {
      _recognitionEngine.LoadGrammar(unloadList[i]);
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
EmulateRecognize Overload
Microsoft.Speech.Recognition Namespace
SpeechRecognized
EmulateRecognize
EmulateRecognizeAsync
RecognizedWordUnit
CompareOptions
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognize Method (String, CompareOptions, EmulateOptions)

[image]

SpeechRecognitionEngine..::..EmulateRecognize Method (String, CompareOptions, EmulateOptions)
SpeechRecognitionEngine Class See Also Send Feedback

Emulates audio input to the recognition engine, using text in place of audio for synchronous speech recognition, specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.

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

Syntax

Visual Basic (Declaration)
Public Function EmulateRecognize ( _
    inputText As String, _
    compareOptions As CompareOptions, _
    emulateOptions As EmulateOptions _
) As RecognitionResult
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim inputText As String
Dim compareOptions As CompareOptions
Dim emulateOptions As EmulateOptions
Dim returnValue As RecognitionResult

returnValue = instance.EmulateRecognize(inputText, _
    compareOptions, emulateOptions)
C#
public RecognitionResult EmulateRecognize(
    string inputText,
    CompareOptions compareOptions,
    EmulateOptions emulateOptions
)

Parameters

inputText
Type: System..::..String

The text to use as the input phrase.

compareOptions
Type: System.Globalization..::..CompareOptions

A bitwise combination of the enumeration values that describe the type of comparison to use for the emulated recognition operation.

emulateOptions
Type: Microsoft.Speech.Recognition..::..EmulateOptions

The type of recognition operation to perform.

Return Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

Returns .

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
EmulateRecognize Overload
Microsoft.Speech.Recognition Namespace
EmulateOptions
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognize Method (RecognizedWordUnit[], CompareOptions, EmulateOptions)

[image]

SpeechRecognitionEngine..::..EmulateRecognize Method (array<RecognizedWordUnit>[]()[][], CompareOptions, EmulateOptions)
SpeechRecognitionEngine Class See Also Send Feedback

Emulates input of specific words to the speech recognizer, using an array of RecognizedWordUnit objects in place of audio for synchronous speech recognition, specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.

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

Syntax

Visual Basic (Declaration)
Public Function EmulateRecognize ( _
    wordUnits As RecognizedWordUnit(), _
    compareOptions As CompareOptions, _
    emulateOptions As EmulateOptions _
) As RecognitionResult
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim wordUnits As RecognizedWordUnit()
Dim compareOptions As CompareOptions
Dim emulateOptions As EmulateOptions
Dim returnValue As RecognitionResult

returnValue = instance.EmulateRecognize(wordUnits, _
    compareOptions, emulateOptions)
C#
public RecognitionResult EmulateRecognize(
    RecognizedWordUnit[] wordUnits,
    CompareOptions compareOptions,
    EmulateOptions emulateOptions
)

Parameters

wordUnits
Type: array< Microsoft.Speech.Recognition..::..RecognizedWordUnit >[]()[][]

An array of word units that contains the input for the recognition operation

compareOptions
Type: System.Globalization..::..CompareOptions

A bitwise combination of the enumeration values that describe the type of comparison to use for the emulated recognition operation.

emulateOptions
Type: Microsoft.Speech.Recognition..::..EmulateOptions

The type of recognition operation to perform.

Return Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

Returns RecognitionResult.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
EmulateRecognize Overload
Microsoft.Speech.Recognition Namespace
EmulateOptions
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognizeAsync Method

[image] [image]

SpeechRecognitionEngine..::..EmulateRecognizeAsync Method
SpeechRecognitionEngine Class See Also Send Feedback

Emulates input to the speech recognizer, using text in place of audio for asynchronous speech recognition.

Overload List

 | Name | Description
Public method | EmulateRecognizeAsync(String) | Emulates input of a phrase to the speech recognizer, using text in place of audio for asynchronous speech recognition.
Public method | EmulateRecognizeAsync(String, EmulateOptions) | Emulates input of a phrase to the speech recognizer, using text in place of audio for asynchronous speech recognition, and specifies the type of recognition operation to perform.
Public method | EmulateRecognizeAsync(String, CompareOptions) | Emulates input of a phrase to the speech recognizer, using text in place of audio for asynchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars.
Public method | EmulateRecognizeAsync(array<RecognizedWordUnit>[]()[][], CompareOptions) | Emulates input of specific words to the speech recognizer, using text in place of audio for asynchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars.
Public method | EmulateRecognizeAsync(String, CompareOptions, EmulateOptions) | Emulates audio input to the recognition engine, using text in place of audio for asynchronous speech recognition, specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.
Public method | EmulateRecognizeAsync(array<RecognizedWordUnit>[]()[][], CompareOptions, EmulateOptions) | Emulates input of specific words to the speech recognizer, using an array of RecognizedWordUnit objects in place of audio for asynchronous speech recognition, specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.
Top

Remarks

These methods bypass the system audio input and provide text to the recognizer as String objects or as an array of RecognizedWordUnit objects. These methods can be helpful when you are testing or debugging an application or a grammar.

Using the EmulateOptions parameter, you can specify one of three types of recognition operation:

  • Emulation. Uses text instead of audio as input to the speech recognition engine to perform recognition.

  • IdentifyConfusion. Identifies phrases in a grammar that may generate false acceptances on recognition because of similarity to other phrases in the grammar.

  • Simulation. Creates an 'idealized' audio representation of the input phrase (based on the speech recognition engine's lexicon and acoustic model), and then performs recognition on the idealized audio.

See EmulateOptions for more information.

Use the SetInputToNull()()()() method to disable audio input to the speech recognition engine during emulation operations.

The speech recognizer raises the SpeechDetected, SpeechHypothesized, SpeechRecognitionRejected, and SpeechRecognized events as if the recognition operation is not emulated. When the recognizer completes the asynchronous recognition operation, it raises the EmulateRecognizeCompleted event. The recognizer ignores new lines and extra white space and treats punctuation as literal input.

Note Note

The RecognitionResult object generated by the speech recognizer in response to emulated input has a value of nullNothingnullptrunita null reference (Nothing in Visual Basic) for its Audio property.

To emulate synchronous recognition, use the EmulateRecognize method.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SpeechRecognizedEventArgs
EmulateRecognize
EmulateRecognize
EmulateRecognizeAsync
EmulateRecognize
RecognizedWordUnit
EmulateOptions

Other Resources

Microsoft Grammar Development Tools
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognizeAsync Method (String)

[image]

SpeechRecognitionEngine..::..EmulateRecognizeAsync Method (String)
SpeechRecognitionEngine Class Example See Also Send Feedback

Emulates input of a phrase to the speech recognizer, using text in place of audio for asynchronous speech recognition.

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

Syntax

Visual Basic (Declaration)
Public Sub EmulateRecognizeAsync ( _
    inputText As String _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim inputText As String

instance.EmulateRecognizeAsync(inputText)
C#
public void EmulateRecognizeAsync(
    string inputText
)

Parameters

inputText
Type: System..::..String

The input for the recognition operation.

Remarks

The speech recognizer raises the SpeechDetected, SpeechHypothesized, SpeechRecognitionRejected, and SpeechRecognized events as if the recognition operation is not emulated. When the recognizer completes the asynchronous recognition operation, it raises the EmulateRecognizeCompleted event.

Emulated recognition ignores new lines and extra white space and treats punctuation literally, rather than letting it define phrases.

Examples

In the following example, an application obtains text input through a Textbox, and uses it to emulate speech recognition.

Copy image Copy Code
private void EmulateTextBox_KeyPress(object sender, KeyPressEventArgs eventArgs)
{
  if ((Keys)eventArgs.KeyChar == Keys.Enter)
  {
  _recognitionEngine.EmulateRecognizeAsync(_emulateTextBox.Text);
  }
}

// Emulate a button click in the emulateTextBox.
private void _emulateButton_Click(object sender, EventArgs e)
{
  _recognitionEngine.EmulateRecognizeAsync(_emulateTextBox.Text);
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
EmulateRecognizeAsync Overload
Microsoft.Speech.Recognition Namespace
SpeechRecognized
EmulateRecognize
EmulateRecognizeAsync
EmulateRecognizeCompleted
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognizeAsync Method (String, EmulateOptions)

[image]

SpeechRecognitionEngine..::..EmulateRecognizeAsync Method (String, EmulateOptions)
SpeechRecognitionEngine Class See Also Send Feedback

Emulates input of a phrase to the speech recognizer, using text in place of audio for asynchronous speech recognition, and specifies the type of recognition operation to perform.

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

Syntax

Visual Basic (Declaration)
Public Sub EmulateRecognizeAsync ( _
    inputText As String, _
    emulateOptions As EmulateOptions _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim inputText As String
Dim emulateOptions As EmulateOptions

instance.EmulateRecognizeAsync(inputText, _
    emulateOptions)
C#
public void EmulateRecognizeAsync(
    string inputText,
    EmulateOptions emulateOptions
)

Parameters

inputText
Type: System..::..String

The text to use as the input phrase.

emulateOptions
Type: Microsoft.Speech.Recognition..::..EmulateOptions

The type of recognition operation to perform.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
EmulateRecognizeAsync Overload
Microsoft.Speech.Recognition Namespace
EmulateOptions
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognizeAsync Method (String, CompareOptions)

[image]

SpeechRecognitionEngine..::..EmulateRecognizeAsync Method (String, CompareOptions)
SpeechRecognitionEngine Class Example See Also Send Feedback

Emulates input of a phrase to the speech recognizer, using text in place of audio for asynchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars.

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

Syntax

Visual Basic (Declaration)
Public Sub EmulateRecognizeAsync ( _
    inputText As String, _
    compareOptions As CompareOptions _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim inputText As String
Dim compareOptions As CompareOptions

instance.EmulateRecognizeAsync(inputText, _
    compareOptions)
C#
public void EmulateRecognizeAsync(
    string inputText,
    CompareOptions compareOptions
)

Parameters

inputText
Type: System..::..String

The input phrase for the recognition operation.

compareOptions
Type: System.Globalization..::..CompareOptions

A bitwise combination of the enumeration values that describe the type of comparison to use for the emulated recognition operation.

Remarks

The speech recognizer raises the SpeechDetected, SpeechHypothesized, SpeechRecognitionRejected, and SpeechRecognized events as if the recognition operation is not emulated. When the recognizer completes the asynchronous recognition operation, it raises the EmulateRecognizeCompleted event.

The only supported values of the compareOptions argument are OrdinalIgnoreCase and IgnoreCase. All other members of CompareOptions will generate a NotSupportedException exception or return a nullNothingnullptrunita null reference (Nothing in Visual Basic).

Emulated recognition ignores new lines and extra white space and treats punctuation literally, rather than letting it define phrases.

Examples

Copy image Copy Code
private void EmulateTextBox_KeyPress(object sender, KeyPressEventArgs eventArgs)
{
  if ((Keys)eventArgs.KeyChar == Keys.Enter)
  {
    _recognitionEngine.EmulateRecognizeAsync(_emulateTextBox.Text);

  }
}

// Emulate a button click in the emulateTextBox.
private void _emulateButton_Click(object sender, EventArgs e)
{
  _recognitionEngine.EmulateRecognizeAsync(_emulateTextBox.Text, System.Globalization.CompareOptions.IgnoreCase);
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
EmulateRecognizeAsync Overload
Microsoft.Speech.Recognition Namespace
SpeechRecognized
EmulateRecognize
EmulateRecognizeAsync
CompareOptions
EmulateRecognizeCompleted
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognizeAsync Method (RecognizedWordUnit[], CompareOptions)

[image]

SpeechRecognitionEngine..::..EmulateRecognizeAsync Method (array<RecognizedWordUnit>[]()[][], CompareOptions)
SpeechRecognitionEngine Class Example See Also Send Feedback

Emulates input of specific words to the speech recognizer, using text in place of audio for asynchronous speech recognition, and specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars.

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

Syntax

Visual Basic (Declaration)
Public Sub EmulateRecognizeAsync ( _
    wordUnits As RecognizedWordUnit(), _
    compareOptions As CompareOptions _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim wordUnits As RecognizedWordUnit()
Dim compareOptions As CompareOptions

instance.EmulateRecognizeAsync(wordUnits, _
    compareOptions)
C#
public void EmulateRecognizeAsync(
    RecognizedWordUnit[] wordUnits,
    CompareOptions compareOptions
)

Parameters

wordUnits
Type: array< Microsoft.Speech.Recognition..::..RecognizedWordUnit >[]()[][]

An array of word units that contains the input for the recognition operation.

compareOptions
Type: System.Globalization..::..CompareOptions

A bitwise combination of the enumeration values that describe the type of comparison to use for the emulated recognition operation.

Remarks

The speech recognizer raises the SpeechDetected, SpeechHypothesized, SpeechRecognitionRejected, and SpeechRecognized events as if the recognition operation is not emulated. When the recognizer completes the asynchronous recognition operation, it raises the EmulateRecognizeCompleted event.

The only supported values of the compareOptions argument are OrdinalIgnoreCase and IgnoreCase. All other members of CompareOptions will generate a NotSupportedException exception or return a nullNothingnullptrunita null reference (Nothing in Visual Basic).

Emulated recognition ignores new lines and extra white space and treats punctuation literally, rather than letting it define phrases.

Examples

In the following example, an application obtains text input through a Textbox, and uses it to asynchronously emulate speech recognition.

Information about the emulated recognition is returned to the user interface by the anonymous method used as the handler for EmulateRecognizeCompleted events.

Copy image Copy Code
private void _emulateButton_Click(object sender, EventArgs e)
{
  _asyncEmulation = true;
  RecognitionResult result =
    _recognitionEngine.EmulateRecognizeAsync(_emulateTextBox.Text);
}

_recognitionEngine.EmulateRecognizeCompleted += delegate(object sender, EmulateRecognizeCompletedEventArgs eventArgs)
{
  _asyncEmulation = false;
  Utils.DisplayAudioInputFormat(_audioStateLabel, _recognitionEngine);
  DisplayResult(eventArgs);
};

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
EmulateRecognizeAsync Overload
Microsoft.Speech.Recognition Namespace
SpeechRecognized
EmulateRecognize
EmulateRecognizeAsync
RecognizedWordUnit
CompareOptions
EmulateRecognizeCompleted
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognizeAsync Method (String, CompareOptions, EmulateOptions)

[image]

SpeechRecognitionEngine..::..EmulateRecognizeAsync Method (String, CompareOptions, EmulateOptions)
SpeechRecognitionEngine Class See Also Send Feedback

Emulates audio input to the recognition engine, using text in place of audio for asynchronous speech recognition, specifies how the recognizer handles Unicode comparison between the phrase and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.

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

Syntax

Visual Basic (Declaration)
Public Sub EmulateRecognizeAsync ( _
    inputText As String, _
    compareOptions As CompareOptions, _
    emulateOptions As EmulateOptions _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim inputText As String
Dim compareOptions As CompareOptions
Dim emulateOptions As EmulateOptions

instance.EmulateRecognizeAsync(inputText, _
    compareOptions, emulateOptions)
C#
public void EmulateRecognizeAsync(
    string inputText,
    CompareOptions compareOptions,
    EmulateOptions emulateOptions
)

Parameters

inputText
Type: System..::..String

The text to use as the input phrase.

compareOptions
Type: System.Globalization..::..CompareOptions

A bitwise combination of the enumeration values that describe the type of comparison to use for the emulated recognition operation.

emulateOptions
Type: Microsoft.Speech.Recognition..::..EmulateOptions

The type of recognition operation to perform.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
EmulateRecognizeAsync Overload
Microsoft.Speech.Recognition Namespace
EmulateOptions
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognizeAsync Method (RecognizedWordUnit[], CompareOptions, EmulateOptions)

[image]

SpeechRecognitionEngine..::..EmulateRecognizeAsync Method (array<RecognizedWordUnit>[]()[][], CompareOptions, EmulateOptions)
SpeechRecognitionEngine Class See Also Send Feedback

Emulates input of specific words to the speech recognizer, using an array of RecognizedWordUnit objects in place of audio for asynchronous speech recognition, specifies how the recognizer handles Unicode comparison between the words and the loaded speech recognition grammars, and specifies the type of recognition operation to perform.

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

Syntax

Visual Basic (Declaration)
Public Sub EmulateRecognizeAsync ( _
    wordUnits As RecognizedWordUnit(), _
    compareOptions As CompareOptions, _
    emulateOptions As EmulateOptions _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim wordUnits As RecognizedWordUnit()
Dim compareOptions As CompareOptions
Dim emulateOptions As EmulateOptions

instance.EmulateRecognizeAsync(wordUnits, _
    compareOptions, emulateOptions)
C#
public void EmulateRecognizeAsync(
    RecognizedWordUnit[] wordUnits,
    CompareOptions compareOptions,
    EmulateOptions emulateOptions
)

Parameters

wordUnits
Type: array< Microsoft.Speech.Recognition..::..RecognizedWordUnit >[]()[][]

An array of word units that contains the input for the recognition operation

compareOptions
Type: System.Globalization..::..CompareOptions

A bitwise combination of the enumeration values that describe the type of comparison to use for the emulated recognition operation.

emulateOptions
Type: Microsoft.Speech.Recognition..::..EmulateOptions

The type of recognition operation to perform.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
EmulateRecognizeAsync Overload
Microsoft.Speech.Recognition Namespace
EmulateOptions
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InstalledRecognizers Method

[image]

SpeechRecognitionEngine..::..InstalledRecognizers Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Returns information for all of the installed speech recognizers on the current system.

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

Syntax

Visual Basic (Declaration)
Public Shared Function InstalledRecognizers As ReadOnlyCollection(Of RecognizerInfo)
Visual Basic (Usage)
Dim returnValue As ReadOnlyCollection(Of RecognizerInfo)

returnValue = SpeechRecognitionEngine.InstalledRecognizers()
C#
public static ReadOnlyCollection<RecognizerInfo> InstalledRecognizers()

Return Value

Type: System.Collections.ObjectModel..::..ReadOnlyCollection <(Of <(<' RecognizerInfo >)>)>

A read-only collection of the RecognizerInfo objects that describe the installed recognizers.

Remarks

To get information about the current recognizer, use the RecognizerInfo property.

Examples

The following example shows part of a console application that demonstrates basic speech recognition. The example uses the collection returned by the InstalledRecognizers()()()() method to find a speech recognizer that supports the English language.

C# Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

      // Select a speech recognizer that supports English.
      RecognizerInfo info = null;
      foreach (RecognizerInfo ri in SpeechRecognitionEngine.InstalledRecognizers())
      {
        if (ri.Culture.TwoLetterISOLanguageName.Equals("en"))
        {
          info = ri;
          break;
        }
      }
      if (info == null) return;

      // Create the selected recognizer.
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(info))
      {

        // Create and load a dictation grammar.
        recognizer.LoadGrammar(new DictationGrammar());

        // Add a handler for the speech recognized event.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

        // Configure input to the speech recognizer.
        recognizer.SetInputToDefaultAudioDevice();

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

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

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

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


LoadGrammar Method

[image]

SpeechRecognitionEngine..::..LoadGrammar Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Synchronously loads a Grammar object.

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

Syntax

Visual Basic (Declaration)
Public Sub LoadGrammar ( _
    grammar As Grammar _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim grammar As Grammar

instance.LoadGrammar(grammar)
C#
public void LoadGrammar(
    Grammar grammar
)

Parameters

grammar
Type: Microsoft.Speech.Recognition..::..Grammar

The grammar object to load.

Remarks

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.

Examples

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.

Copy image Copy Code
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";
        recognizer.LoadGrammarAsync(testGrammar);

        // Configure recognizer input.
        recognizer.SetInputToDefaultAudioDevice();

        // 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.
        recognizer.RecognizeAsync();
        Console.WriteLine("Starting asynchronous recognition...");

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

    // 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);
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
RecognizerUpdateReached
UnloadAllGrammars
UnloadGrammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


LoadGrammarAsync Method

[image]

SpeechRecognitionEngine..::..LoadGrammarAsync Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Asynchronously loads a Grammar object.

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

Syntax

Visual Basic (Declaration)
Public Sub LoadGrammarAsync ( _
    grammar As Grammar _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim grammar As Grammar

instance.LoadGrammarAsync(grammar)
C#
public void LoadGrammarAsync(
    Grammar grammar
)

Parameters

grammar
Type: Microsoft.Speech.Recognition..::..Grammar

The grammar object to load.

Remarks

When the recognizer completes loading a Grammar object, it raises a LoadGrammarCompleted event. 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 synchronously, use the LoadGrammar(Grammar) method.

Examples

The following example creates two speech recognition grammars and constructs a Grammar object from each of the completed grammars. It then asynchronously loads the Grammar objects to the SpeechRecognitionEngine instance. The handler for the recognizer's LoadGrammarCompleted event reports the status of Grammar objects when loaded. The handler for the SpeechRecognized event reports the name of the Grammar object that was used to perform a recognition and the text of the recognition result.

Copy image Copy Code
using System;
using Microsoft.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();

      // 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);

      // Create the "yesno" grammar and build it into a Grammar object.
      Choices yesChoices = new Choices(new string[] { "yes", "yup", "yeah" });
      SemanticResultValue yesValue =
          new SemanticResultValue(yesChoices, (bool)true);
      Choices noChoices = new Choices(new string[] { "no", "nope", "neah" });
      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";

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

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

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

    // 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");
    }

    // 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.
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
RecognizerUpdateReached
UnloadAllGrammars
UnloadGrammar
LoadGrammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


QueryRecognizerSetting Method

[image]

SpeechRecognitionEngine..::..QueryRecognizerSetting Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Returns the values of the current settings for a speech recognition engine managed by a SpeechRecognitionEngine object.

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

Syntax

Visual Basic (Declaration)
Public Function QueryRecognizerSetting ( _
    settingName As String _
) As Object
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim settingName As String
Dim returnValue As Object

returnValue = instance.QueryRecognizerSetting(settingName)
C#
public Object QueryRecognizerSetting(
    string settingName
)

Parameters

settingName
Type: System..::..String

Return Value

Type: System..::..Object

The value of the setting.

Remarks

Recognizer settings can contain string, 64-bit integer, or memory address data. The following table describes the settings that are defined for a recognizer that complies with the Microsoft Speech Platform SDK 11. The following settings must have the same range for each recognizer that supports the setting. A recognizer that complies with the Speech Platform SDK 11 is not required to support these settings and can support other settings.

Name

Description

ResourceUsage

Specifies the recognizer's CPU consumption. The range is from 0 to 100. The default value is 50.

HighConfidenceThreshold

Not used by Microsoft.Speech. The value specified here is effectively the same as any value above the LowConfidenceThreshold. The range is from 0 to 100, inclusive. The default value is 80.

NormalConfidenceThreshold

Not used by Microsoft.Speech. The value specified here is effectively the same as any value above the LowConfidenceThreshold. The range is from 0 to 100, inclusive. The default value is 50.

LowConfidenceThreshold

Not used by Microsoft.Speech. Separates the speech recognized confidence range from the speech rejected confidence range. The range is from 0 to 100, inclusive. The default value is 20.

CFGConfidenceRejectionThreshold

The speech recognition engine accepts full utterances with confidence scores above or equal to this threshold, and rejects full utterances with phrase confidence scores below this threshold. This property accepts the following values:

  • The value -1 causes the engine to use its default value.

  • A value in the range of 0-100 sets the phrase confidence rejection threshold to the specified value.

If this value is set to 0, the speech recognition accepts all utterances. If this value is set to 100, the speech recognition engine rejects all utterances. This property is not to be confused with HighConfidenceThreshold, NormalConfidenceThreshold, or LowConfidenceThreshold, which are used to determine how any given confidence value is categorized (low, medium, or high).

ResponseSpeed

Indicates the length of silence at the end of unambiguous input before the speech recognizer completes a recognition operation. The range is from 0 to 10,000 milliseconds (ms). This setting corresponds to the recognizer's EndSilenceTimeout property.

ComplexResponseSpeed

Indicates the length of silence at the end of ambiguous input before the speech recognizer completes a recognition operation. The range is from 0 to 10,000 ms. This setting corresponds to the recognizer's EndSilenceTimeoutAmbiguous property.

EngineThreadPriority

Sets the priority of the engine thread(s). The range of permitted values is defined by the OS.

  • The minimum value is min(THREAD_PRIORITY_IDLE,THREAD_PRIORITY_HIGHEST)

  • The maximum value is max(THREAD_PRIORITY_IDLE,THREAD_PRIORITY_HIGHEST)

The values of these constants are in defined winbase.h.

AdaptationOn

Indicates whether adaptation of the acoustic model is on (value = 1) or off (value = 0). The default value is 1 (on).

PersistedBackgroundAdaptation

Indicates whether background adaptation is on (value = 1) or off (value = 0), and persists the setting in the registry. The default value is 1 (on).

AssumeCFGFromTrustedSource

Bypasses file integrity checks when loading a CFG, to reduce load time. This should *only* be used by applications that can guarantee that the CFG they are loading has previously been compiled by the application (or by another application it trusts) and has been stored in a secure location where it could not be edited by a malicious agent. This property accepts the following values:

  • Value set to 0 = AssumeCFGFromTrustedSource is OFF

  • Value set to 1 = AssumeCFGFromTrustedSource is ON

The threshold values are used to divide a confidence scale into four portions: rejected, low, medium, and high. This is to allow assigning of a text value to confidence scores in defined ranges. Microsoft.Speech does not distinguish between high, normal, and low confidence levels, and does not assign text values to ranges of confidence scores. Modifying the values for HighConfidenceThreshold and NormalConfidenceThreshold, and LowConfidenceThreshold will have no effect on recognition.

To dictate the confidence level at which higher values indicate recognized speech, and equal or lower values indicate rejected speech, use CFGConfidenceRejectionThreshold. Recognition results with confidence values greater than or equal to the CFGConfidenceRejectionThreshold trigger a SpeechRecognized event. Recognition results with confidence values less than the CFGConfidenceRejectionThreshold trigger a SpeechRecognitionRejected event.

The confidence scores assigned to words and phrases by the recognition engine become the values of the RecognizedWordUnit..::..Confidence and RecognizedPhrase..::..Confidence properties, and are converted to range from 0 to 1, instead of from 0-100.

To modify one of the recognizer's settings, use one of the UpdateRecognizerSetting methods.

You can modify how the speech recognition responds to non-speech input using the BabbleTimeout, InitialSilenceTimeout, EndSilenceTimeout, and EndSilenceTimeoutAmbiguous properties.

Examples

The following example is part of a console application that outputs the values for a number of the settings defined for the recognizer that supports the en-US locale.

Copy image Copy Code
using System;
using System.Globalization;
using Microsoft.Speech.Recognition;

namespace RecognizerSettings
{
  class Program
  {
    static readonly string[] settings = new string[] {
      "ResourceUsage",
      "HighConfidenceThreshold",
      "NormalConfidenceThreshold",
      "LowConfidenceThreshold",
      "ResponseSpeed",
      "ComplexResponseSpeed",
      "AdaptationOn",
      "PersistedBackgroundAdaptation"
    };

    static void Main(string[] args)
    {
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US")))
      {
        Console.WriteLine("Settings for recognizer {0}:",
          recognizer.RecognizerInfo.Name);
        Console.WriteLine();

        foreach (string setting in settings)
        {
          try
          {
            object value = recognizer.QueryRecognizerSetting(setting);
            Console.WriteLine("  {0,-30} = {1}", setting, value);
          }
          catch
          {
            Console.WriteLine("  {0,-30} is not supported by this recognizer.",
              setting);
          }
        }
      }
      Console.WriteLine();

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

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Recognize Method

[image] [image]

SpeechRecognitionEngine..::..Recognize Method
SpeechRecognitionEngine Class See Also Send Feedback

Starts a synchronous speech recognition operation.

Overload List

 | Name | Description
Public method | Recognize()()()() | Performs a synchronous speech recognition operation.
Public method | Recognize(TimeSpan) | Performs a synchronous speech recognition operation with a specified initial silence timeout period.
Top

Remarks

These methods perform a single, synchronous recognition operation. The recognizer performs this operation against its loaded and enabled speech recognition grammars.

During a call to this method, the recognizer can raise the following events:

  • SpeechDetected. Raised when the recognizer detects input that it can identify as speech.

  • SpeechHypothesized. Raised when input creates an ambiguous match with one of the active grammars.

  • SpeechRecognitionRejected or SpeechRecognized. Raised when the recognizer finalizes a recognition operation.

The recognizer does not raise the RecognizeCompleted event when using one of the Recognize()()()() methods.

The Recognize methods return a RecognitionResult object, or nullNothingnullptrunita null reference (Nothing in Visual Basic) if the operation is not successful.

A synchronous recognition operation can fail for the following reasons:

  • Speech is not detected before the timeout intervals expire for the BabbleTimeout or InitialSilenceTimeout properties, or for the initialSilenceTimeout parameter of the Recognize(TimeSpan) method.

  • The recognition engine detects speech but finds no matches in any of its loaded and enabled Grammar objects.

To modify how the recognizer handles the timing of speech or silence with respect to recognition, use the BabbleTimeout, InitialSilenceTimeout, EndSilenceTimeout, and EndSilenceTimeoutAmbiguous properties.

The SpeechRecognitionEngine must have at least one Grammar object loaded before performing recognition. To load a speech recognition grammar, use the LoadGrammar or LoadGrammarAsync method.

To perform asynchronous recognition, use one of the RecognizeAsync methods.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Recognize Method

[image]

SpeechRecognitionEngine..::..Recognize Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Performs a synchronous speech recognition operation.

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

Syntax

Visual Basic (Declaration)
Public Function Recognize As RecognitionResult
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim returnValue As RecognitionResult

returnValue = instance.Recognize()
C#
public RecognitionResult Recognize()

Return Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

The recognition result for the input, or nullNothingnullptrunita null reference (Nothing in Visual Basic) if the operation is not successful.

Remarks

This method performs a single, synchronous recognition operation. The recognizer performs this operation against its loaded and enabled speech recognition grammars.

During a call to this method, the recognizer can raise the following events:

  • SpeechDetected. Raised when the recognizer detects input that it can identify as speech.

  • SpeechHypothesized. Raised when input creates an ambiguous match with one of the active grammars.

  • SpeechRecognitionRejected or SpeechRecognized. Raised when the recognizer finalizes a recognition operation.

The recognizer does not raise the RecognizeCompleted event when using this method.

The Recognize()()()() method returns a RecognitionResult object, or nullNothingnullptrunita null reference (Nothing in Visual Basic) if the operation is not successful.

A synchronous recognition operation can fail for the following reasons:

  • Speech is not detected before the timeout intervals expire for the BabbleTimeout or InitialSilenceTimeout properties.

  • The recognition engine detects speech but finds no matches in any of its loaded and enabled Grammar objects.

To perform asynchronous recognition, use one of the RecognizeAsync methods.

Examples

The following example shows part of a console application that demonstrates basic speech recognition. The example creates a speech recognition grammar for choosing cities for a flight. It then constructs a Grammar object from the grammar, loads it into the SpeechRecognitionEngine object, and performs one recognition operation.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

namespace SynchronousRecognition
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an in-process speech recognizer for the en-US locale.
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(
          new System.Globalization.CultureInfo("en-US")))
      {

        // Create a grammar for choosing cities for a flight.
        Choices cities = new Choices(new string[]
        { "Los Angeles", "New York", "Chicago", "San Francisco", "Miami", "Dallas" });

        GrammarBuilder gb = new GrammarBuilder();
        gb.Append("I want to fly from");
        gb.Append(cities);
        gb.Append("to");
        gb.Append(cities);

        // Construct a Grammar object and load it to the recognizer.
        Grammar cityChooser = new Grammar(gb);
        cityChooser.Name = ("City Chooser");
        recognizer.LoadGrammarAsync(cityChooser);

        // Configure input to the speech recognizer.
        recognizer.SetInputToDefaultAudioDevice();

        // Start synchronous speech recognition.
        RecognitionResult result = recognizer.Recognize();

        if (result != null)
        {
          Console.WriteLine("Recognized text = {0}", result.Text);
        }
        else
        {
          Console.WriteLine("No recognition result available.");
        }
      }

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

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Recognize Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Recognize Method (TimeSpan)

[image]

SpeechRecognitionEngine..::..Recognize Method (TimeSpan)
SpeechRecognitionEngine Class Example See Also Send Feedback

Performs a synchronous speech recognition operation with a specified initial silence timeout period.

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

Syntax

Visual Basic (Declaration)
Public Function Recognize ( _
    initialSilenceTimeout As TimeSpan _
) As RecognitionResult
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim initialSilenceTimeout As TimeSpan
Dim returnValue As RecognitionResult

returnValue = instance.Recognize(initialSilenceTimeout)
C#
public RecognitionResult Recognize(
    TimeSpan initialSilenceTimeout
)

Parameters

initialSilenceTimeout
Type: System..::..TimeSpan

The interval of time a speech recognizer accepts input containing only silence before finalizing recognition.

Return Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

The recognition result for the input, or nullNothingnullptrunita null reference (Nothing in Visual Basic) if the operation is not successful.

Remarks

If the speech recognition engine detects speech within the time interval specified by initialSilenceTimeout argument, Recognize(TimeSpan) performs a single recognition operation and then terminates. The initialSilenceTimeout parameter supersedes the recognizer's InitialSilenceTimeout property.

During a call to this method, the recognizer can raise the following events:

  • SpeechDetected. Raised when the recognizer detects input that it can identify as speech.

  • SpeechHypothesized. Raised when input creates an ambiguous match with one of the active grammars.

  • SpeechRecognitionRejected or SpeechRecognized. Raised when the recognizer finalizes a recognition operation.

The recognizer does not raise the RecognizeCompleted event when using this method.

The Recognize()()()() method returns a RecognitionResult object, or nullNothingnullptrunita null reference (Nothing in Visual Basic) if the operation is not successful.

A synchronous recognition operation can fail for the following reasons:

  • Speech is not detected before the timeout intervals expire for the BabbleTimeout or for the initialSilenceTimeout parameter.

  • The recognition engine detects speech but finds no matches in any of its loaded and enabled Grammar objects.

To perform asynchronous recognition, use one of the RecognizeAsync methods.

Examples

The following example shows part of a console application that demonstrates basic speech recognition. The example creates a speech recognition grammar for choosing cities for a flight. It then constructs a Grammar object from the grammar, loads it into the SpeechRecognitionEngine object. The Recognize(TimeSpan) method specifies a timeout interval of five seconds, after which it will terminate the single recognition operation.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

namespace SynchronousRecognition
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an in-process speech recognizer for the en-US locale.
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(
          new System.Globalization.CultureInfo("en-US")))
      {

        // Create a grammar for choosing cities for a flight.
        Choices cities = new Choices(new string[]
        { "Los Angeles", "New York", "Chicago", "San Francisco", "Miami", "Dallas" });

        GrammarBuilder gb = new GrammarBuilder();
        gb.Append("I want to fly from");
        gb.Append(cities);
        gb.Append("to");
        gb.Append(cities);

        // Construct a Grammar object and load it to the recognizer.
        Grammar cityChooser = new Grammar(gb);
        cityChooser.Name = ("City Chooser");
        recognizer.LoadGrammarAsync(cityChooser);

        // Configure input to the speech recognizer.
        recognizer.SetInputToDefaultAudioDevice();

        // Start synchronous speech recognition.
        RecognitionResult result = recognizer.Recognize(TimeSpan.FromSeconds(5));

        if (result != null)
        {
          Console.WriteLine("Recognized text = {0}", result.Text);
        }
        else
        {
          Console.WriteLine("No recognition result available.");
        }
      }

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

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Recognize Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeAsync Method

[image] [image]

SpeechRecognitionEngine..::..RecognizeAsync Method
SpeechRecognitionEngine Class See Also Send Feedback

Starts an asynchronous speech recognition operation.

Overload List

 | Name | Description
Public method | RecognizeAsync()()()() | Performs a single, asynchronous speech recognition operation.
Public method | RecognizeAsync(RecognizeMode) | Performs one or more asynchronous speech recognition operations.
Top

Remarks

These methods perform single or multiple, asynchronous recognition operations. The recognizer performs each operation against its loaded and enabled speech recognition grammars.

During a call to this method, the recognizer can raise the following events:

  • SpeechDetected. Raised when the recognizer detects input that it can identify as speech.

  • SpeechHypothesized. Raised when input creates an ambiguous match with one of the active grammars.

  • SpeechRecognitionRejected or SpeechRecognized. Raised when the recognizer finalizes a recognition operation.

  • RecognizeCompleted. Raised when a RecognizeAsync()()()() operation finishes.

To retrieve the result of an asynchronous recognition operation, attach an event handler to the recognizer's SpeechRecognized event. The recognizer raises this event whenever it successfully completes a synchronous or asynchronous recognition operation. If recognition was not successful, the Result property on RecognizeCompletedEventArgs object, which you can access in the handler for the RecognizeCompleted event, will be nullNothingnullptrunita null reference (Nothing in Visual Basic).

An asynchronous recognition operation can fail for the following reasons:

  • Speech is not detected before the timeout intervals expire for the BabbleTimeout or InitialSilenceTimeout properties.

  • The recognition engine detects speech but finds no matches in any of its loaded and enabled Grammar objects.

The SpeechRecognitionEngine must have at least one Grammar object loaded before performing recognition. To load a speech recognition grammar, use the LoadGrammar or LoadGrammarAsync method.

To modify how the recognizer handles the timing of speech or silence with respect to recognition, use the BabbleTimeout, InitialSilenceTimeout, EndSilenceTimeout, and EndSilenceTimeoutAmbiguous properties.

To perform synchronous recognition, use one of the Recognize methods.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeAsync Method

[image]

SpeechRecognitionEngine..::..RecognizeAsync Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Performs a single, asynchronous speech recognition operation.

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

Syntax

Visual Basic (Declaration)
Public Sub RecognizeAsync
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine

instance.RecognizeAsync()
C#
public void RecognizeAsync()

Remarks

This method performs a single, asynchronous recognition operation. The recognizer performs the operation against its loaded and enabled speech recognition grammars.

During a call to this method, the recognizer can raise the following events:

  • SpeechDetected. Raised when the recognizer detects input that it can identify as speech.

  • SpeechHypothesized. Raised when input creates an ambiguous match with one of the active grammars.

  • SpeechRecognitionRejected or SpeechRecognized. Raised when the recognizer finalizes a recognition operation.

  • RecognizeCompleted. Raised when a RecognizeAsync()()()() operation finishes.

To retrieve the result of an asynchronous recognition operation, attach an event handler to the recognizer's SpeechRecognized event. The recognizer raises this event whenever it successfully completes a synchronous or asynchronous recognition operation. If recognition was not successful, the Result property on RecognizeCompletedEventArgs object, which you can access in the handler for the RecognizeCompleted event, will be nullNothingnullptrunita null reference (Nothing in Visual Basic).

An asynchronous recognition operation can fail for the following reasons:

  • Speech is not detected before the timeout intervals expire for the BabbleTimeout or InitialSilenceTimeout properties.

  • The recognition engine detects speech but finds no matches in any of its loaded and enabled Grammar objects.

To perform synchronous recognition, use one of the Recognize methods.

Examples

The following example shows part of a console application that demonstrates basic speech recognition. The example creates a speech recognition grammar for choosing cities for a flight. It then constructs a Grammar object from the grammar, loads it into the SpeechRecognitionEngine object, and performs one recognition operation. Event handlers write the results of the recognition operation to the console.

Copy image Copy Code
using System;
using System.Globalization;
using Microsoft.Speech.Recognition;
using System.Threading;

namespace AsynchronousRecognition
{
  class Program
  {
    // Indicate whether asynchronous recognition is complete.
    static bool completed;

    static void Main(string[] args)
    {
      // Construct a SpeechRecognitionEngine object.
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(new CultureInfo("en-US")))
      {
        // Create a grammar for choosing cities for a flight.
        Choices cities = new Choices(new string[]
        { "Los Angeles", "New York", "Chicago", "San Francisco", "Miami", "Dallas" });

        GrammarBuilder gb = new GrammarBuilder();
        gb.Append("I want to fly from");
        gb.Append(cities);
        gb.Append("to");
        gb.Append(cities);

        // Construct a Grammar object and load it to the recognizer.
        Grammar cityChooser = new Grammar(gb);
        cityChooser.Name = ("City Chooser");
        recognizer.LoadGrammarAsync(cityChooser);

        // Attach event handlers.
        recognizer.SpeechDetected +=
          new EventHandler<SpeechDetectedEventArgs>(
            SpeechDetectedHandler);
        recognizer.SpeechHypothesized +=
          new EventHandler<SpeechHypothesizedEventArgs>(
            SpeechHypothesizedHandler);
        recognizer.SpeechRecognitionRejected +=
          new EventHandler<SpeechRecognitionRejectedEventArgs>(
            SpeechRecognitionRejectedHandler);
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(
            SpeechRecognizedHandler);
        recognizer.RecognizeCompleted +=
          new EventHandler<RecognizeCompletedEventArgs>(
            RecognizeCompletedHandler);

        // Assign input to the recognizer and start an asynchronous
        // recognition operation.
        recognizer.SetInputToDefaultAudioDevice();

        completed = false;
        Console.WriteLine("Starting asynchronous recognition...");
        recognizer.RecognizeAsync();

        // Wait for the operation to complete.
        while (!completed)
        {
          Thread.Sleep(333);
        }
        Console.WriteLine("Done.");
      }

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

    // Handle the SpeechDetected event.
    static void SpeechDetectedHandler(object sender, SpeechDetectedEventArgs e)
    {
      Console.WriteLine(" In SpeechDetectedHandler:");
      Console.WriteLine(" - AudioPosition = {0}", e.AudioPosition);
    }

    // Handle the SpeechHypothesized event.
    static void SpeechHypothesizedHandler(
      object sender, SpeechHypothesizedEventArgs e)
    {
      Console.WriteLine(" In SpeechHypothesizedHandler:");

      string grammarName = "<not available>";
      string resultText = "<not available>";
      if (e.Result != null)
      {
        if (e.Result.Grammar != null)
        {
          grammarName = e.Result.Grammar.Name;
        }
        resultText = e.Result.Text;
      }

      Console.WriteLine(" - Grammar Name = {0}; Result Text = {1}",
        grammarName, resultText);
    }

    // Handle the SpeechRecognitionRejected event.
    static void SpeechRecognitionRejectedHandler(
      object sender, SpeechRecognitionRejectedEventArgs e)
    {
      Console.WriteLine(" In SpeechRecognitionRejectedHandler:");

      string grammarName = "<not available>";
      string resultText = "<not available>";
      if (e.Result != null)
      {
        if (e.Result.Grammar != null)
        {
          grammarName = e.Result.Grammar.Name;
        }
        resultText = e.Result.Text;
      }

      Console.WriteLine(" - Grammar Name = {0}; Result Text = {1}",
        grammarName, resultText);
    }

    // Handle the SpeechRecognized event.
    static void SpeechRecognizedHandler(
      object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine(" In SpeechRecognizedHandler.");

      string grammarName = "<not available>";
      string resultText = "<not available>";
      if (e.Result != null)
      {
        if (e.Result.Grammar != null)
        {
          grammarName = e.Result.Grammar.Name;
        }
        resultText = e.Result.Text;
      }

      Console.WriteLine(" - Grammar Name = {0}; Result Text = {1}",
        grammarName, resultText);
    }

    // Handle the RecognizeCompleted event.
    static void RecognizeCompletedHandler(
      object sender, RecognizeCompletedEventArgs e)
    {
      Console.WriteLine(" In RecognizeCompletedHandler.");

      if (e.Error != null)
      {
        Console.WriteLine(
          " - Error occurred during recognition: {0}", e.Error);
        return;
      }
      if (e.InitialSilenceTimeout || e.BabbleTimeout)
      {
        Console.WriteLine(
          " - BabbleTimeout = {0}; InitialSilenceTimeout = {1}",
          e.BabbleTimeout, e.InitialSilenceTimeout);
        return;
      }
      if (e.InputStreamEnded)
      {
        Console.WriteLine(
          " - AudioPosition = {0}; InputStreamEnded = {1}",
          e.AudioPosition, e.InputStreamEnded);
      }
      if (e.Result != null)
      {
        Console.WriteLine(
          " - Grammar = {0}; Text = {1}; Confidence = {2}",
          e.Result.Grammar.Name, e.Result.Text, e.Result.Confidence);
        Console.WriteLine(" - AudioPosition = {0}", e.AudioPosition);
      }
      else
      {
        Console.WriteLine(" - No result.");
      }

      completed = true;
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
RecognizeAsync Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeAsync Method (RecognizeMode)

[image]

SpeechRecognitionEngine..::..RecognizeAsync Method (RecognizeMode)
SpeechRecognitionEngine Class Example See Also Send Feedback

Performs one or more asynchronous speech recognition operations.

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

Syntax

Visual Basic (Declaration)
Public Sub RecognizeAsync ( _
    mode As RecognizeMode _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim mode As RecognizeMode

instance.RecognizeAsync(mode)
C#
public void RecognizeAsync(
    RecognizeMode mode
)

Parameters

mode
Type: Microsoft.Speech.Recognition..::..RecognizeMode

Indicates whether to perform one or multiple recognition operations.

Remarks

If mode is Multiple, the recognizer continues performing asynchronous recognition operations until theRecognizeAsyncCancel or RecognizeAsyncStop method is called.

During a call to this method, the recognizer can raise the following events:

  • SpeechDetected. Raised when the recognizer detects input that it can identify as speech.

  • SpeechHypothesized. Raised when input creates an ambiguous match with one of the active grammars.

  • SpeechRecognitionRejected or SpeechRecognized. Raised when the recognizer finalizes a recognition operation.

  • RecognizeCompleted. Raised when a RecognizeAsync()()()() operation finishes.

To retrieve the result of an asynchronous recognition operation, attach an event handler to the recognizer's SpeechRecognized event. The recognizer raises this event whenever it successfully completes a synchronous or asynchronous recognition operation. If recognition was not successful, the Result property on RecognizeCompletedEventArgs object, which you can access in the handler for the RecognizeCompleted event, will be nullNothingnullptrunita null reference (Nothing in Visual Basic).

An asynchronous recognition operation can fail for the following reasons:

  • Speech is not detected before the timeout intervals expire for the BabbleTimeout or InitialSilenceTimeout properties.

  • The recognition engine detects speech but finds no matches in any of its loaded and enabled Grammar objects.

To perform synchronous recognition, use one of the Recognize methods.

Examples

The following example shows part of a console application that demonstrates basic speech recognition. The example creates a speech recognition grammar for choosing cities for a flight. It then constructs a Grammar object from the grammar, loads it into the SpeechRecognitionEngine object, and performs performs multiple asynchronous recognition operations. The asynchronous operations are cancelled after 30 seconds. Event handlers are included to demonstrate the events that the recognizer raises during the operation.

Copy image Copy Code
using System;
using System.Globalization;
using Microsoft.Speech.Recognition;
using System.Threading;

namespace AsynchronousRecognition
{
  class Program
  {
    // Indicate whether asynchronous recognition is complete.
    static bool completed;

    static void Main(string[] args)
    {
      // Create an in-process speech recognizer.
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(new CultureInfo("en-US")))
      {
        // Create a grammar for choosing cities for a flight.
        Choices cities = new Choices(new string[]
        { "Los Angeles", "New York", "Chicago", "San Francisco", "Miami", "Dallas" });

        GrammarBuilder gb = new GrammarBuilder();
        gb.Append("I want to fly from");
        gb.Append(cities);
        gb.Append("to");
        gb.Append(cities);

        // Construct a Grammar object and load it to the recognizer.
        Grammar cityChooser = new Grammar(gb);
        cityChooser.Name = ("City Chooser");
        recognizer.LoadGrammarAsync(cityChooser);

        // Attach event handlers.
        recognizer.SpeechDetected +=
          new EventHandler<SpeechDetectedEventArgs>(
            SpeechDetectedHandler);
        recognizer.SpeechHypothesized +=
          new EventHandler<SpeechHypothesizedEventArgs>(
            SpeechHypothesizedHandler);
        recognizer.SpeechRecognitionRejected +=
          new EventHandler<SpeechRecognitionRejectedEventArgs>(
            SpeechRecognitionRejectedHandler);
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(
            SpeechRecognizedHandler);
        recognizer.RecognizeCompleted +=
          new EventHandler<RecognizeCompletedEventArgs>(
            RecognizeCompletedHandler);

        // Assign input to the recognizer and start asynchronous
        // recognition.
        recognizer.SetInputToDefaultAudioDevice();

        completed = false;
        Console.WriteLine("Starting asynchronous recognition...");
        recognizer.RecognizeAsync(RecognizeMode.Multiple);

        // Wait 30 seconds, and then cancel asynchronous recognition.
        Thread.Sleep(TimeSpan.FromSeconds(30));
        recognizer.RecognizeAsyncCancel();

        // Wait for the operation to complete.
        while (!completed)
        {
          Thread.Sleep(333);
        }
        Console.WriteLine("Done.");
      }

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

    // Handle the SpeechDetected event.
    static void SpeechDetectedHandler(object sender, SpeechDetectedEventArgs e)
    {
      Console.WriteLine(" In SpeechDetectedHandler:");
      Console.WriteLine(" - AudioPosition = {0}", e.AudioPosition);
    }

    // Handle the SpeechHypothesized event.
    static void SpeechHypothesizedHandler(
      object sender, SpeechHypothesizedEventArgs e)
    {
      Console.WriteLine(" In SpeechHypothesizedHandler:");

      string grammarName = "<not available>";
      string resultText = "<not available>";
      if (e.Result != null)
      {
        if (e.Result.Grammar != null)
        {
          grammarName = e.Result.Grammar.Name;
        }
        resultText = e.Result.Text;
      }

      Console.WriteLine(" - Grammar Name = {0}; Result Text = {1}",
        grammarName, resultText);
    }

    // Handle the SpeechRecognitionRejected event.
    static void SpeechRecognitionRejectedHandler(
      object sender, SpeechRecognitionRejectedEventArgs e)
    {
      Console.WriteLine(" In SpeechRecognitionRejectedHandler:");

      string grammarName = "<not available>";
      string resultText = "<not available>";
      if (e.Result != null)
      {
        if (e.Result.Grammar != null)
        {
          grammarName = e.Result.Grammar.Name;
        }
        resultText = e.Result.Text;
      }

      Console.WriteLine(" - Grammar Name = {0}; Result Text = {1}",
        grammarName, resultText);
    }

    // Handle the SpeechRecognized event.
    static void SpeechRecognizedHandler(
      object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine(" In SpeechRecognizedHandler.");

      string grammarName = "<not available>";
      string resultText = "<not available>";
      if (e.Result != null)
      {
        if (e.Result.Grammar != null)
        {
          grammarName = e.Result.Grammar.Name;
        }
        resultText = e.Result.Text;
      }

      Console.WriteLine(" - Grammar Name = {0}; Result Text = {1}",
        grammarName, resultText);
    }

    // Handle the RecognizeCompleted event.
    static void RecognizeCompletedHandler(
      object sender, RecognizeCompletedEventArgs e)
    {
      Console.WriteLine(" In RecognizeCompletedHandler.");

      if (e.Error != null)
      {
        Console.WriteLine(
          " - Error occurred during recognition: {0}", e.Error);
        return;
      }
      if (e.InitialSilenceTimeout || e.BabbleTimeout)
      {
        Console.WriteLine(
          " - BabbleTimeout = {0}; InitialSilenceTimeout = {1}",
          e.BabbleTimeout, e.InitialSilenceTimeout);
        return;
      }
      if (e.InputStreamEnded)
      {
        Console.WriteLine(
          " - AudioPosition = {0}; InputStreamEnded = {1}",
          e.AudioPosition, e.InputStreamEnded);
      }
      if (e.Result != null)
      {
        Console.WriteLine(
          " - Grammar = {0}; Text = {1}; Confidence = {2}",
          e.Result.Grammar.Name, e.Result.Text, e.Result.Confidence);
        Console.WriteLine(" - AudioPosition = {0}", e.AudioPosition);
      }
      else
      {
        Console.WriteLine(" - No result.");
      }

      completed = true;
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
RecognizeAsync Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeAsyncCancel Method

[image]

SpeechRecognitionEngine..::..RecognizeAsyncCancel Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Terminates asynchronous recognition without waiting for the current recognition operation to complete.

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

Syntax

Visual Basic (Declaration)
Public Sub RecognizeAsyncCancel
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine

instance.RecognizeAsyncCancel()
C#
public void RecognizeAsyncCancel()

Remarks

This method immediately finalizes asynchronous recognition. If the current asynchronous recognition operation is receiving input, the input is truncated and the operation completes with the existing input. The recognizer raises the RecognizeCompleted or EmulateRecognizeCompleted event when an asynchronous operation is canceled, and sets the Cancelled property of the RecognizeCompletedEventArgs to true. This method cancels asynchronous operations initiated by the RecognizeAsync and EmulateRecognizeAsync methods.

To stop asynchronous recognition without truncating the input, use the RecognizeAsyncStop()()()() method.

Examples

The following example shows a graphical user interface which uses a button to start and stop a SpeechRecognitionEngine. When the user clicks the start/stop button while the SpeechRecognitionEngineis running, either RecognizeAsyncCancel or RecognizeAsyncStop is called depending on the state of the application.

Copy image Copy Code
private void _startRecogButton_Click(object sender, EventArgs eventArgs) {
    if (_startRecogButton.Text == "Start Speech Recognition") { //Toggle Speech Recognition on
        _startRecogButton.Text = "Stop Speech Recognition";
        if (_useMultiple) {
            _recognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
        } else {
            _recognitionEngine.RecognizeAsync(RecognizeMode.Single);
        }
    } else {                                                      //Toggle Speech Recognition off
        _startRecogButton.Text = "Start Speech Recognition";
        if (_friendlyStop) {
            _recognitionEngine.RecognizeAsyncStop(); //Stop after current phrase is finished.
        } else {
            _recognitionEngine.RecognizeAsyncCancel(); //Stop before current phrase is finished.
        }

    }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeAsyncStop Method

[image]

SpeechRecognitionEngine..::..RecognizeAsyncStop Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Stops asynchronous recognition after the current recognition operation completes.

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

Syntax

Visual Basic (Declaration)
Public Sub RecognizeAsyncStop
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine

instance.RecognizeAsyncStop()
C#
public void RecognizeAsyncStop()

Remarks

This method finalizes asynchronous recognition without truncating input. If the current asynchronous recognition operation is receiving input, the recognizer continues accepting input until the current recognition operation is completed. The recognizer raises the RecognizeCompleted or EmulateRecognizeCompleted event when an asynchronous operation is stopped, and sets the Cancelled property of the RecognizeCompletedEventArgs to true. This method stops asynchronous operations initiated by the RecognizeAsync and EmulateRecognizeAsync methods.

To stop asynchronous recognition without truncating the input, use the RecognizeAsyncCancel()()()() method.

Examples

The following example shows a graphical user interface which uses a button to start and stop a SpeechRecognitionEngine. When the user clicks the start/stop button while the SpeechRecognitionEngineis running, either RecognizeAsyncCancel or RecognizeAsyncStop is called depending on the state of the application.

Copy image Copy Code
private void _startRecogButton_Click(object sender, EventArgs eventArgs) {
    if (_startRecogButton.Text == "Start Speech Recognition") { //Toggle Speech Recognition on
        _startRecogButton.Text = "Stop Speech Recognition";
        if (_useMultiple) {
            _recognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
        } else {
            _recognitionEngine.RecognizeAsync(RecognizeMode.Single);
        }
    } else {                                                      //Toggle Speech Recognition off
        _startRecogButton.Text = "Start Speech Recognition";
        if (_friendlyStop) {
            _recognitionEngine.RecognizeAsyncStop(); //Stop after current phrase is finished.
        } else {
            _recognitionEngine.RecognizeAsyncCancel(); //Stop before current phrase is finished.
        }

    }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RequestRecognizerUpdate Method

[image] [image]

SpeechRecognitionEngine..::..RequestRecognizerUpdate Method
SpeechRecognitionEngine Class See Also Send Feedback

Requests that the recognizer pauses to update its state.

Overload List

 | Name | Description
Public method | RequestRecognizerUpdate()()()() | Requests that the recognizer pauses to update its state.
Public method | RequestRecognizerUpdate(Object) | Requests that the recognizer pauses to update its state and provides a user token for the associated event.
Public method | RequestRecognizerUpdate(Object, TimeSpan) | Requests that the recognizer pauses to update its state and provides an offset and a user token for the associated event.
Top

Remarks

Use this method to synchronize changes to the recognizer. For example, if you load or unload a speech recognition grammar while the recognizer is processing input, use this method and the RecognizerUpdateReached event to synchronize your application behavior with the state of the recognizer.

When this method is called, the recognizer pauses or completes asynchronous operations and generates a RecognizerUpdateReached event. A RecognizerUpdateReached event handler can then modify the state of the recognizer in between recognition operations. When handling RecognizerUpdateReached events, a speech recognition engine pauses until the event handler returns.

Note Note

If the input to the recognizer is changed before the recognizer raises the RecognizerUpdateReached event, the request is discarded.

When this method is called:

  • If the recognizer is not processing input, the recognizer immediately generates the RecognizerUpdateReached event.

  • If the recognizer is processing input that consists of silence or background noise, the recognizer pauses the recognition operation and generates the RecognizerUpdateReached event.

  • If the recognizer is processing input that does not consist of silence or background noise, the recognizer completes the recognition operation and then generates the RecognizerUpdateReached event.

While the recognizer is handling the RecognizerUpdateReached event:

  • The recognizer does not process input, and the value of the RecognizerAudioPosition property remains the same.

  • The recognizer continues to collect input, and the value of the AudioPosition property can change.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RequestRecognizerUpdate Method

[image]

SpeechRecognitionEngine..::..RequestRecognizerUpdate Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Requests that the recognizer pauses to update its state.

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

Syntax

Visual Basic (Declaration)
Public Sub RequestRecognizerUpdate
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine

instance.RequestRecognizerUpdate()
C#
public void RequestRecognizerUpdate()

Remarks

When the recognizer generates the RecognizerUpdateReached event, the UserToken property of the RecognizerUpdateReachedEventArgs is nullNothingnullptrunita null reference (Nothing in Visual Basic).

To provide a user token, use the RequestRecognizerUpdate(Object) or RequestRecognizerUpdate(Object, TimeSpan) method. To specify an audio position offset, use the RequestRecognizerUpdate(Object, TimeSpan) method.

Examples

The following example shows a console application that loads and unloads Grammar objects. The application uses the RequestRecognizerUpdate()()()() method to request the speech recognition engine to pause so it can receive an update. The application then loads or unloads a Grammar object.

At each update, a handler for RecognizerUpdateReached event writes the name and status of the currently loaded Grammar objects to the console. As grammars are loaded and unloaded, the application first recognizes the names of farm animals, then the names of farm animals and the names of fruits, then only the names of fruits.

Copy image Copy Code
using System;
using System.Speech.Recognition;
using System.Collections.Generic;
using System.Threading;

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

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

        // Create the first grammar - Farm.
        Choices animals = new Choices(new string[] { "cow", "pig", "goat" });
        GrammarBuilder farm = new GrammarBuilder(animals);
        Grammar farmAnimals = new Grammar(farm);
        farmAnimals.Name = "Farm";

        // Create the second grammar - Fruit.
        Choices fruit = new Choices(new string[] { "apples", "peaches", "oranges" });
        GrammarBuilder favorite = new GrammarBuilder(fruit);
        Grammar favoriteFruit = new Grammar(favorite);
        favoriteFruit.Name = "Fruit";

        // Attach event handlers.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
        recognizer.RecognizerUpdateReached +=
          new EventHandler<RecognizerUpdateReachedEventArgs>(recognizer_RecognizerUpdateReached);
        recognizer.SpeechRecognitionRejected +=
          new EventHandler<SpeechRecognitionRejectedEventArgs>(recognizer_SpeechRecognitionRejected);

        // Load the Farm grammar.
        recognizer.LoadGrammar(farmAnimals);
        Console.WriteLine("Grammar Farm is loaded");

        // Start asynchronous, continuous recognition.
        recognizer.RecognizeAsync(RecognizeMode.Multiple);
        Console.WriteLine("Starting asynchronous, continuous recognition");

        // Pause to recognize farm animals.
        Thread.Sleep(7000);
        Console.WriteLine();

        // Request an update and load the Fruit grammar.
        recognizer.RequestRecognizerUpdate();
        recognizer.LoadGrammarAsync(favoriteFruit);
        Thread.Sleep(7000);

        // Request an update and unload the Farm grammar.
        recognizer.RequestRecognizerUpdate();
        recognizer.UnloadGrammar(farmAnimals);
        Thread.Sleep(7000);
      }

      // Keep the console window open.
      Console.WriteLine();
      Console.WriteLine("Press any key to exit...");
      Console.ReadKey();
    }

    // At the update, get the names and enabled status of the currently loaded grammars.
    public static void recognizer_RecognizerUpdateReached(
      object sender, RecognizerUpdateReachedEventArgs e)
    {
      Console.WriteLine();
      Console.WriteLine("Update reached:");
      Thread.Sleep(1000);

      string qualifier;
      List<Grammar> grammars = new List<Grammar>(recognizer.Grammars);
      foreach (Grammar g in grammars)
      {
        qualifier = (g.Enabled) ? "enabled" : "disabled";
        Console.WriteLine("  Grammar {0} is loaded and is {1}.",
        g.Name, qualifier);
      }
    }

    // Write the text of the recognized phrase to the console.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine("  Speech recognized: " + e.Result.Text);
    }

    // Write a message to the console when recognition fails.
    static void recognizer_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
    {
      Console.WriteLine("  Recognition attempt failed");
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
RequestRecognizerUpdate Overload
Microsoft.Speech.Recognition Namespace
RecognizerUpdateReached
RecognizerAudioPosition
AudioPosition
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RequestRecognizerUpdate Method (Object)

[image]

SpeechRecognitionEngine..::..RequestRecognizerUpdate Method (Object)
SpeechRecognitionEngine Class See Also Send Feedback

Requests that the recognizer pauses to update its state and provides a user token for the associated event.

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

Syntax

Visual Basic (Declaration)
Public Sub RequestRecognizerUpdate ( _
    userToken As Object _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim userToken As Object

instance.RequestRecognizerUpdate(userToken)
C#
public void RequestRecognizerUpdate(
    Object userToken
)

Parameters

userToken
Type: System..::..Object

User-defined information that contains information for the operation.

Remarks

When the recognizer generates the RecognizerUpdateReached event, the UserToken property of the RecognizerUpdateReachedEventArgs contains the value of the userToken parameter.

To specify an audio position offset, use the RequestRecognizerUpdate(Object, TimeSpan) method.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
RequestRecognizerUpdate Overload
Microsoft.Speech.Recognition Namespace
RecognizerUpdateReached
RecognizerAudioPosition
AudioPosition
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RequestRecognizerUpdate Method (Object, TimeSpan)

[image]

SpeechRecognitionEngine..::..RequestRecognizerUpdate Method (Object, TimeSpan)
SpeechRecognitionEngine Class See Also Send Feedback

Requests that the recognizer pauses to update its state and provides an offset and a user token for the associated event.

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

Syntax

Visual Basic (Declaration)
Public Sub RequestRecognizerUpdate ( _
    userToken As Object, _
    audioPositionAheadToRaiseUpdate As TimeSpan _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim userToken As Object
Dim audioPositionAheadToRaiseUpdate As TimeSpan

instance.RequestRecognizerUpdate(userToken, _
    audioPositionAheadToRaiseUpdate)
C#
public void RequestRecognizerUpdate(
    Object userToken,
    TimeSpan audioPositionAheadToRaiseUpdate
)

Parameters

userToken
Type: System..::..Object

User-defined information that contains information for the operation.

audioPositionAheadToRaiseUpdate
Type: System..::..TimeSpan

The offset from the current AudioPosition to delay the request.

Remarks

The recognizer does not initiate the recognizer update request until the recognizer's RecognizerAudioPosition equals the current AudioPosition plus audioPositionAheadToRaiseUpdate.

When the recognizer generates the RecognizerUpdateReached event, the UserToken property of the RecognizerUpdateReachedEventArgs contains the value of the userToken parameter.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
RequestRecognizerUpdate Overload
Microsoft.Speech.Recognition Namespace
RecognizerUpdateReached
RecognizerAudioPosition
AudioPosition
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetInputToAudioStream Method

[image]

SpeechRecognitionEngine..::..SetInputToAudioStream Method
SpeechRecognitionEngine Class See Also Send Feedback

Configures the SpeechRecognitionEngine object to receive input from an audio stream.

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

Syntax

Visual Basic (Declaration)
Public Sub SetInputToAudioStream ( _
    audioSource As Stream, _
    audioFormat As SpeechAudioFormatInfo _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim audioSource As Stream
Dim audioFormat As SpeechAudioFormatInfo

instance.SetInputToAudioStream(audioSource, _
    audioFormat)
C#
public void SetInputToAudioStream(
    Stream audioSource,
    SpeechAudioFormatInfo audioFormat
)

Parameters

audioSource
Type: System.IO..::..Stream

The audio input stream.

audioFormat
Type: Microsoft.Speech.AudioFormat..::..SpeechAudioFormatInfo

The format of the audio input.

Remarks

If the recognizer reaches the end of the input stream during a recognition operation, the recognition operation finalizes with the available input. Any subsequent recognition operations can generate an exception, unless you update the input to the recognizer.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SetInputToDefaultAudioDevice
SetInputToNull
SetInputToWaveFile
SetInputToWaveStream
RecognizeCompleted
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetInputToDefaultAudioDevice Method

[image]

SpeechRecognitionEngine..::..SetInputToDefaultAudioDevice Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Configures the SpeechRecognitionEngine object to receive input from the default audio device.

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

Syntax

Visual Basic (Declaration)
Public Sub SetInputToDefaultAudioDevice
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine

instance.SetInputToDefaultAudioDevice()
C#
public void SetInputToDefaultAudioDevice()

Examples

The following example shows part of a console application that demonstrates basic speech recognition and accepts speech input from the system's default audio device.

C# Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

      // Create a SpeechRecognitionEngine object for the default recognizer in the en-US locale.
      using (
      SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(
          new System.Globalization.CultureInfo("en-US")))
      {

        // Create a grammar for finding services in different cities.
        Choices services = new Choices(new string[] { "restaurants", "hotels", "gas stations" });
        Choices cities = new Choices(new string[] { "Seattle", "Boston", "Dallas" });

        GrammarBuilder findServices = new GrammarBuilder("Find");
        findServices.Append(services);
        findServices.Append("near");
        findServices.Append(cities);

        // Create a Grammar object from the GrammarBuilder and load it to the recognizer.
        Grammar servicesGrammar = new Grammar(findServices);
        recognizer.LoadGrammarAsync(servicesGrammar);

        // Add a handler for the speech recognized event.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

        // Configure the input to the speech recognizer.
        recognizer.SetInputToDefaultAudioDevice();

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

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

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

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SetInputToAudioStream
SetInputToNull
SetInputToWaveFile
SetInputToWaveStream
RecognizeCompleted
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetInputToNull Method

[image]

SpeechRecognitionEngine..::..SetInputToNull Method
SpeechRecognitionEngine Class See Also Send Feedback

Disables the input to the speech recognizer.

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

Syntax

Visual Basic (Declaration)
Public Sub SetInputToNull
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine

instance.SetInputToNull()
C#
public void SetInputToNull()

Remarks

Configure the SpeechRecognitionEngine object for no input when using the EmulateRecognize and EmulateRecognizeAsync methods, or when taking a recognition engine temporarily off line.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SetInputToAudioStream
SetInputToDefaultAudioDevice
SetInputToWaveFile
SetInputToWaveStream
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetInputToWaveFile Method

[image]

SpeechRecognitionEngine..::..SetInputToWaveFile Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Configures the SpeechRecognitionEngine object to receive input from a Waveform audio format (.wav) file.

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

Syntax

Visual Basic (Declaration)
Public Sub SetInputToWaveFile ( _
    path As String _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim path As String

instance.SetInputToWaveFile(path)
C#
public void SetInputToWaveFile(
    string path
)

Parameters

path
Type: System..::..String

The path of the file to use as input.

Remarks

If the recognizer reaches the end of the input file during a recognition operation, the recognition operation finalizes with the available input. Any subsequent recognition operations can generate an exception, unless you update the input to the recognizer.

The audio file can be in WMA format provided that both of the following conditions are met.

  • The WMA codec is available.

  • The target operating system has the appropriate Windows features installed or enabled.

    • A computer running Microsoft Windows Server 2003 x64 Editions must have Windows Media Format 9.5 Software Development Kit (SDK) x64 Edition installed.

    • A computer running Microsoft Windows Server 2008 or Windows Server 2008 R2 must have the Desktop Experience feature installed, as described in the following procedure.

    • Windows Vista and Windows 7 already have the Desktop Experience feature enabled automatically.

To install the Desktop Experience feature (Windows Server 2008, Windows Server 2008 R2)

  1. On the Start menu, click Server Management.

  2. In the Server Management dialog box, in the Features Summary pane, click Add Features.

  3. In the Select Features dialog box, select the Desktop Experience check box, and then click Install.

Examples

The following example shows part of a console application that demonstrates basic speech recognition. The example uses input from an audio file, testing123.wav, that contains the phrase, "testing testing one two three". The example generates the following output.

Copy image Copy Code
Starting asynchronous recognition...
  Recognized text =  Testing testing 123
  End of stream encountered.
Done.

Press any key to exit...
Copy image Copy Code
using System;
using System.Globalization;
using System.IO;
using Microsoft.Speech.AudioFormat;
using Microsoft.Speech.Recognition;
using System.Threading;

namespace InputExamples
{
  class Program
  {
    // Indicate whether asynchronous recognition is complete.
    static bool completed;

    static void Main(string[] args)
    {
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(new CultureInfo("en-US")))
      {

        // Create a grammar, construct a Grammar object, and load it to the recognizer.
        GrammarBuilder test = new GrammarBuilder("Testing testing 1,2,3");
        Grammar testing = new Grammar(test);
        testing.Name = "123";

        recognizer.LoadGrammar(testing);

        // Configure the input to the recognizer.
        recognizer.SetInputToWaveFile(@"C:\test\testing123.wav");

        // Attach event handlers.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(
            SpeechRecognizedHandler);
        recognizer.RecognizeCompleted +=
          new EventHandler<RecognizeCompletedEventArgs>(
            RecognizeCompletedHandler);

        // Perform recognition of the whole file.
        Console.WriteLine("Starting asynchronous recognition...");
        completed = false;
        recognizer.RecognizeAsync(RecognizeMode.Multiple);

        while (!completed)
        {
          Thread.Sleep(333);
        }
        Console.WriteLine("Done.");
      }

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

    // Handle the SpeechRecognized event.
    static void SpeechRecognizedHandler(
      object sender, SpeechRecognizedEventArgs e)
    {
      if (e.Result != null && e.Result.Text != null)
      {
        Console.WriteLine("  Recognized text =  {0}", e.Result.Text);
      }
      else
      {
        Console.WriteLine("  Recognized text not available.");
      }
    }

    // Handle the RecognizeCompleted event.
    static void RecognizeCompletedHandler(
      object sender, RecognizeCompletedEventArgs e)
    {
      if (e.Error != null)
      {
        Console.WriteLine("  Error encountered, {0}: {1}",
          e.Error.GetType().Name, e.Error.Message);
      }
      if (e.Cancelled)
      {
        Console.WriteLine("  Operation cancelled.");
      }
      if (e.InputStreamEnded)
      {
        Console.WriteLine("  End of stream encountered.");
      }

      completed = true;
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SetInputToAudioStream
SetInputToDefaultAudioDevice
SetInputToNull
SetInputToWaveStream
RecognizeCompleted
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetInputToWaveStream Method

[image]

SpeechRecognitionEngine..::..SetInputToWaveStream Method
SpeechRecognitionEngine Class See Also Send Feedback

Configures the SpeechRecognitionEngine object to receive input from a stream that contains Waveform audio format (.wav) data.

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

Syntax

Visual Basic (Declaration)
Public Sub SetInputToWaveStream ( _
    audioSource As Stream _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim audioSource As Stream

instance.SetInputToWaveStream(audioSource)
C#
public void SetInputToWaveStream(
    Stream audioSource
)

Parameters

audioSource
Type: System.IO..::..Stream

The stream containing the audio data.

Remarks

If the recognizer reaches the end of the input stream during a recognition operation, the recognition operation finalizes with the available input. Any subsequent recognition operations can generate an exception, unless you update the input to the recognizer.

The audio file can be in WMA format provided that both of the following conditions are met.

  • The WMA codec is available.

  • The target operating system has the appropriate Windows features installed or enabled.

    • A computer running Microsoft Windows Server 2003 x64 Editions must have Windows Media Format 9.5 Software Development Kit (SDK) x64 Edition installed.

    • A computer running Microsoft Windows Server 2008 or Windows Server 2008 R2 must have the Desktop Experience feature installed, as described in the following procedure.

    • Windows Vista and Windows 7 already have the Desktop Experience feature enabled automatically.

To install the Desktop Experience feature (Windows Server 2008, Windows Server 2008 R2)

  1. On the Start menu, click Server Management.

  2. In the Server Management dialog box, in the Features Summary pane, click Add Features.

  3. In the Select Features dialog box, select the Desktop Experience check box, and then click Install.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SetInputToAudioStream
SetInputToDefaultAudioDevice
SetInputToNull
SetInputToWaveFile
RecognizeCompleted
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SimulateRecognize Method

[image]

SpeechRecognitionEngine..::..SimulateRecognize Method
SpeechRecognitionEngine Class See Also Send Feedback

Simulates recognition of the specified string.

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

Syntax

Visual Basic (Declaration)
Public Function SimulateRecognize ( _
    inputText As String _
) As RecognitionResult
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim inputText As String
Dim returnValue As RecognitionResult

returnValue = instance.SimulateRecognize(inputText)
C#
public RecognitionResult SimulateRecognize(
    string inputText
)

Parameters

inputText
Type: System..::..String

The string for which to simulate recognition.

Return Value

Type: Microsoft.Speech.Recognition..::..RecognitionResult

Returns RecognitionResult.

Exceptions

Exception | Condition
ArgumentNullException | Thrown if inputText is nullNothingnullptrunita null reference (Nothing in Visual Basic) or an empty string.

Remarks

The SimulateRecognize(String) method creates an 'idealized' audio representation of the input phrase (based on the engine's lexicon and acoustic model), and then performs recognition on the idealized audio. Simulation can help you to determine whether (or how well) the speech recognition engine recognizes the pronunciation of a word. This is in contrast to the EmulateRecognize()()()() and EmulateRecognizeAsync()()()() methods, which use text instead of audio for recognition.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


UnloadAllGrammars Method

[image]

SpeechRecognitionEngine..::..UnloadAllGrammars Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Unloads all Grammar objects from the recognizer.

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

Syntax

Visual Basic (Declaration)
Public Sub UnloadAllGrammars
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine

instance.UnloadAllGrammars()
C#
public void UnloadAllGrammars()

Remarks

If the recognizer is currently loading a Grammar asynchronously, this method waits until the Grammar is loaded, before it unloads all of the Grammar objects from the SpeechRecognitionEngine instance.

To unload a specific grammar, use the UnloadGrammar method.

Examples

The following example shows part of a console application that demonstrates the synchronous loading and unloading of speech recognition grammars.

Copy image Copy Code
Loading grammars...
Loaded grammars:
 - Grammar1
 - Grammar2
 - Grammar3

Unloading Grammar1...
Loaded grammars:
 - Grammar2
 - Grammar3

Unloading all grammars...
No grammars loaded.

Press any key to exit...
C# Copy image Copy Code
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Speech.Recognition;

namespace UnloadGrammars
{
  class Program
  {
    static void Main(string[] args)
    {
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(new CultureInfo("en-US")))
      {
        Console.WriteLine("Loading grammars...");

        // Create and load a number of grammars.
        Grammar grammar1 = new Grammar(new GrammarBuilder("first grammar"));
        grammar1.Name = "Grammar1";
        recognizer.LoadGrammar(grammar1);

        Grammar grammar2 = new Grammar(new GrammarBuilder("second grammar"));
        grammar2.Name = "Grammar2";
        recognizer.LoadGrammar(grammar2);

        Grammar grammar3 = new Grammar(new GrammarBuilder("third grammar"));
        grammar3.Name = "Grammar3";
        recognizer.LoadGrammar(grammar3);

        // List the recognizer's loaded grammars.
        ListGrammars(recognizer);

        // Unload one grammar and list the loaded grammars.
        Console.WriteLine("Unloading Grammar1...");
        recognizer.UnloadGrammar(grammar1);
        ListGrammars(recognizer);

        // Unload all grammars and list the loaded grammars.
        Console.WriteLine("Unloading all grammars...");
        recognizer.UnloadAllGrammars();
        ListGrammars(recognizer);
      }

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

    private static void ListGrammars(SpeechRecognitionEngine recognizer)
    {
      // Make a copy of the recognizer's grammar collection.
      List<Grammar> loadedGrammars = new List<Grammar>(recognizer.Grammars);

      if (loadedGrammars.Count > 0)
      {
        Console.WriteLine("Loaded grammars:");
        foreach (Grammar g in recognizer.Grammars)
        {
          Console.WriteLine(" - {0}", g.Name);
        }
      }
      else
      {
        Console.WriteLine("No grammars loaded.");
      }
      Console.WriteLine();
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
LoadGrammar
LoadGrammarAsync
UnloadGrammar
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


UnloadGrammar Method

[image]

SpeechRecognitionEngine..::..UnloadGrammar Method
SpeechRecognitionEngine Class Example See Also Send Feedback

Unloads a specified Grammar object from the SpeechRecognitionEngine instance.

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

Syntax

Visual Basic (Declaration)
Public Sub UnloadGrammar ( _
    grammar As Grammar _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim grammar As Grammar

instance.UnloadGrammar(grammar)
C#
public void UnloadGrammar(
    Grammar grammar
)

Parameters

grammar
Type: Microsoft.Speech.Recognition..::..Grammar

The grammar object to unload.

Remarks

If the Grammar specified by the grammar parameter is not currently loaded, TargetInvocationException will be generated.

If the recognizer is running, applications must use RequestRecognizerUpdate()()()() to pause the SpeechRecognitionEngine instance before loading, unloading, enabling, or disabling a Grammar object. To unload all Grammar objects, use the UnloadAllGrammars method.

Examples

The following example shows part of a console application that demonstrates the synchronous loading and unloading of speech recognition grammars.

Copy image Copy Code
Loading grammars...
Loaded grammars:
 - Grammar1
 - Grammar2
 - Grammar3

Unloading Grammar1...
Loaded grammars:
 - Grammar2
 - Grammar3

Unloading all grammars...
No grammars loaded.

Press any key to exit...
C# Copy image Copy Code
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Speech.Recognition;

namespace UnloadGrammars
{
  class Program
  {
    static void Main(string[] args)
    {
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(new CultureInfo("en-US")))
      {
        Console.WriteLine("Loading grammars...");

        // Create and load a number of grammars.
        Grammar grammar1 = new Grammar(new GrammarBuilder("first grammar"));
        grammar1.Name = "Grammar1";
        recognizer.LoadGrammar(grammar1);

        Grammar grammar2 = new Grammar(new GrammarBuilder("second grammar"));
        grammar2.Name = "Grammar2";
        recognizer.LoadGrammar(grammar2);

        Grammar grammar3 = new Grammar(new GrammarBuilder("third grammar"));
        grammar3.Name = "Grammar3";
        recognizer.LoadGrammar(grammar3);

        // List the recognizer's loaded grammars.
        ListGrammars(recognizer);

        // Unload one grammar and list the loaded grammars.
        Console.WriteLine("Unloading Grammar1...");
        recognizer.UnloadGrammar(grammar1);
        ListGrammars(recognizer);

        // Unload all grammars and list the loaded grammars.
        Console.WriteLine("Unloading all grammars...");
        recognizer.UnloadAllGrammars();
        ListGrammars(recognizer);
      }

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

    private static void ListGrammars(SpeechRecognitionEngine recognizer)
    {
      // Make a copy of the recognizer's grammar collection.
      List<Grammar> loadedGrammars = new List<Grammar>(recognizer.Grammars);

      if (loadedGrammars.Count > 0)
      {
        Console.WriteLine("Loaded grammars:");
        foreach (Grammar g in recognizer.Grammars)
        {
          Console.WriteLine(" - {0}", g.Name);
        }
      }
      else
      {
        Console.WriteLine("No grammars loaded.");
      }
      Console.WriteLine();
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
RecognizerUpdateReached
LoadGrammarAsync
LoadGrammarAsync
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


UpdateRecognizerSetting Method

[image] [image]

SpeechRecognitionEngine..::..UpdateRecognizerSetting Method
SpeechRecognitionEngine Class See Also Send Feedback

Updates the values of the current settings for a speech recognition engine managed by a SpeechRecognitionEngine object.

Overload List

 | Name | Description
Public method | UpdateRecognizerSetting(String, Int32) | Updates the specified setting for the SpeechRecognitionEngine with the specified integer value.
Public method | UpdateRecognizerSetting(String, String) | Updates the specified setting for the SpeechRecognitionEngine with the specified integer value.
Top

Remarks

Recognizer settings can contain string, 64-bit integer, or memory address data. The following table describes the settings that are defined for a recognizer that complies with the Microsoft Speech Platform SDK 11. The following settings must have the same range for each recognizer that supports the setting. A recognizer that complies with the Speech Platform SDK 11 is not required to support these settings and can support other settings.

Name

Description

ResourceUsage

Specifies the recognizer's CPU consumption. The range is from 0 to 100. The default value is 50.

HighConfidenceThreshold

Not used by Microsoft.Speech. The value specified here is effectively the same as any value above the LowConfidenceThreshold. The range is from 0 to 100, inclusive. The default value is 80.

NormalConfidenceThreshold

Not used by Microsoft.Speech. The value specified here is effectively the same as any value above the LowConfidenceThreshold. The range is from 0 to 100, inclusive. The default value is 50.

LowConfidenceThreshold

Not used by Microsoft.Speech. Separates the speech recognized confidence range from the speech rejected confidence range. The range is from 0 to 100, inclusive. The default value is 20.

CFGConfidenceRejectionThreshold

The speech recognition engine accepts full utterances with confidence scores above or equal to this threshold, and rejects full utterances with phrase confidence scores below this threshold. This property accepts the following values:

  • The value -1 causes the engine to use its default value.

  • A value in the range of 0-100 sets the phrase confidence rejection threshold to the specified value.

If this value is set to 0, the speech recognition accepts all utterances. If this value is set to 100, the speech recognition engine rejects all utterances. This property is not to be confused with HighConfidenceThreshold, NormalConfidenceThreshold, or LowConfidenceThreshold, which are used to determine how any given confidence value is categorized (low, medium, or high).

ResponseSpeed

Indicates the length of silence at the end of unambiguous input before the speech recognizer completes a recognition operation. The range is from 0 to 10,000 milliseconds (ms). This setting corresponds to the recognizer's EndSilenceTimeout property.

ComplexResponseSpeed

Indicates the length of silence at the end of ambiguous input before the speech recognizer completes a recognition operation. The range is from 0 to 10,000 ms. This setting corresponds to the recognizer's EndSilenceTimeoutAmbiguous property.

EngineThreadPriority

Sets the priority of the engine thread(s). The range of permitted values is defined by the OS.

  • The minimum value is min(THREAD_PRIORITY_IDLE,THREAD_PRIORITY_HIGHEST)

  • The maximum value is max(THREAD_PRIORITY_IDLE,THREAD_PRIORITY_HIGHEST)

The values of these constants are in defined winbase.h.

AdaptationOn

Indicates whether adaptation of the acoustic model is on (value = 1) or off (value = 0). The default value is 1 (on).

PersistedBackgroundAdaptation

Indicates whether background adaptation is on (value = 1) or off (value = 0), and persists the setting in the registry. The default value is 1 (on).

AssumeCFGFromTrustedSource

Bypasses file integrity checks when loading a CFG, to reduce load time. This should *only* be used by applications that can guarantee that the CFG they are loading has previously been compiled by the application (or by another application it trusts) and has been stored in a secure location where it could not be edited by a malicious agent. This property accepts the following values:

  • Value set to 0 = AssumeCFGFromTrustedSource is OFF

  • Value set to 1 = AssumeCFGFromTrustedSource is ON

The threshold values are used to divide a confidence scale into four portions: rejected, low, medium, and high. This is to allow assigning of a text value to confidence scores in defined ranges. Microsoft.Speech does not distinguish between high, normal, and low confidence levels, and does not assign text values to ranges of confidence scores. Modifying the values for HighConfidenceThreshold and NormalConfidenceThreshold, and LowConfidenceThreshold will have no effect on recognition.

To dictate the confidence level at which higher values indicate recognized speech, and equal or lower values indicate rejected speech, use CFGConfidenceRejectionThreshold. Recognition results with confidence values greater than or equal to the CFGConfidenceRejectionThreshold trigger a SpeechRecognized event. Recognition results with confidence values less than the CFGConfidenceRejectionThreshold trigger a SpeechRecognitionRejected event.

The confidence scores assigned to words and phrases by the recognition engine become the values of the RecognizedWordUnit..::..Confidence and RecognizedPhrase..::..Confidence properties, and are converted to range from 0 to 1, instead of from 0-100.

To return one of the recognizer's settings, use the QueryRecognizerSetting method.

You can modify how the speech recognition responds to non-speech input using the BabbleTimeout, InitialSilenceTimeout, EndSilenceTimeout, and EndSilenceTimeoutAmbiguous properties.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


UpdateRecognizerSetting Method (String, Int32)

[image]

SpeechRecognitionEngine..::..UpdateRecognizerSetting Method (String, Int32)
SpeechRecognitionEngine Class Example See Also Send Feedback

Updates the specified setting for the SpeechRecognitionEngine with the specified integer value.

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

Syntax

Visual Basic (Declaration)
Public Sub UpdateRecognizerSetting ( _
    settingName As String, _
    updatedValue As Integer _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim settingName As String
Dim updatedValue As Integer

instance.UpdateRecognizerSetting(settingName, _
    updatedValue)
C#
public void UpdateRecognizerSetting(
    string settingName,
    int updatedValue
)

Parameters

settingName
Type: System..::..String

The name of the speech recognition engine setting.

updatedValue
Type: System..::..Int32

The updated value of the speech recognition engine setting.

Exceptions

Exception | Condition
KeyNotFoundException | Thrown if the key specified by settingName could not be found.

Remarks

The only currently valid setting name is "BackgroundSpeechSensitivity". This setting can be used to adjust the speech recognition engine's sensitivity to speech that occurs in the background. Valid values for this setting are integers in the range -1 through 100, inclusive.

BackgroundSpeechSensitivity setting | Description
-1 | It is unknown whether speech is expected.
0 | Minimum sensitivity. This value is useful when no speech is expected in the background.
100 | Maximum sensitivity. This value is useful when speech is expected in the background. This is the default value.

Examples

The following example is part of a console application that outputs the values for a number of the settings defined for the recognizer that supports the en-US locale. The example updates the confidence level settings, and then queries the recognizer to check the updated values. The example generates the following output.

Copy image Copy Code
Settings for recognizer MS-1033-80-DESK:

  ResourceUsage                  is not supported by this recognizer.
  HighConfidenceThreshold        = 80
  NormalConfidenceThreshold      = 50
  LowConfidenceThreshold         = 20
  ResponseSpeed                  = 150
  ComplexResponseSpeed           = 500
  AdaptationOn                   = 1
  PersistedBackgroundAdaptation  = 1

Updated settings:

  ResourceUsage                  is not supported by this recognizer.
  HighConfidenceThreshold        = 60
  NormalConfidenceThreshold      = 40
  LowConfidenceThreshold         = 15
  ResponseSpeed                  = 150
  ComplexResponseSpeed           = 500
  AdaptationOn                   = 1
  PersistedBackgroundAdaptation  = 1

Press any key to exit...
C# Copy image Copy Code
using System;
using System.Globalization;
using Microsoft.Speech.Recognition;

namespace RecognizerSettings
{
  class Program
  {
    static readonly string[] settings = new string[] {
      "ResourceUsage",
      "HighConfidenceThreshold",
      "NormalConfidenceThreshold",
      "LowConfidenceThreshold",
      "ResponseSpeed",
      "ComplexResponseSpeed",
      "AdaptationOn",
      "PersistedBackgroundAdaptation"
    };

    static void Main(string[] args)
    {
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US")))
      {
        Console.WriteLine("Settings for recognizer {0}:",
          recognizer.RecognizerInfo.Name);
        Console.WriteLine();

        // List the current settings.
        ListSettings(recognizer);

        // Change some of the settings.
        recognizer.UpdateRecognizerSetting("HighConfidenceThreshold", 60);
        recognizer.UpdateRecognizerSetting("NormalConfidenceThreshold", 40);
        recognizer.UpdateRecognizerSetting("LowConfidenceThreshold", 15);

        Console.WriteLine("Updated settings:");
        Console.WriteLine();

        // List the updated settings.
        ListSettings(recognizer);
      }

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

    private static void ListSettings(SpeechRecognitionEngine recognizer)
    {
      foreach (string setting in settings)
      {
        try
        {
          object value = recognizer.QueryRecognizerSetting(setting);
          Console.WriteLine("  {0,-30} = {1}", setting, value);
        }
        catch
        {
          Console.WriteLine("  {0,-30} is not supported by this recognizer.",
            setting);
        }
      }
      Console.WriteLine();
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
UpdateRecognizerSetting Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


UpdateRecognizerSetting Method (String, String)

[image]

SpeechRecognitionEngine..::..UpdateRecognizerSetting Method (String, String)
SpeechRecognitionEngine Class See Also Send Feedback

Updates the specified setting for the SpeechRecognitionEngine with the specified integer value.

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

Syntax

Visual Basic (Declaration)
Public Sub UpdateRecognizerSetting ( _
    settingName As String, _
    updatedValue As String _
)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim settingName As String
Dim updatedValue As String

instance.UpdateRecognizerSetting(settingName, _
    updatedValue)
C#
public void UpdateRecognizerSetting(
    string settingName,
    string updatedValue
)

Parameters

settingName
Type: System..::..String

The name of the setting to update.

updatedValue
Type: System..::..String

The new value for the setting.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
UpdateRecognizerSetting Overload
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionEngine Properties

[image] [image]

SpeechRecognitionEngine Properties
SpeechRecognitionEngine Class See Also Send Feedback

The SpeechRecognitionEngine type exposes the following members.

Properties

 | Name | Description
Public property | AudioFormat | Gets the format of the audio being received by the SpeechRecognitionEngine.
Public property | AudioLevel | Gets the level of the audio being received by the SpeechRecognitionEngine.
Public property | AudioPosition | Gets the current location in the audio stream being generated by the device that is providing input to the SpeechRecognitionEngine.
Public property | AudioState | Gets the state of the audio being received by the SpeechRecognitionEngine.
Public property | BabbleTimeout | Gets or sets the interval of time that a SpeechRecognitionEngine accepts input containing only background noise before finalizing recognition.
Public property | EndSilenceTimeout | Gets or sets the interval of silence that the SpeechRecognitionEngine will accept at the end of unambiguous input before finalizing a recognition operation.
Public property | EndSilenceTimeoutAmbiguous | Gets or sets the interval of silence that the SpeechRecognitionEngine will accept at the end of ambiguous input before finalizing a recognition operation.
Public property | Grammars | Gets a collection of the Grammar objects that are loaded in this SpeechRecognitionEngine instance.
Public property | InitialSilenceTimeout | Gets or sets the time interval during which a SpeechRecognitionEngine accepts input containing only silence before finalizing recognition.
Public property | MaxAlternates | Gets or sets the maximum number of alternate recognition results that the SpeechRecognitionEngine returns for each recognition operation.
Public property | NormalizerCollection | Gets the normalizer collection.
Public property | RecognizerAudioPosition | Gets the current location of the SpeechRecognitionEngine in the audio input that it is processing.
Public property | RecognizerInfo | Gets information about the current instance of SpeechRecognitionEngine.
Top

See Also

Reference

SpeechRecognitionEngine Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioFormat Property

[image]

SpeechRecognitionEngine..::..AudioFormat Property
SpeechRecognitionEngine Class Example See Also Send Feedback

Gets the format of the audio being received by the SpeechRecognitionEngine.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioFormat As SpeechAudioFormatInfo
    Get
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As SpeechAudioFormatInfo

value = instance.AudioFormat
C#
public SpeechAudioFormatInfo AudioFormat { get; }

Property Value

Type: Microsoft.Speech.AudioFormat..::..SpeechAudioFormatInfo

The format of audio at the input to the SpeechRecognitionEngine instance, or nullNothingnullptrunita null reference (Nothing in Visual Basic) if the input is not configured or set to the null input.

Remarks

To configure the audio input, use one of the following methods:

  • SetInputToAudioStream

  • SetInputToDefaultAudioDevice

  • SetInputToNull

  • SetInputToWaveFile

  • SetInputToWaveStream

Examples

The example below uses AudioFormat to obtain and display audio format data.

Copy image Copy Code
static void DisplayAudioDeviceFormat(Label label, SpeechRecognitionEngine recognitionEngine)
{

  if (recognitionEngine != null && label != null)
  {
    label.Text = String.Format("Encoding Format:         {0}\n" +
          "AverageBytesPerSecond    {1}\n" +
          "BitsPerSample            {2}\n" +
          "BlockAlign               {3}\n" +
          "ChannelCount             {4}\n" +
          "SamplesPerSecond         {5}",
          recognitionEngine.AudioFormat.EncodingFormat.ToString(),
          recognitionEngine.AudioFormat.AverageBytesPerSecond,
          recognitionEngine.AudioFormat.BitsPerSample,
          recognitionEngine.AudioFormat.BlockAlign,
          recognitionEngine.AudioFormat.ChannelCount,
          recognitionEngine.AudioFormat.SamplesPerSecond);
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SpeechAudioFormatInfo
SpeechRecognitionEngine
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioLevel Property

[image]

SpeechRecognitionEngine..::..AudioLevel Property
SpeechRecognitionEngine Class See Also Send Feedback

Gets the level of the audio being received by the SpeechRecognitionEngine.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioLevel As Integer
    Get
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As Integer

value = instance.AudioLevel
C#
public int AudioLevel { get; }

Property Value

Type: System..::..Int32

The audio level of the input to the speech recognizer, from 0 through 100.

Remarks

The value 0 represents silence, and 100 represents the maximum input volume.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
AudioLevelUpdated
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioPosition Property

[image]

SpeechRecognitionEngine..::..AudioPosition Property
SpeechRecognitionEngine Class Example See Also Send Feedback

Gets the current location in the audio stream being generated by the device that is providing input to the SpeechRecognitionEngine.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioPosition As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As TimeSpan

value = instance.AudioPosition
C#
public TimeSpan AudioPosition { get; }

Property Value

Type: System..::..TimeSpan

The current location in the audio stream being generated by the input device.

Remarks

The AudioPosition property references the input device's position in its generated audio stream. By contrast, the RecognizerAudioPosition property references the recognizer's position within its audio input. These positions can be different. For example, if the recognizer has received input for which it has not yet generated a recognition result then the value of the RecognizerAudioPosition property is less than the value of the AudioPosition property.

Examples

The following example creates a simple grammar, constructs a Grammar object, and loads it to the SpeechRecognitionEngine. A handler for the SpeechDetected event writes to the console the AudioPosition, RecognizerAudioPosition, and AudioLevel when the speech recognizer detects speech at its input.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

      // Initialize a SpeechRecognitionEngine object for US English.
      recognizer = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));
      recognizer.SetInputToDefaultAudioDevice();

      // Create a grammar for finding services in different cities.
      Choices services = new Choices(new string[] { "restaurants", "hotels", "gas stations" });
      Choices cities = new Choices(new string[] { "Seattle", "Boston", "Dallas" });

      GrammarBuilder findServices = new GrammarBuilder("Find");
      findServices.Append(services);
      findServices.Append("near");
      findServices.Append(cities);

      // Create a Grammar object from the GrammarBuilder and load it to the recognizer.
      Grammar servicesGrammar = new Grammar(findServices);
      recognizer.LoadGrammarAsync(servicesGrammar);

      // Add handlers for events.
      recognizer.SpeechRecognized +=
        new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
      recognizer.SpeechDetected +=
        new EventHandler<SpeechDetectedEventArgs>(recognizer_SpeechDetected);

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

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

    // Gather information about detected speech and write it to the console.
    static void recognizer_SpeechDetected(object sender, SpeechDetectedEventArgs e)
    {
      Console.WriteLine();
      Console.WriteLine("Speech detected:");
      Console.WriteLine("  Audio level: " + recognizer.AudioLevel);
      Console.WriteLine("  Audio position at the event: " + e.AudioPosition);
      Console.WriteLine("  Current audio position: " + recognizer.AudioPosition);
      Console.WriteLine("  Current recognizer audio position: " + recognizer.RecognizerAudioPosition);
    }

    // Write the text of the recognition result to the console.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine("\nSpeech recognized: " + e.Result.Text);

      // Add event handler code here.
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioState Property

[image]

SpeechRecognitionEngine..::..AudioState Property
SpeechRecognitionEngine Class See Also Send Feedback

Gets the state of the audio being received by the SpeechRecognitionEngine.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioState As AudioState
    Get
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As AudioState

value = instance.AudioState
C#
public AudioState AudioState { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..AudioState

The state of the audio input to the speech recognizer.

Remarks

The AudioState property represents the audio state with a member of the AudioState enumeration.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
Microsoft.Speech.Recognition..::..AudioState
AudioStateChanged
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


BabbleTimeout Property

[image]

SpeechRecognitionEngine..::..BabbleTimeout Property
SpeechRecognitionEngine Class Example See Also Send Feedback

Gets or sets the interval of time that a SpeechRecognitionEngine accepts input containing only background noise before finalizing recognition.

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

Syntax

Visual Basic (Declaration)
Public Property BabbleTimeout As TimeSpan
    Get
    Set
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As TimeSpan

value = instance.BabbleTimeout

instance.BabbleTimeout = value
C#
public TimeSpan BabbleTimeout { get; set; }

Property Value

Type: System..::..TimeSpan

The duration of the time interval.

Remarks

Each speech recognizer has an algorithm to distinguish between silence and speech. The recognizer classifies as background noise any non-silence input that does not match the initial rule of any of the recognizer's loaded and enabled speech recognition grammars. If the recognizer receives only background noise and silence within the babble timeout interval, then the recognizer finalizes that recognition operation.

  • For asynchronous recognition operations, the recognizer raises the RecognizeCompleted event, where the RecognizeCompletedEventArgs..::..BabbleTimeout property is true, and the RecognizeCompletedEventArgs..::..Result property is nullNothingnullptrunita null reference (Nothing in Visual Basic).

  • For synchronous recognition operations and emulation, the recognizer returns nullNothingnullptrunita null reference (Nothing in Visual Basic), instead of a valid RecognitionResult.

If the babble timeout period is set to 0, the recognizer does not perform a babble timeout check. The timeout interval can be any non-negative number. The default is 0 seconds.

Examples

The following example shows part of a console application that demonstrates basic speech recognition that sets the BabbleTimeout and InitialSilenceTimeout properties of a SpeechRecognitionEngine before initiating speech recognition. Handlers for the speech recognizer's AudioStateChanged and RecognizeCompleted events output event information to the console to demonstrate how the InitialSilenceTimeout properties of a SpeechRecognitionEngine affect recognition operations.

C# Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

      // Initialize an in-process speech recognizer.
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(
          new System.Globalization.CultureInfo("en-US")))
      {
        // Load a Grammar object.
        recognizer.LoadGrammar(CreateServicesGrammar("FindServices"));

        // Add event handlers.
        recognizer.AudioStateChanged +=
          new EventHandler<AudioStateChangedEventArgs>(
            AudioStateChangedHandler);
        recognizer.RecognizeCompleted +=
          new EventHandler<RecognizeCompletedEventArgs>(
            RecognizeCompletedHandler);

        // Configure input to the speech recognizer.
        recognizer.SetInputToDefaultAudioDevice();

        recognizer.InitialSilenceTimeout = TimeSpan.FromSeconds(3);
        recognizer.BabbleTimeout = TimeSpan.FromSeconds(2);
        recognizer.EndSilenceTimeout = TimeSpan.FromSeconds(1);
        recognizer.EndSilenceTimeoutAmbiguous = TimeSpan.FromSeconds(1.5);

        Console.WriteLine("BabbleTimeout: {0}", recognizer.BabbleTimeout);
        Console.WriteLine("InitialSilenceTimeout: {0}", recognizer.InitialSilenceTimeout);
        Console.WriteLine("EndSilenceTimeout: {0}", recognizer.EndSilenceTimeout);
        Console.WriteLine("EndSilenceTimeoutAmbiguous: {0}", recognizer.EndSilenceTimeoutAmbiguous);
        Console.WriteLine();

        // Start asynchronous speech recognition.
        recognizer.RecognizeAsync(RecognizeMode.Single);

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

    // Create a grammar and build it into a Grammar object.
    static Grammar CreateServicesGrammar(string grammarName)
    {

      // Create a grammar for finding services in different cities.
      Choices services = new Choices(new string[] { "restaurants", "hotels", "gas stations" });
      Choices cities = new Choices(new string[] { "Seattle", "Boston", "Dallas" });

      GrammarBuilder findServices = new GrammarBuilder("Find");
      findServices.Append(services);
      findServices.Append("near");
      findServices.Append(cities);

      // Create a Grammar object from the GrammarBuilder..
      Grammar servicesGrammar = new Grammar(findServices);
      servicesGrammar.Name = ("FindServices");
      return servicesGrammar;
    }

    // Handle the AudioStateChanged event.
    static void AudioStateChangedHandler(
      object sender, AudioStateChangedEventArgs e)
    {
      Console.WriteLine("AudioStateChanged ({0}): {1}",
        DateTime.Now.ToString("mm:ss.f"), e.AudioState);
    }

    // Handle the RecognizeCompleted event.
    static void RecognizeCompletedHandler(
      object sender, RecognizeCompletedEventArgs e)
    {
      Console.WriteLine("RecognizeCompleted ({0}):",
        DateTime.Now.ToString("mm:ss.f"));

      string resultText;
      if (e.Result != null) { resultText = e.Result.Text; }
      else { resultText = "<null>"; }

      Console.WriteLine(
        " BabbleTimeout: {0}; InitialSilenceTimeout: {1}; Result text: {2}",
        e.BabbleTimeout, e.InitialSilenceTimeout, resultText);
      if (e.Error != null)
      {
        Console.WriteLine(" Exception message: ", e.Error.Message);
      }

      // Start the next asynchronous recognition operation.
      ((SpeechRecognitionEngine)sender).RecognizeAsync(RecognizeMode.Single);
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EndSilenceTimeout Property

[image]

SpeechRecognitionEngine..::..EndSilenceTimeout Property
SpeechRecognitionEngine Class See Also Send Feedback

Gets or sets the interval of silence that the SpeechRecognitionEngine will accept at the end of unambiguous input before finalizing a recognition operation.

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

Syntax

Visual Basic (Declaration)
Public Property EndSilenceTimeout As TimeSpan
    Get
    Set
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As TimeSpan

value = instance.EndSilenceTimeout

instance.EndSilenceTimeout = value
C#
public TimeSpan EndSilenceTimeout { get; set; }

Property Value

Type: System..::..TimeSpan

The duration of the interval of silence.

Remarks

This property determines how long the speech recognition engine will wait for additional input before finalizing a recognition operation. The speech recognition engine uses this timeout interval when the recognition input is unambiguous. For example, for a speech recognition grammar that supports recognition of either "new game please" or "new game", "new game please" is an unambiguous input, and "new game" is an ambiguous input.

The timeout interval can be from 0 seconds to 10 seconds, inclusive. The default is 150 milliseconds.

To set the timeout interval for ambiguous input, use the EndSilenceTimeoutAmbiguous property.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
BabbleTimeout
EndSilenceTimeoutAmbiguous
InitialSilenceTimeout
Recognize
EmulateRecognize
RecognizeAsync
EmulateRecognizeAsync
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EndSilenceTimeoutAmbiguous Property

[image]

SpeechRecognitionEngine..::..EndSilenceTimeoutAmbiguous Property
SpeechRecognitionEngine Class See Also Send Feedback

Gets or sets the interval of silence that the SpeechRecognitionEngine will accept at the end of ambiguous input before finalizing a recognition operation.

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

Syntax

Visual Basic (Declaration)
Public Property EndSilenceTimeoutAmbiguous As TimeSpan
    Get
    Set
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As TimeSpan

value = instance.EndSilenceTimeoutAmbiguous

instance.EndSilenceTimeoutAmbiguous = value
C#
public TimeSpan EndSilenceTimeoutAmbiguous { get; set; }

Property Value

Type: System..::..TimeSpan

The duration of the interval of silence.

Remarks

This property determines how long the speech recognition engine will wait for additional input before finalizing a recognition operation. The speech recognizer uses this timeout interval when the recognition input is ambiguous. For example, for a speech recognition grammar that supports recognition of either "new game please" or "new game", "new game please" is an unambiguous input, and "new game" is an ambiguous input.

The timeout interval can be from 0 seconds to 10 seconds, inclusive. The default is 500 milliseconds.

To set the timeout interval for unambiguous input, use the EndSilenceTimeout property.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
BabbleTimeout
EndSilenceTimeout
InitialSilenceTimeout
Recognize
EmulateRecognize
RecognizeAsync
EmulateRecognizeAsync
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Grammars Property

[image]

SpeechRecognitionEngine..::..Grammars Property
SpeechRecognitionEngine Class Example See Also Send Feedback

Gets a collection of the Grammar objects that are loaded in this SpeechRecognitionEngine instance.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Grammars As ReadOnlyCollection(Of Grammar)
    Get
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As ReadOnlyCollection(Of Grammar)

value = instance.Grammars
C#
public ReadOnlyCollection<Grammar> Grammars { get; }

Property Value

Type: System.Collections.ObjectModel..::..ReadOnlyCollection <(Of <(<' Grammar >)>)>

The collection of Grammar objects.

Examples

The following example outputs information to the console for each speech recognition grammar that is currently loaded by a speech recognizer.

Important note Important

Copy the grammar collection to avoid errors if the collection is modified while this method enumerates the elements of the collection.

C# Copy image Copy Code
private static void ListGrammars(SpeechRecognitionEngine recognizer)
{
  string qualifier;
  List<Grammar> grammars = new List<Grammar>(recognizer.Grammars);
  foreach (Grammar g in grammars)
  {
    qualifier = (g.Enabled) ? "enabled" : "disabled";

    Console.WriteLine("Grammar {0} is loaded and is {1}.",
      g.Name, qualifier);
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
Grammar
[T:System.Collections.ObjectModel.ReadOnlyCollection(T)]
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InitialSilenceTimeout Property

[image]

SpeechRecognitionEngine..::..InitialSilenceTimeout Property
SpeechRecognitionEngine Class Example See Also Send Feedback

Gets or sets the time interval during which a SpeechRecognitionEngine accepts input containing only silence before finalizing recognition.

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

Syntax

Visual Basic (Declaration)
Public Property InitialSilenceTimeout As TimeSpan
    Get
    Set
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As TimeSpan

value = instance.InitialSilenceTimeout

instance.InitialSilenceTimeout = value
C#
public TimeSpan InitialSilenceTimeout { get; set; }

Property Value

Type: System..::..TimeSpan

The duration of the interval of silence.

Remarks

Each speech recognizer has an algorithm to distinguish between silence and speech. If the recognizer input is silence during the initial silence timeout period, then the recognizer finalizes that recognition operation.

  • For asynchronous recognition operations and emulation, the recognizer raises the RecognizeCompleted event, where the RecognizeCompletedEventArgs..::..InitialSilenceTimeout property is true, and the RecognizeCompletedEventArgs..::..Result property is nullNothingnullptrunita null reference (Nothing in Visual Basic).

  • For synchronous recognition operations and emulation, the recognizer returns nullNothingnullptrunita null reference (Nothing in Visual Basic), instead of a valid RecognitionResult.

If the initial silence timeout interval is set to 0, the recognizer does not perform an initial silence timeout check. The timeout interval can be any non-negative interval. The default is 0 seconds.

Examples

The following example shows part of a console application that demonstrates basic speech recognition. The example sets the BabbleTimeout and InitialSilenceTimeout properties of a SpeechRecognitionEngine before initiating speech recognition. Handlers for the speech recognizer's AudioStateChanged and RecognizeCompleted events output event information to the console to demonstrate how the InitialSilenceTimeout properties of a SpeechRecognitionEngine properties affect recognition operations.

C# Copy image Copy Code

using System;
using Microsoft.Speech.Recognition;

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

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

      // Create a grammar for choosing cities for a flight.
        Choices cities = new Choices(new string[]
        { "Los Angeles", "New York", "Chicago", "San Francisco", "Miami", "Dallas" });

        GrammarBuilder gb = new GrammarBuilder();
        gb.Append("I want to fly from");
        gb.Append(cities);
        gb.Append("to");
        gb.Append(cities);

        // Create a Grammar object from the GrammarBuilder and load it to the recognizer.
        Grammar g = new Grammar(gb);
        g.Name = ("City Chooser");
        recognizer.LoadGrammarAsync(g);

        // Add event handlers.
        recognizer.AudioStateChanged +=
          new EventHandler<AudioStateChangedEventArgs>(
            AudioStateChangedHandler);
        recognizer.RecognizeCompleted +=
          new EventHandler<RecognizeCompletedEventArgs>(
            RecognizeCompletedHandler);

        // Configure input to the speech recognizer.
        recognizer.SetInputToDefaultAudioDevice();

        recognizer.InitialSilenceTimeout = TimeSpan.FromSeconds(3);
        recognizer.BabbleTimeout = TimeSpan.FromSeconds(2);
        recognizer.EndSilenceTimeout = TimeSpan.FromSeconds(1);
        recognizer.EndSilenceTimeoutAmbiguous = TimeSpan.FromSeconds(1.5);

        Console.WriteLine("BabbleTimeout: {0}", recognizer.BabbleTimeout);
        Console.WriteLine("InitialSilenceTimeout: {0}", recognizer.InitialSilenceTimeout);
        Console.WriteLine("EndSilenceTimeout: {0}", recognizer.EndSilenceTimeout);
        Console.WriteLine("EndSilenceTimeoutAmbiguous: {0}", recognizer.EndSilenceTimeoutAmbiguous);
        Console.WriteLine();

        // Start asynchronous speech recognition.
        recognizer.RecognizeAsync(RecognizeMode.Single);

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

    // Handle the AudioStateChanged event.
    static void AudioStateChangedHandler(
      object sender, AudioStateChangedEventArgs e)
    {
      Console.WriteLine("AudioStateChanged ({0}): {1}",
        DateTime.Now.ToString("mm:ss.f"), e.AudioState);
    }

    // Handle the RecognizeCompleted event.
    static void RecognizeCompletedHandler(
      object sender, RecognizeCompletedEventArgs e)
    {
      Console.WriteLine("RecognizeCompleted ({0}):",
        DateTime.Now.ToString("mm:ss.f"));

      string resultText;
      if (e.Result != null) { resultText = e.Result.Text; }
      else { resultText = "<null>"; }

      Console.WriteLine(
        " BabbleTimeout: {0}; InitialSilenceTimeout: {1}; Result text: {2}",
        e.BabbleTimeout, e.InitialSilenceTimeout, resultText);
      if (e.Error != null)
      {
        Console.WriteLine(" Exception message: ", e.Error.Message);
      }

      // Start the next asynchronous recognition operation.
      ((SpeechRecognitionEngine)sender).RecognizeAsync(RecognizeMode.Single);
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
BabbleTimeout
EndSilenceTimeout
EndSilenceTimeoutAmbiguous
Recognize
EmulateRecognize
RecognizeAsync
EmulateRecognizeAsync
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MaxAlternates Property

[image]

SpeechRecognitionEngine..::..MaxAlternates Property
SpeechRecognitionEngine Class Example See Also Send Feedback

Gets or sets the maximum number of alternate recognition results that the SpeechRecognitionEngine returns for each recognition operation.

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

Syntax

Visual Basic (Declaration)
Public Property MaxAlternates As Integer
    Get
    Set
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As Integer

value = instance.MaxAlternates

instance.MaxAlternates = value
C#
public int MaxAlternates { get; set; }

Property Value

Type: System..::..Int32

The number of alternate results to return.

Remarks

The Alternates property of the RecognitionResult class contains the collection of RecognizedPhrase objects that represent possible interpretations of the input.

The default value for MaxAlternates is 10.

Examples

The example below shows a handler for a TextChanged()()()() event that allows end user to update the value of MaxAlternates.

Copy image Copy Code
private void _maxAltsInput_TextChanged(object sender, EventArgs e)
{
  int newMax;
  newMax = _recognizer.MaxAlternates;
  try
  {
    newMax = int.Parse(_maxAltsInput.Text, System.Globalization.NumberStyles.Integer);
  }
  catch (Exception exception)
  {
    MessageBox.Show(string.Format(
         "Invalid Input:   {0}\n Error Message:   {1}",
        _maxAltsInput.Text, exception.Message));
  }
  _recognizer.MaxAlternates = newMax;
  _maxAltsInput.Text = _recognizer.MaxAlternates.ToString();
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SpeechRecognitionEngine
Alternates
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizerCollection Property

[image]

SpeechRecognitionEngine..::..NormalizerCollection Property
SpeechRecognitionEngine Class See Also Send Feedback

Gets the normalizer collection.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property NormalizerCollection As NormalizerCollection
    Get
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As NormalizerCollection

value = instance.NormalizerCollection
C#
public NormalizerCollection NormalizerCollection { get; }

Property Value

Type: Microsoft.Speech.Text..::..NormalizerCollection

Returns NormalizerCollection.

Exceptions

Exception | Condition
ObjectDisposedException | Thrown if this SpeechRecognitionEngine instance has been disposed.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizerAudioPosition Property

[image]

SpeechRecognitionEngine..::..RecognizerAudioPosition Property
SpeechRecognitionEngine Class See Also Send Feedback

Gets the current location of the SpeechRecognitionEngine in the audio input that it is processing.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property RecognizerAudioPosition As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As TimeSpan

value = instance.RecognizerAudioPosition
C#
public TimeSpan RecognizerAudioPosition { get; }

Property Value

Type: System..::..TimeSpan

The position of the recognizer in the audio input that it is processing.

Remarks

The audio position is specific to each speech recognizer. The zero value of an input stream is established when it is enabled.

The RecognizerAudioPosition property references the SpeechRecognitionEngine object's position within its audio input. By contrast, the AudioPosition property references the input device's position in its generated audio stream. These positions can be different. For example, if the recognizer has received input for which it has not yet generated a recognition result then the value of the RecognizerAudioPosition property is less than the value of the AudioPosition property.

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
AudioPosition
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizerInfo Property

[image]

SpeechRecognitionEngine..::..RecognizerInfo Property
SpeechRecognitionEngine Class Example See Also Send Feedback

Gets information about the current instance of SpeechRecognitionEngine.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property RecognizerInfo As RecognizerInfo
    Get
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim value As RecognizerInfo

value = instance.RecognizerInfo
C#
public RecognizerInfo RecognizerInfo { get; }

Property Value

Type: Microsoft.Speech.Recognition..::..RecognizerInfo

Information about the current speech recognizer.

Remarks

To get information about all of the installed speech recognizers for the current system, use the InstalledRecognizers()()()() method.

Examples

The following example gets a partial list of data for the current speech recognition engine. For more information, see RecognizerInfo.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

namespace RecognitionEngine
{
  class Program
  {
    static void Main(string[] args)
    {
      using (SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine())
      {
        Console.WriteLine("Information for the current speech recognition engine:");
        Console.WriteLine("  Name: {0}", recognizer.RecognizerInfo.Name);
        Console.WriteLine("  Culture: {0}", recognizer.RecognizerInfo.Culture.ToString());
        Console.WriteLine("  Description: {0}", recognizer.RecognizerInfo.Description);
      }

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

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SpeechRecognitionEngine(RecognizerInfo)
InstalledRecognizers()()()()
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionEngine Events

[image] [image]

SpeechRecognitionEngine Events
SpeechRecognitionEngine Class See Also Send Feedback

The SpeechRecognitionEngine type exposes the following members.

Events

 | Name | Description
Public event | AudioLevelUpdated | Raised when the SpeechRecognitionEngine reports the level of its audio input.
Public event | AudioSignalProblemOccurred | Raised when the SpeechRecognitionEngine detects a problem in the audio signal.
Public event | AudioStateChanged | Raised when the state changes in the audio being received by the SpeechRecognitionEngine.
Public event | EmulateRecognizeCompleted | Raised when the SpeechRecognitionEngine finalizes an asynchronous recognition operation of emulated input.
Public event | LoadGrammarCompleted | Raised when the SpeechRecognitionEngine finishes the asynchronous loading of a Grammar object.
Public event | RecognizeCompleted | Raised when the SpeechRecognitionEngine finalizes an asynchronous recognition operation.
Public event | RecognizerUpdateReached | Raised when a running SpeechRecognitionEngine pauses to accept modifications.
Public event | SpeechDetected | Raised when the SpeechRecognitionEngine detects input that it can identify as speech.
Public event | SpeechHypothesized | Raised when the SpeechRecognitionEngine has recognized a word or words that may be a component of multiple complete phrases in a grammar.
Public event | SpeechRecognitionRejected | Raised when the SpeechRecognitionEngine receives input that does not match any of its loaded and enabled Grammar objects.
Public event | SpeechRecognized | Raised when the SpeechRecognitionEngine receives input that matches any of its loaded and enabled Grammar objects.
Top

See Also

Reference

SpeechRecognitionEngine Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioLevelUpdated Event

[image]

SpeechRecognitionEngine..::..AudioLevelUpdated Event
SpeechRecognitionEngine Class Example See Also Send Feedback

Raised when the SpeechRecognitionEngine reports the level of its audio input.

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

Syntax

Visual Basic (Declaration)
Public Event AudioLevelUpdated As EventHandler(Of AudioLevelUpdatedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim handler As EventHandler(Of AudioLevelUpdatedEventArgs)

AddHandler instance.AudioLevelUpdated, handler
C#
public event EventHandler<AudioLevelUpdatedEventArgs> AudioLevelUpdated

Remarks

The SpeechRecognitionEngine raises this event multiple times per second. The frequency with which the event is raised depends on the computer on which the application is running.

To get the audio level at the time of the event, use the AudioLevel property of the associated AudioLevelUpdatedEventArgs. To get the current audio level of the input to the recognizer, use the recognizer's AudioLevel property.

When you create an AudioLevelUpdated delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.

Examples

The following example adds a handler for the AudioLevelUpdated event to a SpeechRecognitionEngine object. The handler outputs the new audio level to the console.

Copy image Copy Code
private SpeechRecognitionEngine recognizer;

// Initialize the SpeechRecognitionEngine object.
private void Initialize()
{
  recognizer = new SpeechRecognitionEngine();

  // Add an event handler for the AudioLevelUpdated event.
  recognizer.AudioLevelUpdated +=
   new EventHandler<AudioLevelUpdatedEventArgs>(recognizer_AudioLevelUpdated);

  // Add other initialization code here.

}

// Write the audio level to the console when the AudioLevelUpdated event is raised.
void recognizer_AudioLevelUpdated(object sender, AudioLevelUpdatedEventArgs e)
{
  Console.WriteLine("The audio level is now: {0}.", e.AudioLevel);
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
AudioLevelUpdatedEventArgs
AudioLevel
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioSignalProblemOccurred Event

[image]

SpeechRecognitionEngine..::..AudioSignalProblemOccurred Event
SpeechRecognitionEngine Class Example See Also Send Feedback

Raised when the SpeechRecognitionEngine detects a problem in the audio signal.

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

Syntax

Visual Basic (Declaration)
Public Event AudioSignalProblemOccurred As EventHandler(Of AudioSignalProblemOccurredEventArgs)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim handler As EventHandler(Of AudioSignalProblemOccurredEventArgs)

AddHandler instance.AudioSignalProblemOccurred, handler
C#
public event EventHandler<AudioSignalProblemOccurredEventArgs> AudioSignalProblemOccurred

Remarks

To get which problem occurred, use the AudioSignalProblem property of the associated AudioSignalProblemOccurredEventArgs.

When you create an AudioSignalProblemOccurred delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.

Examples

The following example defines an event handler that gathers information about an AudioSignalProblemOccurred event.

Copy image Copy Code
private SpeechRecognitionEngine recognizer;

// Initialize a SpeechRecognitionEngine object.
private void Initialize()
{
  recognizer = new SpeechRecognitionEngine();

  // Add a handler for the AudioSignalProblemOccurred event.
  recognizer.AudioSignalProblemOccurred +=
    new EventHandler<AudioSignalProblemOccurredEventArgs>(
      recognizer_AudioSignalProblemOccurred);
}

// Gather information when the AudioSignalProblemOccurred event is raised.
void recognizer_AudioSignalProblemOccurred(object sender, AudioSignalProblemOccurredEventArgs e)
{
  StringBuilder details = new StringBuilder();

  details.AppendLine("Audio signal problem information:");
  details.AppendFormat(
    " Audio level:               {0}" + Environment.NewLine +
    " Audio position:            {1}" + Environment.NewLine +
    " Audio signal problem:      {2}" + Environment.NewLine +
    " Recognition engine audio position: {3}" + Environment.NewLine,
    e.AudioLevel, e.AudioPosition,  e.AudioSignalProblem,
    e.recoEngineAudioPosition);

  // Insert additional event handler code here.
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
AudioSignalProblem
AudioSignalProblemOccurredEventArgs
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioStateChanged Event

[image]

SpeechRecognitionEngine..::..AudioStateChanged Event
SpeechRecognitionEngine Class Example See Also Send Feedback

Raised when the state changes in the audio being received by the SpeechRecognitionEngine.

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

Syntax

Visual Basic (Declaration)
Public Event AudioStateChanged As EventHandler(Of AudioStateChangedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim handler As EventHandler(Of AudioStateChangedEventArgs)

AddHandler instance.AudioStateChanged, handler
C#
public event EventHandler<AudioStateChangedEventArgs> AudioStateChanged

Remarks

To get the audio state at the time of the event, use the AudioState property of the associated AudioStateChangedEventArgs. To get the current audio state of the input to the recognizer, use the recognizer's AudioState property. For more information about audio state, see the AudioState enumeration.

When you create an AudioStateChanged delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.

Examples

The following example uses a handler for the AudioStateChanged event to write the recognizer's new AudioState to the console each time it changes, using a member of the AudioState enumeration.

Copy image Copy Code
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.
        Choices animals = new Choices(new string[] { "cow", "pig", "goat" });
        GrammarBuilder farm = new GrammarBuilder("On this farm he had a");
        farm.Append(animals);
        Grammar farmAnimals = new Grammar(farm);
        farmAnimals.Name = "Farm";
        recognizer.LoadGrammar(farmAnimals);

        // Attach event handlers.
        recognizer.AudioStateChanged +=
          new EventHandler<AudioStateChangedEventArgs>(recognizer_AudioStateChanged);
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
        recognizer.LoadGrammarCompleted +=
          new EventHandler<LoadGrammarCompletedEventArgs>(recognizer_LoadGrammarCompleted);

        // Set the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

        // Start recognition.
        recognizer.RecognizeAsync();

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

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

    // Handle the SpeechRecognized event.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      if (e.Result != null && e.Result.Text != null)
      {
        Console.WriteLine();
        Console.WriteLine("  Recognized text =  {0}", e.Result.Text);
        Console.WriteLine();
      }
      else
      {
        Console.WriteLine("  Recognized text not available.");
      }

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

    // Handle the AudioStateChanged event.
    static void recognizer_AudioStateChanged(object sender, AudioStateChangedEventArgs e)
    {
      Console.WriteLine("The new audio state is: " + e.AudioState);
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
AudioState
AudioStateChangedEventArgs
AudioState
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EmulateRecognizeCompleted Event

[image]

SpeechRecognitionEngine..::..EmulateRecognizeCompleted Event
SpeechRecognitionEngine Class Example See Also Send Feedback

Raised when the SpeechRecognitionEngine finalizes an asynchronous recognition operation of emulated input.

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

Syntax

Visual Basic (Declaration)
Public Event EmulateRecognizeCompleted As EventHandler(Of EmulateRecognizeCompletedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim handler As EventHandler(Of EmulateRecognizeCompletedEventArgs)

AddHandler instance.EmulateRecognizeCompleted, handler
C#
public event EventHandler<EmulateRecognizeCompletedEventArgs> EmulateRecognizeCompleted

Remarks

Each EmulateRecognizeAsync method begins an asynchronous recognition operation. The SpeechRecognitionEngine raises the EmulateRecognizeCompleted event when it finalizes the asynchronous operation.

The EmulateRecognizeAsync(String) operation can raise the SpeechDetected, SpeechHypothesized, SpeechRecognitionRejected, and SpeechRecognized events. The EmulateRecognizeCompleted event is the last such event that the recognizer raises for a given operation.

If emulated recognition was successful, you can access the recognition result using the either of the following:

  • The Result property in the EmulateRecognizeCompletedEventArgs object in the handler for the EmulateRecognizeCompleted event.

  • The Result property in the SpeechRecognizedEventArgs object in the handler for the SpeechRecognized event.

If emulated recognition was not successful, the SpeechRecognized event is not raised and the Result will be null.

Note Note

Do not call the [Dispose] method on a SpeechRecognitionEngine from within an event handler.

EmulateRecognizeCompletedEventArgs derives from AsyncCompletedEventArgs.

SpeechRecognizedEventArgs derives from RecognitionEventArgs.

When you create an EmulateRecognizeCompleted delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.

Examples

The following example is part of a console application that loads a speech recognition grammar and demonstrates asynchronous emulated input, the associated recognition results, and the associated events raised by the speech recognizer.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;
using System.Threading;

namespace InProcessRecognizer
{
  class Program
  {
    // Indicate whether the asynchronous emulate recognition
    // operation has completed.
    static bool completed;

    static void Main(string[] args)
    {

      // Initialize a SpeechRecognitionEngine object.
      using (SpeechRecognitionEngine recognizer =
        new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US")))
      {
        // Create and load a sample grammar.
        Grammar testGrammar =
          new Grammar(new GrammarBuilder("testing testing"));
        testGrammar.Name = "Test Grammar";
        recognizer.LoadGrammar(testGrammar);

        // Attach event handlers for recognition events.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(SpeechRecognizedHandler);
        recognizer.EmulateRecognizeCompleted +=
          new EventHandler<EmulateRecognizeCompletedEventArgs>(
            EmulateRecognizeCompletedHandler);

        completed = false;

        // This EmulateRecognizeAsync call mathches the grammar
        // and generates a SpeechRecognized event.
        recognizer.EmulateRecognizeAsync("testing testing");

        // Wait for the asynchronous operation to complete.
        while (!completed)
        {
          Thread.Sleep(333);
        }

        completed = false;

        // This EmulateRecognizeAsync call does not match the grammar
        // or generate a SpeechRecognized event.
        recognizer.EmulateRecognizeAsync("testing one two three");

        // Wait for the asynchronous operation to complete.
        while (!completed)
        {
          Thread.Sleep(333);
        }
      }

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

    // Handle the SpeechRecognized event.
    static void SpeechRecognizedHandler(
      object sender, SpeechRecognizedEventArgs e)
    {
      if (e.Result != null)
      {
        Console.WriteLine("Result of 1st call to EmulateRecognizeAsync = {0}",
          e.Result.Text ?? "<no text>");
        Console.WriteLine();
      }
      else
      {
        Console.WriteLine("No recognition result");
      }
    }

    // Handle the EmulateRecognizeCompleted event.
    static void EmulateRecognizeCompletedHandler(
      object sender, EmulateRecognizeCompletedEventArgs e)
    {
      if (e.Result == null)
      {
        Console.WriteLine("Result of 2nd call to EmulateRecognizeAsync = No result generated.");
      }

      // Indicate the asynchronous operation is complete.
      completed = true;
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
EmulateRecognizeCompletedEventArgs
SpeechRecognized
SpeechDetected
SpeechHypothesized
SpeechRecognitionRejected
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


LoadGrammarCompleted Event

[image]

SpeechRecognitionEngine..::..LoadGrammarCompleted Event
SpeechRecognitionEngine Class Example See Also Send Feedback

Raised when the SpeechRecognitionEngine finishes the asynchronous loading of a Grammar object.

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

Syntax

Visual Basic (Declaration)
Public Event LoadGrammarCompleted As EventHandler(Of LoadGrammarCompletedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim handler As EventHandler(Of LoadGrammarCompletedEventArgs)

AddHandler instance.LoadGrammarCompleted, handler
C#
public event EventHandler<LoadGrammarCompletedEventArgs> LoadGrammarCompleted

Remarks

The recognizer's LoadGrammarAsync method initiates an asynchronous operation. The SpeechRecognitionEngine raises this event when it completes the operation. To get the Grammar object that the recognizer loaded, use the Grammar property of the associated LoadGrammarCompletedEventArgs. To get the current Grammar objects the recognizer has loaded, use the recognizer's Grammars property.

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 create a LoadGrammarCompleted delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.

Examples

The following example creates two speech recognition grammars and constructs a Grammar object from each of the completed grammars. It then asynchronously loads the Grammar objects to the SpeechRecognitionEngine instance. The handler for the recognizer's LoadGrammarCompleted event reports the status of Grammar objects when loaded. The handler for the SpeechRecognized event reports the name of the Grammar object that was used to perform a recognition and the text of the recognition result.

Copy image Copy Code
using System;
using Microsoft.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();

      // 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);

      // Create the "yesno" grammar and build it into a Grammar object.
      Choices yesChoices = new Choices(new string[] { "yes", "yup", "yeah" });
      SemanticResultValue yesValue =
          new SemanticResultValue(yesChoices, (bool)true);
      Choices noChoices = new Choices(new string[] { "no", "nope", "neah" });
      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";

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

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

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

    // 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");
    }

    // 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.
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
RecognizerUpdateReached
UnloadAllGrammars
UnloadGrammar
LoadGrammar
LoadGrammarAsync
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizeCompleted Event

[image]

SpeechRecognitionEngine..::..RecognizeCompleted Event
SpeechRecognitionEngine Class Example See Also Send Feedback

Raised when the SpeechRecognitionEngine finalizes an asynchronous recognition operation.

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

Syntax

Visual Basic (Declaration)
Public Event RecognizeCompleted As EventHandler(Of RecognizeCompletedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim handler As EventHandler(Of RecognizeCompletedEventArgs)

AddHandler instance.RecognizeCompleted, handler
C#
public event EventHandler<RecognizeCompletedEventArgs> RecognizeCompleted

Remarks

The SpeechRecognitionEngine object's RecognizeAsync method initiates an asynchronous recognition operation. When the recognizer finalizes the asynchronous operation, it raises this event.

Using the handler for the RecognizeCompleted event, you can access the RecognitionResult in the RecognizeCompletedEventArgs object. If recognition was not successful, RecognitionResult will be nullNothingnullptrunita null reference (Nothing in Visual Basic). To determine whether a timeout or an interruption in audio input caused recognition to fail, you can access the properties for InitialSilenceTimeout, BabbleTimeout, or InputStreamEnded.

Note Note

Do not call the [Dispose] method on a SpeechRecognitionEngine from within an event handler.

See the RecognizeCompletedEventArgs class for more information.

To obtain details on the best rejected recognition candidates, attach a handler for the SpeechRecognitionRejected event.

When you create a RecognizeCompleted delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.

Examples

The following example recognizes phrases such as "Display the list of artists in the jazz category" or "Display albums gospel". The example uses a handler for the RecognizeCompleted event to display information about the results of recognition in the console.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

    // Initialize a SpeechRecognitionEngine object.
    {
      using (SpeechRecognitionEngine recognizer =
         new SpeechRecognitionEngine())
      {

        //  Create lists of alternative choices.
        Choices listTypes = new Choices(new string[] { "albums", "artists" });
        Choices genres = new Choices(new string[] {
          "blues", "classical", "gospel", "jazz", "rock" });

        //  Create a GrammarBuilder object and assemble the grammar components.
        GrammarBuilder mediaMenu = new GrammarBuilder("Display");
        mediaMenu.Append("the list of", 0, 1);
        mediaMenu.Append(listTypes);
        mediaMenu.Append("in the", 0, 1);
        mediaMenu.Append(genres);
        mediaMenu.Append("category.", 0, 1);

        //  Build a Grammar object from the GrammarBuilder.
        Grammar mediaMenuGrammar = new Grammar(mediaMenu);
        mediaMenuGrammar.Name = "Media Chooser";

        // Attach event handlers.
        recognizer.RecognizeCompleted +=
          new EventHandler<RecognizeCompletedEventArgs>(recognizer_RecognizeCompleted);
        recognizer.LoadGrammarCompleted +=
          new EventHandler<LoadGrammarCompletedEventArgs>(recognizer_LoadGrammarCompleted);

        // Load the grammar object to the recognizer.
        recognizer.LoadGrammarAsync(mediaMenuGrammar);

        // Set the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

        // 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:");
        Console.WriteLine("  Grammar: " + e.Result.Grammar.Name);
        Console.WriteLine("  Recognized text: " + e.Result.Text);
        Console.WriteLine("  Confidence score: " + e.Result.Confidence);
        Console.WriteLine("  Audio position: " + 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)
    {
      Console.WriteLine("Grammar loaded:  " + e.Grammar.Name);
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
RecognizeCompletedEventArgs
RecognizeAsync
SpeechRecognized
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RecognizerUpdateReached Event

[image]

SpeechRecognitionEngine..::..RecognizerUpdateReached Event
SpeechRecognitionEngine Class Example See Also Send Feedback

Raised when a running SpeechRecognitionEngine pauses to accept modifications.

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

Syntax

Visual Basic (Declaration)
Public Event RecognizerUpdateReached As EventHandler(Of RecognizerUpdateReachedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim handler As EventHandler(Of RecognizerUpdateReachedEventArgs)

AddHandler instance.RecognizerUpdateReached, handler
C#
public event EventHandler<RecognizerUpdateReachedEventArgs> RecognizerUpdateReached

Remarks

Applications must use RequestRecognizerUpdate()()()() to pause a running instance of SpeechRecognitionEngine before modifying its settings or its Grammar objects. The SpeechRecognitionEngine raises this event when it is ready to accept modifications.

For example, while the SpeechRecognitionEngine is paused, you can load, unload, enable, and disable Grammar objects, and modify values for the BabbleTimeout, InitialSilenceTimeout, and EndSilenceTimeout properties. For more information, see the RequestRecognizerUpdate method.

When you create a RecognizerUpdateReached delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.

Examples

The following example shows a console application that loads and unloads Grammar objects. The application uses the RequestRecognizerUpdate()()()() method to request the speech recognition engine to pause so it can receive an update. The application then loads or unloads a Grammar object.

At each update, a handler for RecognizerUpdateReached event writes the name and status of the currently loaded Grammar objects to the console. As grammars are loaded and unloaded, the application first recognizes the names of farm animals, then the names of farm animals and the names of fruits, then only the names of fruits.

Copy image Copy Code
using System;
using System.Speech.Recognition;
using System.Collections.Generic;
using System.Threading;

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

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

        // Create the first grammar - Farm.
        Choices animals = new Choices(new string[] { "cow", "pig", "goat" });
        GrammarBuilder farm = new GrammarBuilder(animals);
        Grammar farmAnimals = new Grammar(farm);
        farmAnimals.Name = "Farm";

        // Create the second grammar - Fruit.
        Choices fruit = new Choices(new string[] { "apples", "peaches", "oranges" });
        GrammarBuilder favorite = new GrammarBuilder(fruit);
        Grammar favoriteFruit = new Grammar(favorite);
        favoriteFruit.Name = "Fruit";

        // Attach event handlers.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
        recognizer.RecognizerUpdateReached +=
          new EventHandler<RecognizerUpdateReachedEventArgs>(recognizer_RecognizerUpdateReached);
        recognizer.SpeechRecognitionRejected +=
          new EventHandler<SpeechRecognitionRejectedEventArgs>(recognizer_SpeechRecognitionRejected);

        // Load the Farm grammar.
        recognizer.LoadGrammar(farmAnimals);
        Console.WriteLine("Grammar Farm is loaded");

        // Start asynchronous, continuous recognition.
        recognizer.RecognizeAsync(RecognizeMode.Multiple);
        Console.WriteLine("Starting asynchronous, continuous recognition");

        // Pause to recognize farm animals.
        Thread.Sleep(7000);
        Console.WriteLine();

        // Request an update and load the Fruit grammar.
        recognizer.RequestRecognizerUpdate();
        recognizer.LoadGrammarAsync(favoriteFruit);
        Thread.Sleep(7000);

        // Request an update and unload the Farm grammar.
        recognizer.RequestRecognizerUpdate();
        recognizer.UnloadGrammar(farmAnimals);
        Thread.Sleep(7000);
      }

      // Keep the console window open.
      Console.WriteLine();
      Console.WriteLine("Press any key to exit...");
      Console.ReadKey();
    }

    // At the update, get the names and enabled status of the currently loaded grammars.
    public static void recognizer_RecognizerUpdateReached(
      object sender, RecognizerUpdateReachedEventArgs e)
    {
      Console.WriteLine();
      Console.WriteLine("Update reached:");
      Thread.Sleep(1000);

      string qualifier;
      List<Grammar> grammars = new List<Grammar>(recognizer.Grammars);
      foreach (Grammar g in grammars)
      {
        qualifier = (g.Enabled) ? "enabled" : "disabled";
        Console.WriteLine("  Grammar {0} is loaded and is {1}.",
        g.Name, qualifier);
      }
    }

    // Write the text of the recognized phrase to the console.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine("  Speech recognized: " + e.Result.Text);
    }

    // Write a message to the console when recognition fails.
    static void recognizer_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
    {
      Console.WriteLine("  Recognition attempt failed");
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
RecognizerUpdateReachedEventArgs
RequestRecognizerUpdate
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechDetected Event

[image]

SpeechRecognitionEngine..::..SpeechDetected Event
SpeechRecognitionEngine Class Example See Also Send Feedback

Raised when the SpeechRecognitionEngine detects input that it can identify as speech.

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

Syntax

Visual Basic (Declaration)
Public Event SpeechDetected As EventHandler(Of SpeechDetectedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim handler As EventHandler(Of SpeechDetectedEventArgs)

AddHandler instance.SpeechDetected, handler
C#
public event EventHandler<SpeechDetectedEventArgs> SpeechDetected

Remarks

Each speech recognizer has an algorithm to distinguish between silence and speech. When the SpeechRecognitionEngine performs a speech recognition operation, it raises the SpeechDetected event when its algorithm identifies the input as speech. The AudioPosition property of the associated SpeechDetectedEventArgs object indicates location in the input stream where the recognizer detected speech. The SpeechRecognitionEngine raises the SpeechDetected event before it raises any of the SpeechHypothesized, SpeechRecognized, or SpeechRecognitionRejected events.

For more information see the Recognize, RecognizeAsync, EmulateRecognize, and EmulateRecognizeAsync methods.

When you create a SpeechDetected delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.

Examples

The following example is part of a console application for choosing origin and destination cities for a flight. The application recognizes phrases such as "I want to fly from Miami to Chicago." The example uses the SpeechDetected event to report the AudioPosition each time speech is detected.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

    // Initialize a SpeechRecognitionEngine object.
    {
      using (SpeechRecognitionEngine recognizer =
         new SpeechRecognitionEngine())
      {

        // Create a grammar.
        Choices cities = new Choices(new string[] {
          "Los Angeles", "New York", "Chicago", "San Francisco", "Miami", "Dallas" });

        GrammarBuilder gb = new GrammarBuilder();
        gb.Append("I would like to fly from");
        gb.Append(cities);
        gb.Append("to");
        gb.Append(cities);

        // Create a Grammar object and load it to the recognizer.
        Grammar g = new Grammar(gb);
        g.Name = ("City Chooser");
        recognizer.LoadGrammarAsync(g);

        // Attach event handlers.
        recognizer.LoadGrammarCompleted +=
          new EventHandler<LoadGrammarCompletedEventArgs>(recognizer_LoadGrammarCompleted);
        recognizer.SpeechDetected +=
          new EventHandler<SpeechDetectedEventArgs>(recognizer_SpeechDetected);
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

        // Set the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

        // Start recognition.
        recognizer.RecognizeAsync();

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

    // Handle the SpeechDetected event.
    static void recognizer_SpeechDetected(object sender, SpeechDetectedEventArgs e)
    {
      Console.WriteLine("  Speech detected at AudioPosition = {0}", e.AudioPosition);
    }

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

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

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SpeechRecognitionEngine
SpeechDetectedEventArgs
RecognitionEventArgs
SpeechHypothesized
SpeechRecognitionRejected
SpeechRecognized
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechHypothesized Event

[image]

SpeechRecognitionEngine..::..SpeechHypothesized Event
SpeechRecognitionEngine Class Example See Also Send Feedback

Raised when the SpeechRecognitionEngine has recognized a word or words that may be a component of multiple complete phrases in a grammar.

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

Syntax

Visual Basic (Declaration)
Public Event SpeechHypothesized As EventHandler(Of SpeechHypothesizedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim handler As EventHandler(Of SpeechHypothesizedEventArgs)

AddHandler instance.SpeechHypothesized, handler
C#
public event EventHandler<SpeechHypothesizedEventArgs> SpeechHypothesized

Remarks

The SpeechRecognitionEngine generates numerous SpeechHypothesized events as it attempts to identify an input phrase. You can access the text of partially recognized phrases in the Result property of the SpeechHypothesizedEventArgs object in the handler for the SpeechHypothesized event. Typically, handling these events is useful only for debugging.

SpeechHypothesizedEventArgs derives from RecognitionEventArgs.

For more information see the EndSilenceTimeoutAmbiguous property and the Recognize, RecognizeAsync, EmulateRecognize, and EmulateRecognizeAsync methods.

When you create a SpeechHypothesized delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.

Examples

The following example recognizes phrases such as "Display the list of artists in the jazz category". The example uses the SpeechHypothesized event to display incomplete phrase fragments in the console as they are recognized.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;

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

    // Initialize a SpeechRecognitionEngine object.
    {
      using (SpeechRecognitionEngine recognizer =
         new SpeechRecognitionEngine())
      {

        // Create a grammar.
        //  Create lists of alternative choices.
        Choices listTypes = new Choices(new string[] { "albums", "artists" });
        Choices genres = new Choices(new string[] {
          "blues", "classical", "gospel", "jazz", "rock" });

        //  Create a GrammarBuilder object and assemble the grammar components.
        GrammarBuilder mediaMenu = new GrammarBuilder("Display the list of");
        mediaMenu.Append(listTypes);
        mediaMenu.Append("in the");
        mediaMenu.Append(genres);
        mediaMenu.Append("category.");

        //  Build a Grammar object from the GrammarBuilder.
        Grammar mediaMenuGrammar = new Grammar(mediaMenu);
        mediaMenuGrammar.Name = "Media Chooser";

        // Attach event handlers.
        recognizer.LoadGrammarCompleted +=
          new EventHandler<LoadGrammarCompletedEventArgs>(recognizer_LoadGrammarCompleted);
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
        recognizer.SpeechHypothesized +=
          new EventHandler<SpeechHypothesizedEventArgs>(recognizer_SpeechHypothesized);

        // Load the grammar object to the recognizer.
        recognizer.LoadGrammarAsync(mediaMenuGrammar);

        // Set the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

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

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

    // Handle the SpeechHypothesized event.
    static void recognizer_SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
    {
      Console.WriteLine("Speech hypothesized: " + e.Result.Text);
    }

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

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

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SpeechRecognitionEngine
RecognitionEventArgs
SpeechHypothesizedEventArgs
SpeechDetected
SpeechRecognitionRejected
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionRejected Event

[image]

SpeechRecognitionEngine..::..SpeechRecognitionRejected Event
SpeechRecognitionEngine Class Example See Also Send Feedback

Raised when the SpeechRecognitionEngine receives input that does not match any of its loaded and enabled Grammar objects.

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

Syntax

Visual Basic (Declaration)
Public Event SpeechRecognitionRejected As EventHandler(Of SpeechRecognitionRejectedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim handler As EventHandler(Of SpeechRecognitionRejectedEventArgs)

AddHandler instance.SpeechRecognitionRejected, handler
C#
public event EventHandler<SpeechRecognitionRejectedEventArgs> SpeechRecognitionRejected

Remarks

The recognizer raises this event if it determines that input does not match with sufficient confidence any of its loaded and enabled Grammar objects. The Result property of the SpeechRecognitionRejectedEventArgs contains the rejected RecognitionResult object. You can use the handler for the SpeechRecognitionRejected event to retrieve recognition Alternates that were rejected and their Confidence scores.

If your application is using a SpeechRecognitionEngine instance, you can modify the confidence level at which speech input is accepted or rejected with one of the UpdateRecognizerSetting()()()() methods. You can modify how the speech recognition responds to non-speech input using the BabbleTimeout, InitialSilenceTimeout, EndSilenceTimeout, and EndSilenceTimeoutAmbiguous properties.

When you create a SpeechRecognitionRejected delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.

Examples

The following example recognizes phrases such as "Display the list of artists in the jazz category" or "Display albums gospel". The example uses a handler for the SpeechRecognitionRejected event to display a notification in the console when the speech input cannot be matched to the contents of the grammar with sufficient Confidence to produce a successful recognition. The handler also displays recognition result Alternates that were rejected because of low confidence scores.

Copy image Copy Code
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 a grammar.
        //  Create lists of alternative choices.
        Choices listTypes = new Choices(new string[] { "albums", "artists" });
        Choices genres = new Choices(new string[] {
          "blues", "classical", "gospel", "jazz", "rock" });

        //  Create a GrammarBuilder object and assemble the grammar components.
        GrammarBuilder mediaMenu = new GrammarBuilder("Display");
        mediaMenu.Append("the list of", 0, 1);
        mediaMenu.Append(listTypes);
        mediaMenu.Append("in the", 0, 1);
        mediaMenu.Append(genres);
        mediaMenu.Append("category", 0, 1);

        //  Build a Grammar object from the GrammarBuilder.
        Grammar mediaMenuGrammar = new Grammar(mediaMenu);
        mediaMenuGrammar.Name = "Media Chooser";

        // Attach event handlers.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
        recognizer.SpeechRecognitionRejected +=
          new EventHandler<SpeechRecognitionRejectedEventArgs>(recognizer_SpeechRecognitionRejected);

        // Load the grammar object to the recognizer.
        recognizer.LoadGrammarAsync(mediaMenuGrammar);

        // Set the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

        // Start asynchronous, continuous recognition.
        recognizer.RecognizeAsync(RecognizeMode.Multiple);
        Console.WriteLine("Starting asynchronous recognition...");

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

    // Handle the SpeechRecognitionRejected event.
    static void recognizer_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
    {
      Console.WriteLine("Speech input was rejected.");
      foreach (RecognizedPhrase phrase in e.Result.Alternates)
      {
        Console.WriteLine("  Rejected phrase: " + phrase.Text);
        Console.WriteLine("  Confidence score: " + phrase.Confidence);
        Console.WriteLine("  Grammar name:  " + phrase.Grammar.Name);
      }
    }

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

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SpeechRecognitionEngine
RecognitionEventArgs
SpeechRecognitionRejectedEventArgs
SpeechDetected
SpeechHypothesized
SpeechRecognized
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognized Event

[image]

SpeechRecognitionEngine..::..SpeechRecognized Event
SpeechRecognitionEngine Class Example See Also Send Feedback

Raised when the SpeechRecognitionEngine receives input that matches any of its loaded and enabled Grammar objects.

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

Syntax

Visual Basic (Declaration)
Public Event SpeechRecognized As EventHandler(Of SpeechRecognizedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechRecognitionEngine
Dim handler As EventHandler(Of SpeechRecognizedEventArgs)

AddHandler instance.SpeechRecognized, handler
C#
public event EventHandler<SpeechRecognizedEventArgs> SpeechRecognized

Remarks

You can initiate a recognition operation using the one of the Recognize()()()() or RecognizeAsync()()()() methods. The recognizer raises the SpeechRecognized event if it determines that input matches one of its loaded Grammar objects with a sufficient level of confidence to constitute recognition. The Result property of the SpeechRecognitionRejectedEventArgs contains the accepted RecognitionResult object. Handlers of SpeechRecognized events can obtain the recognized phrase as well as a list of recognition Alternates with lower confidence scores.

You can modify the confidence level at which the SpeechRecognitionEngine accepts or rejects speech input with one of the UpdateRecognizerSetting()()()() methods. You can modify how the speech recognition responds to non-speech input using the BabbleTimeout, InitialSilenceTimeout, EndSilenceTimeout, and EndSilenceTimeoutAmbiguous properties.

When the recognizer receives input that matches a grammar, the Grammar object can raise its SpeechRecognized event. The Grammar object's SpeechRecognized event is raised prior to the speech recognizer's SpeechRecognized event. Any tasks specific to a particular grammar should always be performed by a handler for the SpeechRecognized event.

When you create a SpeechRecognized delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.

Examples

The following example is part of a console application that creates a speech recognition grammar, constructs a Grammar object, and loads it into the SpeechRecognitionEngine to perform recognition. The grammar recognizes spoken input such as "I want to fly from Chicago to Miami". The example retrieves information from the recognition result using a handler for the SpeechRecognized event.

Copy image Copy Code
using System;
using System.Collections.Generic;
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 SemanticResultValue objects that contain cities and airport codes.
        SemanticResultValue chicago = new SemanticResultValue("Chicago", "ORD");
        SemanticResultValue boston = new SemanticResultValue("Boston", "BOS");
        SemanticResultValue miami = new SemanticResultValue("Miami", "MIA");
        SemanticResultValue dallas = new SemanticResultValue("Dallas", "DFW");

        // Create a Choices object and add the SemanticResultValue objects.
        Choices cities = new Choices();
        cities.Add(new Choices(new GrammarBuilder[] { chicago, boston, miami, dallas }));

        // Build the phrase and add SemanticResultKeys.
        GrammarBuilder chooseCities = new GrammarBuilder();
        chooseCities.Append("I want to fly from");
        chooseCities.Append(new SemanticResultKey("origin", cities));
        chooseCities.Append("to");
        chooseCities.Append(new SemanticResultKey("destination", cities));

        // Build a Grammar object from the GrammarBuilder.
        Grammar bookFlight = new Grammar(chooseCities);
        bookFlight.Name = "Book Flight";

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

        // Load the grammar object to the recognizer.
        recognizer.LoadGrammarAsync(bookFlight);

        // Set the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

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

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

    // Handle the SpeechRecognized event.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine("Recognition result summary:");
      Console.WriteLine(
        "  Recognized phrase: {0}\n" +
        "  Confidence score {1}\n" +
        "  Grammar used: {2}\n",
        e.Result.Text, e.Result.Confidence, e.Result.Grammar.Name);

      // Display the semantic values in the recognition result.
      Console.WriteLine("  Semantic results:");
      foreach (KeyValuePair<String, SemanticValue> child in e.Result.Semantics)
      {
        Console.WriteLine("    The {0} city is {1}",
          child.Key, child.Value.Value ?? "null");
      }
      Console.WriteLine();

      // Display information about the words in the recognition result.
      Console.WriteLine("  Word summary: ");
      foreach (RecognizedWordUnit word in e.Result.Words)
      {
        Console.WriteLine(
          "    Lexical form ({1})" +
          " Pronunciation ({0})" +
          " Display form ({2})",
          word.Pronunciation, word.LexicalForm, word.DisplayAttributes);
      }

      // Display information about the audio in the recognition result.
      Console.WriteLine("  Input audio summary:\n" +
            "    Candidate Phrase at:       {0} mSec\n" +
            "    Phrase Length:             {1} mSec\n" +
            "    Input State Time:          {2}\n" +
            "    Input Format:              {3}\n",
            e.Result.Audio.AudioPosition,
            e.Result.Audio.Duration,
            e.Result.Audio.StartTime,
            e.Result.Audio.Format.EncodingFormat);

      // Display information about the alternate recognitions in the recognition result.
      Console.WriteLine("  Alternate phrase collection:");
      foreach (RecognizedPhrase phrase in e.Result.Alternates)
      {
        Console.WriteLine("    Phrase: " + phrase.Text);
        Console.WriteLine("    Confidence score: " + phrase.Confidence);
      }

      // Display information about text that was replaced during normalization.
      if (e.Result.ReplacementWordUnits.Count != 0)
      {
        Console.WriteLine("  Replacement text:\n");
        foreach (ReplacementText rep in e.Result.ReplacementWordUnits)
        {
          Console.WriteLine("      At index {0} for {1} words. Text: {2}\n",
          rep.FirstWordIndex, rep.CountOfWords, rep.Text);
        }
        //label.Text += String.Format("\n\n");

      }
      else
      {
        Console.WriteLine();
        Console.WriteLine("No text was replaced");
      }
    }
  }
}

See Also

Reference

SpeechRecognitionEngine Class
SpeechRecognitionEngine Members
Microsoft.Speech.Recognition Namespace
SpeechRecognitionEngine
RecognitionEventArgs
SpeechRecognitionRejectedEventArgs
SpeechDetected
SpeechHypothesized
SpeechRecognitionRejected
SpeechRecognized
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionRejectedEventArgs Class

[image]

SpeechRecognitionRejectedEventArgs Class
Members Example See Also Send Feedback

Provides information for the SpeechRecognitionRejected event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Recognition..::..RecognitionEventArgs
Microsoft.Speech.Recognition..::..SpeechRecognitionRejectedEventArgs

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class SpeechRecognitionRejectedEventArgs _
    Inherits RecognitionEventArgs
Visual Basic (Usage)
Dim instance As SpeechRecognitionRejectedEventArgs
C#
[SerializableAttribute]
public class SpeechRecognitionRejectedEventArgs : RecognitionEventArgs

Remarks

An instance of SpeechRecognitionRejectedEventArgs is created when the SpeechRecognitionEngine object raises the SpeechRecognitionRejected event at the completion of a RecognizeAsync()()()() operation.

The SpeechRecognitionEngine raises the SpeechRecognitionRejected when none of the Alternates generated by a recognition operation have a high enough Confidence score to be accepted. To obtain detailed information about rejected phrases, access the Result property in the handler for the event.

SpeechRecognitionRejectedEventArgs derives from RecognitionEventArgs.

Examples

The following example recognizes phrases such as "Display the list of artists in the jazz category" or "Display albums gospel". The example uses a handler for the SpeechRecognitionRejected event to display a notification in the console when the speech input cannot be matched to the contents of the grammar with sufficient Confidence to produce a successful recognition. The handler also displays recognition result Alternates that were rejected because of low confidence scores.

Copy image Copy Code
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 a grammar.
        //  Create lists of alternative choices.
        Choices listTypes = new Choices(new string[] { "albums", "artists" });
        Choices genres = new Choices(new string[] {
          "blues", "classical", "gospel", "jazz", "rock" });

        //  Create a GrammarBuilder object and assemble the grammar components.
        GrammarBuilder mediaMenu = new GrammarBuilder("Display");
        mediaMenu.Append("the list of", 0, 1);
        mediaMenu.Append(listTypes);
        mediaMenu.Append("in the", 0, 1);
        mediaMenu.Append(genres);
        mediaMenu.Append("category", 0, 1);

        //  Build a Grammar object from the GrammarBuilder.
        Grammar mediaMenuGrammar = new Grammar(mediaMenu);
        mediaMenuGrammar.Name = "Media Chooser";

        // Attach event handlers.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
        recognizer.SpeechRecognitionRejected +=
          new EventHandler<SpeechRecognitionRejectedEventArgs>(recognizer_SpeechRecognitionRejected);

        // Load the grammar object to the recognizer.
        recognizer.LoadGrammarAsync(mediaMenuGrammar);

        // Set the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

        // Start asynchronous, continuous recognition.
        recognizer.RecognizeAsync(RecognizeMode.Multiple);
        Console.WriteLine("Starting asynchronous recognition...");

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

    // Handle the SpeechRecognitionRejected event.
    static void recognizer_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
    {
      Console.WriteLine("Speech input was rejected.");
      foreach (RecognizedPhrase phrase in e.Result.Alternates)
      {
        Console.WriteLine("  Rejected phrase: " + phrase.Text);
        Console.WriteLine("  Confidence score: " + phrase.Confidence);
        Console.WriteLine("  Grammar name:  " + phrase.Grammar.Name);
      }
    }

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

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SpeechRecognitionRejectedEventArgs Members
Microsoft.Speech.Recognition Namespace
RecognitionEventArgs
RecognitionResult
SpeechRecognitionRejected
SpeechRecognized
SpeechRecognizedEventArgs
SpeechHypothesized
SpeechHypothesizedEventArgs
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionRejectedEventArgs Members

[image] [image]

SpeechRecognitionRejectedEventArgs Members
SpeechRecognitionRejectedEventArgs Class Methods Properties See Also Send Feedback

Provides information for the SpeechRecognitionRejected event.

The SpeechRecognitionRejectedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Result | Gets the results of the speech or DTMF recognition operation. (Inherited from RecognitionEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeechRecognitionRejectedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionRejectedEventArgs Methods

[image] [image]

SpeechRecognitionRejectedEventArgs Methods
SpeechRecognitionRejectedEventArgs Class See Also Send Feedback

The SpeechRecognitionRejectedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeechRecognitionRejectedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognitionRejectedEventArgs Properties

[image] [image]

SpeechRecognitionRejectedEventArgs Properties
SpeechRecognitionRejectedEventArgs Class See Also Send Feedback

The SpeechRecognitionRejectedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Result | Gets the results of the speech or DTMF recognition operation. (Inherited from RecognitionEventArgs.)
Top

See Also

Reference

SpeechRecognitionRejectedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognizedEventArgs Class

[image]

SpeechRecognizedEventArgs Class
Members Example See Also Send Feedback

Provides information for the Grammar..::..SpeechRecognized and SpeechRecognitionEngine..::..SpeechRecognized events.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Recognition..::..RecognitionEventArgs
Microsoft.Speech.Recognition..::..SpeechRecognizedEventArgs

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class SpeechRecognizedEventArgs _
    Inherits RecognitionEventArgs
Visual Basic (Usage)
Dim instance As SpeechRecognizedEventArgs
C#
[SerializableAttribute]
public class SpeechRecognizedEventArgs : RecognitionEventArgs

Remarks

An instance of SpeechRecognizedEventArgs is created when the SpeechRecognitionEngine object or the Grammar object raises a SpeechRecognized event during a recognition operation. You can initiate a recognition operation using the one of the Recognize()()()() or RecognizeAsync()()()() methods.

SpeechRecognized events are generated when one or more of the Alternates from a recognition operation have a high enough Confidence score to be accepted. To obtain detailed information about a recognized phrase, access the Result property in the handler for the event.

SpeechRecognizedEventArgs derives from RecognitionEventArgs.

Examples

The following example is part of a console application that creates a speech recognition grammar, constructs a Grammar object, and loads it into the SpeechRecognitionEngine to perform recognition. The grammar recognizes spoken input such as "I want to fly from Chicago to Miami". The example retrieves information from the recognition result using a handler for the SpeechRecognized event.

Copy image Copy Code
using System;
using System.Collections.Generic;
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 SemanticResultValue objects that contain cities and airport codes.
        SemanticResultValue chicago = new SemanticResultValue("Chicago", "ORD");
        SemanticResultValue boston = new SemanticResultValue("Boston", "BOS");
        SemanticResultValue miami = new SemanticResultValue("Miami", "MIA");
        SemanticResultValue dallas = new SemanticResultValue("Dallas", "DFW");

        // Create a Choices object and add the SemanticResultValue objects.
        Choices cities = new Choices();
        cities.Add(new Choices(new GrammarBuilder[] { chicago, boston, miami, dallas }));

        // Build the phrase and add SemanticResultKeys.
        GrammarBuilder chooseCities = new GrammarBuilder();
        chooseCities.Append("I want to fly from");
        chooseCities.Append(new SemanticResultKey("origin", cities));
        chooseCities.Append("to");
        chooseCities.Append(new SemanticResultKey("destination", cities));

        // Build a Grammar object from the GrammarBuilder.
        Grammar bookFlight = new Grammar(chooseCities);
        bookFlight.Name = "Book Flight";

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

        // Load the grammar object to the recognizer.
        recognizer.LoadGrammarAsync(bookFlight);

        // Set the input to the recognizer.
        recognizer.SetInputToDefaultAudioDevice();

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

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

    // Handle the SpeechRecognized event.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine("Recognition result summary:");
      Console.WriteLine(
        "  Recognized phrase: {0}\n" +
        "  Confidence score {1}\n" +
        "  Grammar used: {2}\n",
        e.Result.Text, e.Result.Confidence, e.Result.Grammar.Name);

      // Display the semantic values in the recognition result.
      Console.WriteLine("  Semantic results:");
      foreach (KeyValuePair<String, SemanticValue> child in e.Result.Semantics)
      {
        Console.WriteLine("    The {0} city is {1}",
          child.Key, child.Value.Value ?? "null");
      }
      Console.WriteLine();

      // Display information about the words in the recognition result.
      Console.WriteLine("  Word summary: ");
      foreach (RecognizedWordUnit word in e.Result.Words)
      {
        Console.WriteLine(
          "    Lexical form ({1})" +
          " Pronunciation ({0})" +
          " Display form ({2})",
          word.Pronunciation, word.LexicalForm, word.DisplayAttributes);
      }

      // Display information about the audio in the recognition result.
      Console.WriteLine("  Input audio summary:\n" +
            "    Candidate Phrase at:       {0} mSec\n" +
            "    Phrase Length:             {1} mSec\n" +
            "    Input State Time:          {2}\n" +
            "    Input Format:              {3}\n",
            e.Result.Audio.AudioPosition,
            e.Result.Audio.Duration,
            e.Result.Audio.StartTime,
            e.Result.Audio.Format.EncodingFormat);

      // Display information about the alternate recognitions in the recognition result.
      Console.WriteLine("  Alternate phrase collection:");
      foreach (RecognizedPhrase phrase in e.Result.Alternates)
      {
        Console.WriteLine("    Phrase: " + phrase.Text);
        Console.WriteLine("    Confidence score: " + phrase.Confidence);
      }

      // Display information about text that was replaced during normalization.
      if (e.Result.ReplacementWordUnits.Count != 0)
      {
        Console.WriteLine("  Replacement text:\n");
        foreach (ReplacementText rep in e.Result.ReplacementWordUnits)
        {
          Console.WriteLine("      At index {0} for {1} words. Text: {2}\n",
          rep.FirstWordIndex, rep.CountOfWords, rep.Text);
        }
        //label.Text += String.Format("\n\n");

      }
      else
      {
        Console.WriteLine();
        Console.WriteLine("No text was replaced");
      }
    }
  }
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SpeechRecognizedEventArgs Members
Microsoft.Speech.Recognition Namespace
RecognitionEventArgs
RecognitionResult
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognizedEventArgs Members

[image] [image]

SpeechRecognizedEventArgs Members
SpeechRecognizedEventArgs Class Methods Properties See Also Send Feedback

Provides information for the Grammar..::..SpeechRecognized and SpeechRecognitionEngine..::..SpeechRecognized events.

The SpeechRecognizedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | IsExtendable | Gets whether this recognition can be extended by additional input.
Public property | Result | Gets the results of the speech or DTMF recognition operation. (Inherited from RecognitionEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeechRecognizedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognizedEventArgs Methods

[image] [image]

SpeechRecognizedEventArgs Methods
SpeechRecognizedEventArgs Class See Also Send Feedback

The SpeechRecognizedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeechRecognizedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechRecognizedEventArgs Properties

[image] [image]

SpeechRecognizedEventArgs Properties
SpeechRecognizedEventArgs Class See Also Send Feedback

The SpeechRecognizedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | IsExtendable | Gets whether this recognition can be extended by additional input.
Public property | Result | Gets the results of the speech or DTMF recognition operation. (Inherited from RecognitionEventArgs.)
Top

See Also

Reference

SpeechRecognizedEventArgs Class
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


IsExtendable Property

[image]

SpeechRecognizedEventArgs..::..IsExtendable Property
SpeechRecognizedEventArgs Class See Also Send Feedback

Gets whether this recognition can be extended by additional input.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property IsExtendable As Boolean
    Get
Visual Basic (Usage)
Dim instance As SpeechRecognizedEventArgs
Dim value As Boolean

value = instance.IsExtendable
C#
public bool IsExtendable { get; }

Property Value

Type: System..::..Boolean

Returns true if the recognition can be extended, and false otherwise.

Remarks

If a grammar is capable of recognizing the utterances "one two" and "one two three", the utterance "one two" is considered an extendable recognition.

See Also

Reference

SpeechRecognizedEventArgs Class
SpeechRecognizedEventArgs Members
Microsoft.Speech.Recognition Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SubsetMatchingMode Enumeration

[image]

SubsetMatchingMode Enumeration
Example See Also Send Feedback

Enumerates values of subset matching mode.

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

Syntax

Visual Basic (Declaration)
Public Enumeration SubsetMatchingMode
Visual Basic (Usage)
Dim instance As SubsetMatchingMode
C#
public enum SubsetMatchingMode

Members

Member name | Description
Subsequence | Indicates that subset matching mode is Subsequence.
OrderedSubset | Indicates that subset matching mode is OrderedSubset.
SubsequenceContentRequired | Indicates that subset matching mode is SubsequenceContentRequired.
OrderedSubsetContentRequired | Indicates that subset matching mode is OrderedSubsetContentRequired.

Remarks

Using the Microsoft Speech Platform SDK 11, you can construct a grammar that successfully recognizes a phrase even though only a subset of its contents is found in the audio input.

By default, a recognition engine requires an exact match against an entire phrase. The recognition engine can also match partial phrases according to parameters defined by a SubsetMatchingMode member used as an argument to the GrammarBuilder(String, SubsetMatchingMode) constructor or the Append method.

The following illustrates how each of the SubsetMatchingMode members affects recognition when used in a grammar that contains the phrase "a car the truck a boat that plane".

OrderedSubset

This mode indicates that a subset of the phrase will be used to successfully recognize the entire phrase if the following are true:

  • One or more words in the phrase are recognized in the audio input.

  • The relative order of those recognized words is the same as in the phrase.

  • Matched words may consist of only prepositions and articles.

Adding the phrase "a car the truck a boat that plane" to a grammar using OrderedSubset mode produces the following result on recognition:

Input Phrase | Result
"a car the truck a boat that plane" | The entire phrase "a car the truck a boat that plane" is recognized.
"a car the truck a boat" | The entire phrase "a car the truck a boat that plane" is recognized.
"a car the that plane" | The entire phrase "a car the truck a boat that plane" is recognized. A recognized subset is not required to be a sequence of the original string.
"a car the boat a truck that plane" | Recognition is not successful. The words are out of order.
"a the" | The entire phrase "a car the truck a boat that plane" is recognized. Prepositions and articles are used for recognition.

OrderedSubsetContentRequired

This mode indicates that a subset of the phrase will be used to successfully recognize the entire phrase if the following are true:

  • One or more words in the phrase are recognized in the audio input, and

  • The relative order of those recognized words is the same as in the phrase.

  • Matched words cannot consist of only prepositions and articles.

Adding the phrase "a car the truck a boat that plane" to a grammar using OrderedSubsetContentRequired mode produces the following result on recognition:

Input Phrase | Result
"a car the truck a boat that plane" | The entire phrase "a car the truck a boat that plane" is recognized.
"a car the truck a boat" | The entire phrase "a car the truck a boat that plane" is recognized.
"a car the that plane" | The entire phrase "a car the truck a boat that plane" is recognized. A recognized subset is not required to be a sequence of the original string.
"a car the boat a truck that plane" | Recognition is not successful. The words are out of order.
"a the" | Recognition is not successful. Speech input must contain words other than articles and prepositions.

Subsequence:

This mode indicates that a subset of the phrase will be used to successfully recognize the entire phrase if the following are true:

  • One or more words in the phrase are recognized in the audio input as a sequence of the phrase, and

  • The relative order of those recognized words is the same as in the phrase.

  • Matched words may consist of only prepositions and articles.

Adding the phrase "a car the truck a boat that plane" to a grammar using Subsequence mode produces the following result on recognition:

Input Phrase | Result
"a car the truck a boat that plane" | The entire phrase "a car the truck a boat that plane" is recognized.
"a car the truck a boat" | The entire phrase "a car the truck a boat that plane" is recognized.
"a car the that plane" | Recognition is not successful. A recognized subset is required to be a sequence of the original string.
"a car the boat a truck that plane" | Recognition is not successful. The words are out of order.
"a the" | The entire phrase "a car the truck a boat that plane" is recognized. Prepositions and articles are used for recognition.

SubsequenceContentRequired

This mode indicates that a subset of the phrase will be used to successfully recognize the entire phrase if the following are true:

  • One or more words in the match string are recognized in the audio input as a sequence of the phrase.

  • Matched words cannot consist of only prepositions and articles.

Adding the phrase "a car the truck a boat that plane" to a grammar using SubsequenceContentRequired mode produces the following result on recognition:

Input Phrase | Result
"a car the truck a boat that plane" | The entire phrase "a car the truck a boat that plane" is recognized.
"a car the truck a boat" | The entire phrase "a car the truck a boat that plane" is recognized.
"a car the that plane" | Recognition is not successful. A recognized subset is required to be a sequence of the original string.
"a car the boat a truck that plane" | Recognition is not successful. The words are out of order.
"a the" | Recognition is not successful. Speech input must contain words other than articles and prepositions.

Examples

Below is a test routine which generates four Grammar objects, using the same phrase, for each of the SubsetMatchingModes. These Grammar objects can then be tested.

Copy image Copy Code
private void CreateSubsetMatchTest()
{
  foreach ( Microsoft.Speech.Recognition.SubsetMatchingMode mode
              in Enum.GetValues(typeof(Microsoft.Speech.Recognition.SubsetMatchingMode)))
  {
    GrammarBuilder gb = new GrammarBuilder("a car the truck a boat that plane",mode);
    Grammar grammar = new Grammar(gb);
    grammar.Name = mode.ToString();
    grammar.Enabled=true;
    _recognizer.LoadGrammar(grammar);
  }
}

See Also

Reference

Microsoft.Speech.Recognition Namespace
GrammarBuilder
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Microsoft.Speech.Recognition.SrgsGrammar Namespace

[image]

Microsoft.Speech.Recognition.SrgsGrammar Namespace
See Also Send Feedback

With the members of the Microsoft.Speech.Recogntion.SRGSGrammar namespace, you can programmatically create grammars that comply with the W3C Speech Recognition Grammar Specification Version 1.0 (SRGS).

To create an SRGS grammar programmatically, you construct an empty SrgsDocument instance and add instances of classes that represent SRGS elements. The SrgsItem, SrgsOneOf, SrgsRule, SrgsRuleRef, SrgsSemanticInterpretationTag, and SrgsToken classes represent elements defined in the SRGS specification. Some of the properties of the SrgsDocument class represent attributes in the SRGS specification, such as Root, Mode, Culture, and XmlBase. See SRGS Grammar XML Reference (Microsoft.Speech) for a reference to the elements and attributes of the SRGS specification as supported by the Microsoft Speech Platform SDK 11.

To add a grammar rule to a SrgsDocument, use the Add(SrgsElement) method of the SrgsRule class. You can modify the text within an SRGS element using the Text property of a SrgsText instance.

See Create Grammars Using SrgsGrammar (Microsoft.Speech) for more information and examples.

You can also construct SrgsDocument instances from existing SRGS-compliant XML grammar files, from an instance of SrgsRule, or from an instance of GrammarBuilder.

You can use the methods of the SrgsGrammarCompiler class to compile completed SrgsDocument objects for into a binary format that can be more efficiently consumed by a speech recognition engine.

Grammars created with members of the Microsoft.Speech.Recognition.SrgsGrammar namespace can be used by constructors of the Grammar class to create Grammar objects.

Classes

 | Class | Description
Public class | MssGrammarCompiler | Represents a compiler for speech recognition grammars.
Public class | SrgsDocument | Defines a design-time object that is used to build strongly typed runtime grammars that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0.
Public class | SrgsElement | Defines the base class for classes in the Microsoft.Speech.Recognition.SrgsGrammar namespace that correspond to the elements in an SRGS grammar.
Public class | SrgsGrammarCompiler | Compiles SrgsDocument and XML-format grammar files into binary grammar files with the .cfg extension and sends the output to a stream.
Public class | SrgsItem | Represents a grammar element that contains phrases or other entities that a user can speak to produce a successful recognition.
Public class | SrgsOneOf | Represents a list of alternative words or phrases, any one of which may be used to match speech input.
Public class | SrgsRule | Represents a grammar rule.
Public class | SrgsRuleRef | Represents the grammar element that specifies a reference to a rule.
Public class | SrgsRulesCollection | Represents a collection of SrgsRule objects.
Public class | SrgsSemanticInterpretationTag | Represents a tag that contains ECMAScript that is run when the rule is matched.
Public class | SrgsText | Represents the textual content of grammar elements defined by the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0.
Public class | SrgsToken | Represents a word or short phrase that can be recognized.

Enumerations

 | Enumeration | Description
Public enumeration | SrgsGrammarMode | Indicates the type of input that the grammar, defined by the SrgsDocument, will match.
Public enumeration | SrgsPhoneticAlphabet | Enumerates the supported phonetic alphabets.
Public enumeration | SrgsRuleScope | Enumerates values for the scope of a SrgsRule object.

See Also

Reference

Microsoft.Speech.AudioFormat
Microsoft.Speech.Recognition
Microsoft.Speech.Synthesis
Microsoft.Speech.Text

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MssGrammarCompiler Class

[image]

MssGrammarCompiler Class
Members See Also Send Feedback

Represents a compiler for speech recognition grammars.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition.SrgsGrammar..::..MssGrammarCompiler

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

Syntax

Visual Basic (Declaration)
Public NotInheritable Class MssGrammarCompiler
Visual Basic (Usage)
You do not need to declare an instance of a static class in order to access its members.
C#
public static class MssGrammarCompiler

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

MssGrammarCompiler Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MssGrammarCompiler Members

[image] [image]

MssGrammarCompiler Members
MssGrammarCompiler Class Methods See Also Send Feedback

Represents a compiler for speech recognition grammars.

Methods

Name | Description
Compile(Stream, Stream, CultureInfo%, SrgsGrammarMode%, Collection<(Of <<'(Uri>)>>)%) | Compiles a speech recognition grammar.
Compile(Stream, ISpeechResourceLoader, Stream, CultureInfo%, SrgsGrammarMode%, Collection<(Of <<'(Uri>)>>)%, Uri%) | Creates a compiler for speech recognition grammars.
Top

See Also

Reference

MssGrammarCompiler Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MssGrammarCompiler Methods

[image] [image]

MssGrammarCompiler Methods
MssGrammarCompiler Class See Also Send Feedback

Methods

Name | Description
Compile(Stream, Stream, CultureInfo%, SrgsGrammarMode%, Collection<(Of <<'(Uri>)>>)%) | Compiles a speech recognition grammar.
Compile(Stream, ISpeechResourceLoader, Stream, CultureInfo%, SrgsGrammarMode%, Collection<(Of <<'(Uri>)>>)%, Uri%) | Creates a compiler for speech recognition grammars.
Top

See Also

Reference

MssGrammarCompiler Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile Method

[image] [image]

MssGrammarCompiler..::..Compile Method
MssGrammarCompiler Class See Also Send Feedback

Overload List

Name | Description
Compile(Stream, Stream, CultureInfo%, SrgsGrammarMode%, Collection<(Of <<'(Uri>)>>)%) | Compiles a speech recognition grammar.
Compile(Stream, ISpeechResourceLoader, Stream, CultureInfo%, SrgsGrammarMode%, Collection<(Of <<'(Uri>)>>)%, Uri%) | Creates a compiler for speech recognition grammars.
Top

See Also

Reference

MssGrammarCompiler Class
MssGrammarCompiler Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile Method (Stream, Stream, CultureInfo, SrgsGrammarMode, Collection(Uri))

[image]

MssGrammarCompiler..::..Compile Method (Stream, Stream, CultureInfo%, SrgsGrammarMode%, Collection<(Of <(<'Uri>)>)>%)
MssGrammarCompiler Class See Also Send Feedback

Compiles a speech recognition grammar.

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

Syntax

Visual Basic (Declaration)
Public Shared Sub Compile ( _
    inputStream As Stream, _
    outputStream As Stream, _
    <OutAttribute> ByRef culture As CultureInfo, _
    <OutAttribute> ByRef mode As SrgsGrammarMode, _
    <OutAttribute> ByRef referencedGrammars As Collection(Of Uri) _
)
Visual Basic (Usage)
Dim inputStream As Stream
Dim outputStream As Stream
Dim culture As CultureInfo
Dim mode As SrgsGrammarMode
Dim referencedGrammars As Collection(Of Uri)

MssGrammarCompiler.Compile(inputStream, outputStream, _
    culture, mode, referencedGrammars)
C#
public static void Compile(
    Stream inputStream,
    Stream outputStream,
    out CultureInfo culture,
    out SrgsGrammarMode mode,
    out Collection<Uri> referencedGrammars
)

Parameters

inputStream
Type: System.IO..::..Stream
outputStream
Type: System.IO..::..Stream
culture
Type: System.Globalization..::..CultureInfo %
mode
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsGrammarMode %
referencedGrammars
Type: System.Collections.ObjectModel..::..Collection <(Of <(<' Uri >)>)>%

See Also

Reference

MssGrammarCompiler Class
MssGrammarCompiler Members
Compile Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile Method (Stream, ISpeechResourceLoader, Stream, CultureInfo, SrgsGrammarMode, Collection(Uri), Uri)

[image]

MssGrammarCompiler..::..Compile Method (Stream, ISpeechResourceLoader, Stream, CultureInfo%, SrgsGrammarMode%, Collection<(Of <(<'Uri>)>)>%, Uri%)
MssGrammarCompiler Class See Also Send Feedback

Creates a compiler for speech recognition grammars.

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

Syntax

Visual Basic (Declaration)
Public Shared Sub Compile ( _
    inputStream As Stream, _
    resourceLoader As ISpeechResourceLoader, _
    outputStream As Stream, _
    <OutAttribute> ByRef culture As CultureInfo, _
    <OutAttribute> ByRef mode As SrgsGrammarMode, _
    <OutAttribute> ByRef referencedGrammars As Collection(Of Uri), _
    <OutAttribute> ByRef lexicon As Uri _
)
Visual Basic (Usage)
Dim inputStream As Stream
Dim resourceLoader As ISpeechResourceLoader
Dim outputStream As Stream
Dim culture As CultureInfo
Dim mode As SrgsGrammarMode
Dim referencedGrammars As Collection(Of Uri)
Dim lexicon As Uri

MssGrammarCompiler.Compile(inputStream, resourceLoader, _
    outputStream, culture, mode, referencedGrammars, _
    lexicon)
C#
public static void Compile(
    Stream inputStream,
    ISpeechResourceLoader resourceLoader,
    Stream outputStream,
    out CultureInfo culture,
    out SrgsGrammarMode mode,
    out Collection<Uri> referencedGrammars,
    out Uri lexicon
)

Parameters

inputStream
Type: System.IO..::..Stream
resourceLoader
Type: Microsoft.Speech..::..ISpeechResourceLoader
outputStream
Type: System.IO..::..Stream
culture
Type: System.Globalization..::..CultureInfo %
mode
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsGrammarMode %
referencedGrammars
Type: System.Collections.ObjectModel..::..Collection <(Of <(<' Uri >)>)>%
lexicon
Type: System..::..Uri %

See Also

Reference

MssGrammarCompiler Class
MssGrammarCompiler Members
Compile Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsDocument Class

[image]

SrgsDocument Class
Members See Also Send Feedback

Defines a design-time object that is used to build strongly typed runtime grammars that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsDocument

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class SrgsDocument
Visual Basic (Usage)
Dim instance As SrgsDocument
C#
[SerializableAttribute]
public sealed class SrgsDocument

Remarks

You can you construct an empty SrgsDocument instance and build a grammar by adding instances of classes that represent SRGS elements, such as SrgsRule, SrgsOneOf,SrgsItem, SrgsRuleRef, SrgsSemanticInterpretationTag, and SrgsToken. You can also construct an SrgsDocument instance from an existing SRGS-compliant XML grammar file, from an instance of SrgsRule, or from an instance of GrammarBuilder.

After the SrgsDocument object is created, it can be loaded into a Grammar object or compiled by SrgsGrammarCompiler, enabling it to be read by a Grammar object.

See Create Grammars Using SrgsGrammar (Microsoft.Speech) for more information and examples.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SrgsDocument Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
Grammar
SrgsGrammarCompiler
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsDocument Members

[image] [image]

SrgsDocument Members
SrgsDocument Class Constructors Methods Properties See Also Send Feedback

Defines a design-time object that is used to build strongly typed runtime grammars that conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0.

The SrgsDocument type exposes the following members.

Constructors

 | Name | Description
Public method | SrgsDocument()()()() | Initializes a new instance of the SrgsDocument class.
Public method | SrgsDocument(String) | Initializes a new instance of the SrgsDocument class specifying the location of the XML document that is used to fill in the SrgsDocument instance.
Public method | SrgsDocument(XmlReader) | Initializes a new instance of the SrgsDocument class from an instance of XmlReader that references an XML-format grammar file.
Public method | SrgsDocument(GrammarBuilder) | Initializes a new instance of the SrgsDocument class from a GrammarBuilder object.
Public method | SrgsDocument(SrgsRule) | Initializes a new instance of the SrgsDocument class and specifies an SrgsRule object to be the root rule of the grammar.
Top

Properties

 | Name | Description
Public property | Culture | Gets or sets the culture information for the SrgsDocument instance.
Public property | Mode | Gets or sets the mode for the SrgsDocument class.
Public property | PhoneticAlphabet | Gets or sets the phonetic alphabet of the SrgsDocument class.
Public property | Root | Gets or sets the root rule of the SrgsDocument class.
Public property | Rules | Gets the collection of rules that are currently defined for the SrgsDocument class.
Public property | XmlBase | Gets or sets the base URI of the SrgsDocument class.
Top

Methods

 | Name | Description
Public method | AddLexicon | Adds a link to the specified lexicon.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Public method | WriteSrgs | Writes the contents of the SrgsDocument object to an XML-format grammar file that conforms to the Speech Recognition Grammar Specification (SRGS) Version 1.0.
Top

See Also

Reference

SrgsDocument Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsDocument Constructor

[image] [image]

SrgsDocument Constructor
SrgsDocument Class See Also Send Feedback

Initializes a new instance of the SrgsDocument class.

Overload List

 | Name | Description
Public method | SrgsDocument()()()() | Initializes a new instance of the SrgsDocument class.
Public method | SrgsDocument(String) | Initializes a new instance of the SrgsDocument class specifying the location of the XML document that is used to fill in the SrgsDocument instance.
Public method | SrgsDocument(XmlReader) | Initializes a new instance of the SrgsDocument class from an instance of XmlReader that references an XML-format grammar file.
Public method | SrgsDocument(GrammarBuilder) | Initializes a new instance of the SrgsDocument class from a GrammarBuilder object.
Public method | SrgsDocument(SrgsRule) | Initializes a new instance of the SrgsDocument class and specifies an SrgsRule object to be the root rule of the grammar.
Top

Remarks

Using the constructors for the SrgsDocument class, you can create an instance of SrgsDocument from a GrammarBuilder, SrgsRule, or XmlReader object, from a string that contains the path to an XML-format grammar, or you can initiate a blank instance of SrgsDocument.

See Also

Reference

SrgsDocument Class
SrgsDocument Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsDocument Constructor

[image]

SrgsDocument Constructor
SrgsDocument Class Example See Also Send Feedback

Initializes a new instance of the SrgsDocument class.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New SrgsDocument()
C#
public SrgsDocument()

Remarks

This constructor creates an empty SrgsDocument instance. To build a grammar within an empty SrgsDocument instance, add instances of classes that represent SRGS elements, such as SrgsRule, SrgsRuleRef, SrgsOneOf, and SrgsItem.

Examples

The following example creates an SrgsDocument object and then creates a public rule named rootRule. It then creates an SrgsItem that consists of the string "A nation that has won the world cup is:", and adds this item to the Elements property of the rule. The example then creates two more rules (ruleEurope and ruleSAmerica), each of which is an SrgsOneOf object that contains three SrgsItem objects. After that, another SrgsOneOf object is created that contains SrgsRuleRef objects that refer to ruleEurope and ruleSAmerica. The new SrgsOneOf object is then added to the Elements property of rootRule. After this, all three rules (rootRule, ruleEurope, and ruleSAmerica) are added to the Rules property of SrgsDocument. Finally, the three rules are compiled into a binary representation of the grammar.

C# Copy image Copy Code
SrgsDocument document = new SrgsDocument();

SrgsRule rootRule = new SrgsRule("WorldCupWinner");
rootRule.Scope = SrgsRuleScope.Public;

rootRule.Elements.Add(new SrgsItem("A nation that has won the world cup is: "));
SrgsOneOf oneOfEurope = new SrgsOneOf(new SrgsItem("England"), new SrgsItem("France"), new SrgsItem("Germany"), new SrgsItem("Italy"));
SrgsRule ruleEurope = new SrgsRule("EuropeanNations", oneOfEurope);

SrgsOneOf oneOfSAmerica = new SrgsOneOf(new SrgsItem("Argentina"), new SrgsItem("Brazil"), new SrgsItem("Uruguay"));
SrgsRule ruleSAmerica = new SrgsRule("SouthAmericanNations", oneOfSAmerica);

rootRule.Elements.Add(new SrgsOneOf(new SrgsItem(new SrgsRuleRef(ruleEurope)), new SrgsItem(new SrgsRuleRef(ruleSAmerica))));

document.Rules.Add(rootRule, ruleEurope, ruleSAmerica);
document.Root = rootRule;

String fileName = Path.GetTempFileName();
FileStream stream = new FileStream(fileName, FileMode.Create);

SrgsGrammarCompiler.Compile(document, stream);
stream.Close();
lil

See Also

Reference

SrgsDocument Class
SrgsDocument Members
SrgsDocument Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsDocument Constructor (String)

[image]

SrgsDocument Constructor (String)
SrgsDocument Class Example See Also Send Feedback

Initializes a new instance of the SrgsDocument class specifying the location of the XML document that is used to fill in the SrgsDocument instance.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    path As String _
)
Visual Basic (Usage)
Dim path As String

Dim instance As New SrgsDocument(path)
C#
public SrgsDocument(
    string path
)

Parameters

path
Type: System..::..String

The location of the SRGS XML file.

Exceptions

Exception | Condition
ArgumentNullException | path is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentException | path is an empty string.

Examples

The following example creates a new SrgsDocument from the file named "srgsDocumentFile.xml".

C# Copy image Copy Code
string srgsDocumentFile = Path.Combine(Path.GetTempPath(), "srgsDocumentFile.xml");
SrgsDocument document = null;

if (File.Exists(srgsDocumentFile))
   document = new SrgsDocument(srgsDocumentFile);

See Also

Reference

SrgsDocument Class
SrgsDocument Members
SrgsDocument Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsDocument Constructor (XmlReader)

[image]

SrgsDocument Constructor (XmlReader)
SrgsDocument Class Example See Also Send Feedback

Initializes a new instance of the SrgsDocument class from an instance of XmlReader that references an XML-format grammar file.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    srgsGrammar As XmlReader _
)
Visual Basic (Usage)
Dim srgsGrammar As XmlReader

Dim instance As New SrgsDocument(srgsGrammar)
C#
public SrgsDocument(
    XmlReader srgsGrammar
)

Parameters

srgsGrammar
Type: System.Xml..::..XmlReader

The XmlReader that was created with the SrgsDocument XML instance.

Exceptions

Exception | Condition
ArgumentNullException | srgsGrammar is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Examples

The following example creates a new instance of SrgsDocument from an instance of XmlReader that references the file "srgsDocumentFile.xml".

C# Copy image Copy Code
string srgsDocumentFile = Path.Combine(Path.GetTempPath(), "srgsDocumentFile.xml");
SrgsDocument document = null;

if (File.Exists(srgsDocumentFile))
{
  XmlReader reader = XmlReader.Create(srgsDocumentFile);
  document = new SrgsDocument(reader);
  reader.Close();
}

See Also

Reference

SrgsDocument Class
SrgsDocument Members
SrgsDocument Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsDocument Constructor (GrammarBuilder)

[image]

SrgsDocument Constructor (GrammarBuilder)
SrgsDocument Class Example See Also Send Feedback

Initializes a new instance of the SrgsDocument class from a GrammarBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    builder As GrammarBuilder _
)
Visual Basic (Usage)
Dim builder As GrammarBuilder

Dim instance As New SrgsDocument(builder)
C#
public SrgsDocument(
    GrammarBuilder builder
)

Parameters

builder
Type: Microsoft.Speech.Recognition..::..GrammarBuilder

The GrammarBuilder object used to create the SrgsDocument instance.

Exceptions

Exception | Condition
ArgumentNullException | The value of builder is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Examples

The following example builds a grammar in a GrammarBuilder instance using Choices objects. It then creates an SrgsDocument from the GrammarBuilder object.

C# Copy image Copy Code
GrammarBuilder builder = null;

// Create new Choices objects and add countries, and create GrammarBuilder objects.
Choices choicesEurope = new Choices(new string[] { "England", "France", "Germany", "Italy" });
GrammarBuilder europe = new GrammarBuilder(choicesEurope);

Choices choicesSAmerica = new Choices(new string[] { "Argentina", "Brazil", "Uruguay" });
GrammarBuilder sAmerica = new GrammarBuilder(choicesSAmerica);

Choices worldCupWinnerChoices = new Choices(new GrammarBuilder[] {choicesEurope, choicesSAmerica});

// Create new GrammarBuilder from a Choices object.
builder = new GrammarBuilder(worldCupWinnerChoices);

// Create an SrgsDocument object from a GrammarBuilder object.
SrgsDocument document = new SrgsDocument(builder);

See Also

Reference

SrgsDocument Class
SrgsDocument Members
SrgsDocument Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsDocument Constructor (SrgsRule)

[image]

SrgsDocument Constructor (SrgsRule)
SrgsDocument Class Example See Also Send Feedback

Initializes a new instance of the SrgsDocument class and specifies an SrgsRule object to be the root rule of the grammar.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    grammarRootRule As SrgsRule _
)
Visual Basic (Usage)
Dim grammarRootRule As SrgsRule

Dim instance As New SrgsDocument(grammarRootRule)
C#
public SrgsDocument(
    SrgsRule grammarRootRule
)

Parameters

grammarRootRule
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsRule

The root rule in the SrgsDocument object.

Exceptions

Exception | Condition
SystemArgumentNullException | The value of grammarRootRule is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Remarks

This constructor adds the specified rule to the SrgsRulesCollection of the SrgsDocument object and sets it as the Root rule for the grammar.

Examples

The following example creates two rules (chooseCities and destCities) for choosing origin and destination cities for a flight. The example initializes the SrgsDocument instance using the chooseCities rule as an argument. The example writes the contents of the rules collection and the name of the root rule to the console.

C# Copy image Copy Code
// Create a rule that contains a list of destination cities.
SrgsRule destCities = new SrgsRule("Destination");
SrgsOneOf toCities = new SrgsOneOf(new string[] { "New York", "Seattle", "Denver" });
destCities.Add(toCities);

// Create a list of origin cities and supporting phrases.
SrgsOneOf fromCities = new SrgsOneOf(new SrgsItem[] {
  new SrgsItem("Dallas"), new SrgsItem("Miami"), new SrgsItem("Chicago") });
SrgsItem intro = new SrgsItem("I want to fly from");
SrgsItem to = new SrgsItem("to");

// Create the root rule of the grammar, and assemble the components.
SrgsRule chooseCities = new SrgsRule("Trip");
chooseCities.Add(intro);
chooseCities.Add(fromCities);
chooseCities.Add(to);
chooseCities.Add(new SrgsRuleRef(destCities));

// Create the SrgsDocument and specify the root rule to add.
SrgsDocument bookFlight = new SrgsDocument(chooseCities);

// Add the rule for the destination cities to the document's rule collection.
bookFlight.Rules.Add(new SrgsRule[] { destCities });

// Display the contents of the Rules collection and the name of the root rule.
foreach (SrgsRule rule in bookFlight.Rules)
{
  Console.WriteLine("Rule " + rule.Id + " is in the rules collection");
}
Console.WriteLine("Root Rule " + bookFlight.Root.Id);

// Create a Grammar object and load it to the recognizer.
Grammar g = new Grammar(bookFlight);
g.Name = ("City Chooser");
recognizer.LoadGrammarAsync(g);

See Also

Reference

SrgsDocument Class
SrgsDocument Members
SrgsDocument Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsDocument Methods

[image] [image]

SrgsDocument Methods
SrgsDocument Class See Also Send Feedback

The SrgsDocument type exposes the following members.

Methods

 | Name | Description
Public method | AddLexicon | Adds a link to the specified lexicon.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Public method | WriteSrgs | Writes the contents of the SrgsDocument object to an XML-format grammar file that conforms to the Speech Recognition Grammar Specification (SRGS) Version 1.0.
Top

See Also

Reference

SrgsDocument Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AddLexicon Method

[image]

SrgsDocument..::..AddLexicon Method
SrgsDocument Class See Also Send Feedback

Adds a link to the specified lexicon.

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

Syntax

Visual Basic (Declaration)
Public Sub AddLexicon ( _
    lexiconUri As Uri _
)
Visual Basic (Usage)
Dim instance As SrgsDocument
Dim lexiconUri As Uri

instance.AddLexicon(lexiconUri)
C#
public void AddLexicon(
    Uri lexiconUri
)

Parameters

lexiconUri
Type: System..::..Uri

The lexicon to add.

Remarks

A pronunciation lexicon is a collection of words or phrases together with their pronunciations, which consist of letters and characters from a supported phonetic alphabet. You can reference only one lexicon from an SrgsDocument grammar.

Pronunciations specified in an external lexicon file take precedence over the pronunciations of the speech recognition engine's internal lexicon or dictionary. However, pronunciations specified inline using the Pronunciation property of the SrgsToken object take precedence over pronunciations specified in any lexicon. Inline pronunciations apply only to a single occurrence of a word. By contrast, pronunciations specified in a lexicon apply to all occurrences of a word in a grammar.

See Also

Reference

SrgsDocument Class
SrgsDocument Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


WriteSrgs Method

[image]

SrgsDocument..::..WriteSrgs Method
SrgsDocument Class Example See Also Send Feedback

Writes the contents of the SrgsDocument object to an XML-format grammar file that conforms to the Speech Recognition Grammar Specification (SRGS) Version 1.0.

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

Syntax

Visual Basic (Declaration)
Public Sub WriteSrgs ( _
    srgsGrammar As XmlWriter _
)
Visual Basic (Usage)
Dim instance As SrgsDocument
Dim srgsGrammar As XmlWriter

instance.WriteSrgs(srgsGrammar)
C#
public void WriteSrgs(
    XmlWriter srgsGrammar
)

Parameters

srgsGrammar
Type: System.Xml..::..XmlWriter

The XmlWriter that is used to write the SrgsDocument instance.

Exceptions

Exception | Condition
ArgumentNullException | srgsGrammar is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Examples

The following example creates an SrgsDocument object, and then creates a public rule named winnerRule. It then creates an SrgsItem that consists of the string "A nation that has won the world cup is:", and adds this item to the Elements property of the rule. The example then creates two more rules (ruleEurope and ruleSAmerica), each of which is an SrgsOneOf object that contains three SrgsItem objects. After that, another SrgsOneOf object is created that contains SrgsRuleRef objects that refer to ruleEurope and ruleSAmerica. The new SrgsOneOf object is then added to the Elements property of winnerRule. After this, all three rules (winnerRule, ruleEurope, and ruleSAmerica) are added to the Rules property of the SrgsDocument. Finally, the example creates an empty XML file and an instance of XmlWriter. The WriteSrgs method uses the XmlWriter instance to write the contents of the SrgsDocument to the XML file.

C# Copy image Copy Code
public void WorldSoccerWinners ()
{

  // Create an SrgsDocument, create a new rule
  // and set its scope to public.
  SrgsDocument document = new SrgsDocument();
  SrgsRule winnerRule = new SrgsRule("WorldCupWinner");
  winnerRule.Scope = SrgsRuleScope.Public;

  // Add the introduction.
  winnerRule.Elements.Add(new SrgsItem("A nation that has won the world cup is: "));

  // Create the rule for the European nations.
  SrgsOneOf oneOfEurope = new SrgsOneOf(new SrgsItem[] {new SrgsItem("England"),
    new SrgsItem("France"), new SrgsItem("Germany"), new SrgsItem("Italy")});
  SrgsRule ruleEurope = (new SrgsRule("EuropeanNations", new SrgsElement[] {oneOfEurope}));

  // Create the rule for the South American nations.
  SrgsOneOf oneOfSAmerica = new SrgsOneOf(new SrgsItem[] {new SrgsItem("Argentina"),
    new SrgsItem("Brazil"), new SrgsItem("Uruguay")});
  SrgsRule ruleSAmerica = (new SrgsRule("SouthAmericanNations", new SrgsElement[] {oneOfSAmerica}));

  // Add references to winnerRule for ruleEurope and ruleSAmerica.
  winnerRule.Elements.Add(new SrgsOneOf(new SrgsItem[] {(new SrgsItem
    (new SrgsRuleRef(ruleEurope))), new SrgsItem(new SrgsRuleRef(ruleSAmerica))}));

  // Add all the rules to the document and make winnerRule
  // the root rule of the document.
  document.Rules.Add(new SrgsRule[] {winnerRule, ruleEurope, ruleSAmerica});
  document.Root = winnerRule;

  // Create a string object with the path to the file to use.
  string srgsDocumentFile = Path.Combine(Path.GetTempPath(), "srgsDocumentFile.xml");

  // Create an XmlWriter object and pass the file path.
  XmlWriter writer = XmlWriter.Create(srgsDocumentFile);

  // Write the contents of the XmlWriter object to an SRGS-compatible XML file.
  document.WriteSrgs(writer);
  writer.Close();
}

See Also

Reference

SrgsDocument Class
SrgsDocument Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsDocument Properties

[image] [image]

SrgsDocument Properties
SrgsDocument Class See Also Send Feedback

The SrgsDocument type exposes the following members.

Properties

 | Name | Description
Public property | Culture | Gets or sets the culture information for the SrgsDocument instance.
Public property | Mode | Gets or sets the mode for the SrgsDocument class.
Public property | PhoneticAlphabet | Gets or sets the phonetic alphabet of the SrgsDocument class.
Public property | Root | Gets or sets the root rule of the SrgsDocument class.
Public property | Rules | Gets the collection of rules that are currently defined for the SrgsDocument class.
Public property | XmlBase | Gets or sets the base URI of the SrgsDocument class.
Top

See Also

Reference

SrgsDocument Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Culture Property

[image]

SrgsDocument..::..Culture Property
SrgsDocument Class See Also Send Feedback

Gets or sets the culture information for the SrgsDocument instance.

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

Syntax

Visual Basic (Declaration)
Public Property Culture As CultureInfo
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsDocument
Dim value As CultureInfo

value = instance.Culture

instance.Culture = value
C#
public CultureInfo Culture { get; set; }

Property Value

Type: System.Globalization..::..CultureInfo

Returns the current culture information for the SrgsDocument.

Exceptions

Exception | Condition
ArgumentNullException | The value being assigned to Culture is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentException | The value being assigned to Culture is InvariantCulture.

Remarks

The Culture property sets the single culture for the grammar defined in the SrgsDocument object.

The Microsoft Speech Platform SDK 11 accepts all valid language-country codes as values for Culture. For a given language code specified in the Culture property, a speech recognition engine that supports that language code must be installed for the grammar to be loaded successfully.

If the Culture property specifies only a language code, (such as "en" for English or "es" for Spanish), and not a country/region code, then any installed recognizer that expresses support for that generic, region-independent language will be able to load the grammar. See Language Identifier Constants and Strings for a comprehensive list of language codes.

The Microsoft Speech Platform Runtime 11 and Speech Platform SDK 11 do not include any engines for speech recognition in a specific language. You must download a language pack (an engine for speech recognition in a specific language) for each language on which you want to perform speech recognition.

The language packs are different for each version of the Speech Platform Runtime. You must download the language pack version that matches the version of the Speech Platform Runtime that you have installed. The language packs for the Speech Platform SDK 11 are for server-based applications and are different than the languages that ship with Windows Vista or Windows 7. Use the following links to download the version of the server language packs that match your Speech Platform Runtime version:

  • Server Language Packs v11.0

  • Server Language Packs v10.2

  • Server Language Packs v10.1

  • Server Language Packs v10.0

See Language Support for a list of languages for which you can download language packs.

See Also

Reference

SrgsDocument Class
SrgsDocument Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Mode Property

[image]

SrgsDocument..::..Mode Property
SrgsDocument Class See Also Send Feedback

Gets or sets the mode for the SrgsDocument class.

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

Syntax

Visual Basic (Declaration)
Public Property Mode As SrgsGrammarMode
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsDocument
Dim value As SrgsGrammarMode

value = instance.Mode

instance.Mode = value
C#
public SrgsGrammarMode Mode { get; set; }

Property Value

Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsGrammarMode

The recognition mode of the SrgsDocument.

Remarks

The Mode property returns a member of the SrgsGrammarMode that determines the type of input that the SrgsDocument expects. The two possible values are Voice for speech input, and Dtmf for input of dual-tone multi-frequency (DTMF) tones that are commonly associated with a telephone.

See Also

Reference

SrgsDocument Class
SrgsDocument Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
SrgsGrammarMode
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PhoneticAlphabet Property

[image]

SrgsDocument..::..PhoneticAlphabet Property
SrgsDocument Class See Also Send Feedback

Gets or sets the phonetic alphabet of the SrgsDocument class.

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

Syntax

Visual Basic (Declaration)
Public Property PhoneticAlphabet As SrgsPhoneticAlphabet
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsDocument
Dim value As SrgsPhoneticAlphabet

value = instance.PhoneticAlphabet

instance.PhoneticAlphabet = value
C#
public SrgsPhoneticAlphabet PhoneticAlphabet { get; set; }

Property Value

Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsPhoneticAlphabet

Returns the phonetic alphabet that must be used to specify custom pronunciations in the SrgsToken object.

Remarks

Phonetic alphabets are composed of phones, which consist of letters, numbers or characters, sometimes in combination. Each phone describes a unique sound of speech. This is in contrast to the Latin alphabet, for which any letter may represent multiple spoken sounds. Consider the different pronunciations of the letter "c" in the words "candy" and "cease", or the different pronunciations of the letter combination "th" in the words "thing" and "those".

In the Microsoft Speech Platform SDK 11, you can use any of three phonetic alphabets to specify custom pronunciations: International Phone Alphabet (IPA), Universal Phone Set (UPS), or the SAPI phone set. The specified phonetic alphabet determines which phone set will be used to define inline pronunciations for SrgsToken objects. The phones specified in Pronunciation must match the phonetic alphabet specified in PhoneticAlphabet.

See Lexicons and Phonetic Alphabets (Microsoft.Speech) for more information.

See Also

Reference

SrgsDocument Class
SrgsDocument Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Root Property

[image]

SrgsDocument..::..Root Property
SrgsDocument Class Example See Also Send Feedback

Gets or sets the root rule of the SrgsDocument class.

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

Syntax

Visual Basic (Declaration)
Public Property Root As SrgsRule
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsDocument
Dim value As SrgsRule

value = instance.Root

instance.Root = value
C#
public SrgsRule Root { get; set; }

Property Value

Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsRule

Returns the rule that is designated as the root rule of the SrgsDocument.

Remarks

The SrgsRule object must already be in the document's SrgsRulesCollection before it can be set to the root rule.

You can also set the root rule for an SrgsDocument object by using an SrgsRule object as the argument to the SrgsDocument constructor.

Examples

The following example creates a rule named rootRule, and then creates an SrgsDocument object named document. The example then calls the Add method to add the rule to the document. Finally, the example sets the document's Root property to rootRule, thereby making it the root rule.

C# Copy image Copy Code
SrgsRule rootRule = new SrgsRule("WorldCupWinner");
rootRule.Scope = SrgsRuleScope.Public;

SrgsDocument document = new SrgsDocument();

document.Rules.Add(rootRule);
document.Root = rootRule;

See Also

Reference

SrgsDocument Class
SrgsDocument Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
SrgsRule
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Rules Property

[image]

SrgsDocument..::..Rules Property
SrgsDocument Class Example See Also Send Feedback

Gets the collection of rules that are currently defined for the SrgsDocument class.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Rules As SrgsRulesCollection
    Get
Visual Basic (Usage)
Dim instance As SrgsDocument
Dim value As SrgsRulesCollection

value = instance.Rules
C#
public SrgsRulesCollection Rules { get; }

Property Value

Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsRulesCollection

Returns the rules defined for the SrgsDocument object.

Remarks

You can add SrgsRule objects to the SrgsRulesCollection by using the Add method on the Rules property. If you initialize an SrgsDocument object and specify an SrgsRule object as the argument, the SrgsRule is automatically added to the SrgsRulesCollection for the SrgsDocument.

Examples

The following example creates an SrgsDocument object, and then creates a public rule named rootRule. It then creates an SrgsItem that consists of the string "A nation that has won the world cup is:", and adds this item to the Elements property of the rule. The example then creates two more rules (ruleEurope and ruleSAmerica), each of which is an SrgsOneOf object that contains three SrgsItem objects. After that, another SrgsOneOf object is created that contains SrgsRuleRef objects that refer to ruleEurope and ruleSAmerica. The new SrgsOneOf object is then added to the Elements property of rootRule. After this, all three rules (rootRule, ruleEurope, and ruleSAmerica) are added to the Rules property of SrgsDocument. Finally, rootRule is made the root rule for the grammar of SrgsDocument.

C# Copy image Copy Code
SrgsDocument document = new SrgsDocument();

SrgsRule rootRule = new SrgsRule("WorldCupWinner");
rootRule.Scope = SrgsRuleScope.Public;

rootRule.Elements.Add(new SrgsItem("A nation that has won the world cup is: "));
SrgsOneOf oneOfEurope = new SrgsOneOf(new SrgsItem("England"), new SrgsItem("France"), new SrgsItem("Germany"), new SrgsItem("Italy"));
SrgsRule ruleEurope = new SrgsRule("EuropeanNations", oneOfEurope);

SrgsOneOf oneOfSAmerica = new SrgsOneOf(new SrgsItem("Argentine"), new SrgsItem("Brazil"), new SrgsItem("Uruguay"));
SrgsRule ruleSAmerica = new SrgsRule("SouthAmericanNations", oneOfSAmerica);

rootRule.Elements.Add(new SrgsOneOf(new SrgsItem(new SrgsRuleRef(ruleEurope)), new SrgsItem(new SrgsRuleRef(ruleSAmerica))));

document.Rules.Add(rootRule, ruleEurope, ruleSAmerica);
document.Root = rootRule;

See Also

Reference

SrgsDocument Class
SrgsDocument Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
SrgsRulesCollection
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


XmlBase Property

[image]

SrgsDocument..::..XmlBase Property
SrgsDocument Class See Also Send Feedback

Gets or sets the base URI of the SrgsDocument class.

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

Syntax

Visual Basic (Declaration)
Public Property XmlBase As Uri
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsDocument
Dim value As Uri

value = instance.XmlBase

instance.XmlBase = value
C#
public Uri XmlBase { get; set; }

Property Value

Type: System..::..Uri

The current base URI of SrgsDocument.

Remarks

XmlBase property gets a value that is used to resolve relative URIs in a SrgsDocument object. Suppose the value for XmlBase is "http://www.contoso.com/" and the SrgsDocument contains a relative rule reference to another document, for example SrgsRuleRef("ExternalGrammar.grxml"). This creates the following absolute path to the external document: http://www.contoso.com/ExternalGrammar.grxml.

See Also

Reference

SrgsDocument Class
SrgsDocument Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsElement Class

[image]

SrgsElement Class
Members See Also Send Feedback

Defines the base class for classes in the Microsoft.Speech.Recognition.SrgsGrammar namespace that correspond to the elements in an SRGS grammar.

Inheritance Hierarchy

System..::..Object
System..::..MarshalByRefObject
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsElement
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsItem
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsOneOf
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsRuleRef
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsSemanticInterpretationTag
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsText
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsToken

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public MustInherit Class SrgsElement _
    Inherits MarshalByRefObject
Visual Basic (Usage)
Dim instance As SrgsElement
C#
[SerializableAttribute]
public abstract class SrgsElement : MarshalByRefObject

Remarks

The SrgsElement class is the base class for the following classes, which correspond to elements defined in the Microsoft Recognition Grammar Specification (SRGS) Version 1.0:

  • SrgsItem

  • SrgsOneOf

  • SrgsRuleRef

  • SrgsSemanticInterpretationTag

  • SrgsToken

An additional class inherits from SrgsElement and represents the text contained within the classes listed above:

  • SrgsText

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SrgsElement Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsElement Members

[image] [image]

SrgsElement Members
SrgsElement Class Constructors Methods See Also Send Feedback

Defines the base class for classes in the Microsoft.Speech.Recognition.SrgsGrammar namespace that correspond to the elements in an SRGS grammar.

The SrgsElement type exposes the following members.

Constructors

 | Name | Description
Protected method | SrgsElement | Infrastructure. Initializes a new instance of the SrgsElement class.
Top

Methods

 | Name | Description
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsElement Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsElement Constructor

[image]

SrgsElement Constructor
SrgsElement Class See Also Send Feedback

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

Initializes a new instance of the SrgsElement class.

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

Syntax

Visual Basic (Declaration)
Protected Sub New
Visual Basic (Usage)
Dim instance As New SrgsElement()
C#
protected SrgsElement()

See Also

Reference

SrgsElement Class
SrgsElement Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsElement Methods

[image] [image]

SrgsElement Methods
SrgsElement Class See Also Send Feedback

The SrgsElement type exposes the following members.

Methods

 | Name | Description
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsElement Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MemberwiseClone Method

[image] [image]

SrgsElement..::..MemberwiseClone Method
SrgsElement Class See Also Send Feedback

Overload List

 | Name | Description
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Top

See Also

Reference

SrgsElement Class
SrgsElement Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsGrammarCompiler Class

[image]

SrgsGrammarCompiler Class
Members See Also Send Feedback

Compiles SrgsDocument and XML-format grammar files into binary grammar files with the .cfg extension and sends the output to a stream.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsGrammarCompiler

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

Syntax

Visual Basic (Declaration)
Public NotInheritable Class SrgsGrammarCompiler
Visual Basic (Usage)
You do not need to declare an instance of a static class in order to access its members.
C#
public static class SrgsGrammarCompiler

Remarks

You compile SrgsDocument objects and XML-format grammars to a binary format to optimize them for loading and consumption by a speech recognition engine. Compiling a speech recognition grammar using one of the Compile methods can reduce the amount of time required to construct a Grammar object from an SrgsDocument or an XML-format grammar.

For more information, see Compile SRGS Grammars (Microsoft.Speech).

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SrgsGrammarCompiler Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsGrammarCompiler Members

[image] [image]

SrgsGrammarCompiler Members
SrgsGrammarCompiler Class Methods See Also Send Feedback

Compiles SrgsDocument and XML-format grammar files into binary grammar files with the .cfg extension and sends the output to a stream.

Methods

Name | Description
Compile(String, Stream) | Compiles an XML-format grammar file into a binary grammar file with the .cfg extension and sends the output to a stream.
Compile(XmlReader, Stream) | Compiles data for an XML-format grammar file referenced by an XmlReader into a binary grammar file with the .cfg extension and sends the output to a stream.
Compile(SrgsDocument, Stream) | Compiles an SrgsDocument into a binary grammar file with the .cfg extension and sends the output to a stream.
Top

See Also

Reference

SrgsGrammarCompiler Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsGrammarCompiler Methods

[image] [image]

SrgsGrammarCompiler Methods
SrgsGrammarCompiler Class See Also Send Feedback

Methods

Name | Description
Compile(String, Stream) | Compiles an XML-format grammar file into a binary grammar file with the .cfg extension and sends the output to a stream.
Compile(XmlReader, Stream) | Compiles data for an XML-format grammar file referenced by an XmlReader into a binary grammar file with the .cfg extension and sends the output to a stream.
Compile(SrgsDocument, Stream) | Compiles an SrgsDocument into a binary grammar file with the .cfg extension and sends the output to a stream.
Top

See Also

Reference

SrgsGrammarCompiler Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile Method

[image] [image]

SrgsGrammarCompiler..::..Compile Method
SrgsGrammarCompiler Class See Also Send Feedback

Compiles SRGSDocument and XML-format grammar files into binary grammar files with the .cfg extension and sends the output to a stream.

Overload List

Name | Description
Compile(String, Stream) | Compiles an XML-format grammar file into a binary grammar file with the .cfg extension and sends the output to a stream.
Compile(XmlReader, Stream) | Compiles data for an XML-format grammar file referenced by an XmlReader into a binary grammar file with the .cfg extension and sends the output to a stream.
Compile(SrgsDocument, Stream) | Compiles an SrgsDocument into a binary grammar file with the .cfg extension and sends the output to a stream.
Top

See Also

Reference

SrgsGrammarCompiler Class
SrgsGrammarCompiler Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile Method (String, Stream)

[image]

SrgsGrammarCompiler..::..Compile Method (String, Stream)
SrgsGrammarCompiler Class See Also Send Feedback

Compiles an XML-format grammar file into a binary grammar file with the .cfg extension and sends the output to a stream.

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

Syntax

Visual Basic (Declaration)
Public Shared Sub Compile ( _
    inputPath As String, _
    outputStream As Stream _
)
Visual Basic (Usage)
Dim inputPath As String
Dim outputStream As Stream

SrgsGrammarCompiler.Compile(inputPath, outputStream)
C#
public static void Compile(
    string inputPath,
    Stream outputStream
)

Parameters

inputPath
Type: System..::..String

The path of the file to compile.

outputStream
Type: System.IO..::..Stream

The stream that receives the results of compilation.

Exceptions

Exception | Condition
ArgumentNullException | inputPath is nullNothingnullptrunita null reference (Nothing in Visual Basic). outputStream is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentException | inputPath is an empty string.

Remarks

The XML-format grammar file must conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0.

When accessing files, a security check is performed when the file is created or opened. The security check is typically not done again unless the file is closed and reopened.

For more information, see Compile SRGS Grammars (Microsoft.Speech).

See Also

Reference

SrgsGrammarCompiler Class
SrgsGrammarCompiler Members
Compile Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile Method (XmlReader, Stream)

[image]

SrgsGrammarCompiler..::..Compile Method (XmlReader, Stream)
SrgsGrammarCompiler Class See Also Send Feedback

Compiles data for an XML-format grammar file referenced by an XmlReader into a binary grammar file with the .cfg extension and sends the output to a stream.

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

Syntax

Visual Basic (Declaration)
Public Shared Sub Compile ( _
    reader As XmlReader, _
    outputStream As Stream _
)
Visual Basic (Usage)
Dim reader As XmlReader
Dim outputStream As Stream

SrgsGrammarCompiler.Compile(reader, outputStream)
C#
public static void Compile(
    XmlReader reader,
    Stream outputStream
)

Parameters

reader
Type: System.Xml..::..XmlReader

The XmlReader that reads data from the grammar. The grammar can reside in a physical file or in memory.

outputStream
Type: System.IO..::..Stream

The stream that will receive the results of compilation.

Exceptions

Exception | Condition
ArgumentNullException | reader is nullNothingnullptrunita null reference (Nothing in Visual Basic). outputStream is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Remarks

The XML-format grammar file referenced by the XmlReader must conform to the Speech Recognition Grammar Specification (SRGS) Version 1.0.

For more information, see Compile SRGS Grammars (Microsoft.Speech).

See Also

Reference

SrgsGrammarCompiler Class
SrgsGrammarCompiler Members
Compile Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Compile Method (SrgsDocument, Stream)

[image]

SrgsGrammarCompiler..::..Compile Method (SrgsDocument, Stream)
SrgsGrammarCompiler Class See Also Send Feedback

Compiles an SrgsDocument into a binary grammar file with the .cfg extension and sends the output to a stream.

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

Syntax

Visual Basic (Declaration)
Public Shared Sub Compile ( _
    srgsGrammar As SrgsDocument, _
    outputStream As Stream _
)
Visual Basic (Usage)
Dim srgsGrammar As SrgsDocument
Dim outputStream As Stream

SrgsGrammarCompiler.Compile(srgsGrammar, outputStream)
C#
public static void Compile(
    SrgsDocument srgsGrammar,
    Stream outputStream
)

Parameters

srgsGrammar
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsDocument

The grammar to compile.

outputStream
Type: System.IO..::..Stream

The stream that receives the results of compilation.

Exceptions

Exception | Condition
ArgumentNullException | srgsGrammar is nullNothingnullptrunita null reference (Nothing in Visual Basic). outputStream is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Remarks

For more information, see Compile SRGS Grammars (Microsoft.Speech).

See Also

Reference

SrgsGrammarCompiler Class
SrgsGrammarCompiler Members
Compile Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsGrammarMode Enumeration

[image]

SrgsGrammarMode Enumeration
Example See Also Send Feedback

Indicates the type of input that the grammar, defined by the SrgsDocument, will match.

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

Syntax

Visual Basic (Declaration)
Public Enumeration SrgsGrammarMode
Visual Basic (Usage)
Dim instance As SrgsGrammarMode
C#
public enum SrgsGrammarMode

Members

Member name | Description
Voice | The SrgsDocument object will match speech input.
Dtmf | The SrgsDocument object will match DTMF tones similar to those found on a telephone, instead of speech.

Remarks

The input mode for an SrgsDocument is determined by its Mode property. The default input mode is Voice, which indicates that the grammar defined by the SrgsDocument will match speech input.

The Dtmf mode indicates that a grammar will match Dual-Tone Multi-Frequency (DTMF) tones instead of speech. There are 16 DTMF tones, 12 of which are commonly found on most telephones.

When you create a Grammar object from an SrgsDocument, the Grammar object will match the type of input specified by the Mode property, which gets an instance of SrgsGrammarMode.

Examples

C# Copy image Copy Code
string srgsDocumentFile = Path.Combine(Path.GetTempPath(), "srgsDocumentFile.xml");
SrgsDocument document = null;
GrammarBuilder builder = null;
Grammar grammar = null;

Choices firstThree = new Choices(new string[] {"1", "2", "3"});
Choices nextThree = new Choices(new string[] {"4", "5", "6"});
Choices lastThree = new Choices(new string[] {"7", "8", "9"});

Choices keyPadChoices = new Choices(new GrammarBuilder[] {firstThree, nextThree, lastThree, new Choices("0")});

builder = new GrammarBuilder(keyPadChoices);
document = new SrgsDocument(builder);

document.Mode = SrgsGrammarMode.Dtmf;
grammar = new Grammar(document);

See Also

Reference

Microsoft.Speech.Recognition.SrgsGrammar Namespace
Grammar
SrgsDocument
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsItem Class

[image]

SrgsItem Class
Members See Also Send Feedback

Represents a grammar element that contains phrases or other entities that a user can speak to produce a successful recognition.

Inheritance Hierarchy

System..::..Object
System..::..MarshalByRefObject
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsElement
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsItem

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class SrgsItem _
    Inherits SrgsElement
Visual Basic (Usage)
Dim instance As SrgsItem
C#
[SerializableAttribute]
public class SrgsItem : SrgsElement

Remarks

An SrgsItem object can consist of phrases, entities such as SrgsRuleRef objects, logical combinations of phrases and SrgsRuleRef objects, and so on. You can use the Elements property on the SrgsItem class to gain access to the constituents of an SrgsItem object.

The order in which SrgsItem objects appear in a given SrgsRule object specifies the order in which a user must speak them. By default, the contents of an SrgsItem must be spoken exactly once. To specify that the contents of an SrgsItem must be spoken repeatedly, use the SrgsItem(Int32) constructor and set the repeatCount parameter. Similarly, to specify a range for the number of times that an SrgsItem can be spoken, create the SrgsItem with one of the constructors that set the MaxRepeat property and the MinRepeat property. If the SrgsItem already exists, you can use one of the SrgsItem..::..SetRepeat or the SetRepeat methods to specify repeats.

You can also specify the probability that an item will be repeatedly spoken by setting the value of the RepeatProbability property.

SrgsItem objects within an SrgsOneOf object comprise a list of alternatives from which the user can speak one. You can use the Weight property to specify the likelihood that a given item in the list will be spoken.

The SrgsItem class represents the item element that is defined in the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0. For information about the SRGS item element and details about its support by the Microsoft Speech Platform SDK 11, see item Element (Microsoft.Speech).

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SrgsItem Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsItem Members

[image] [image]

SrgsItem Members
SrgsItem Class Constructors Methods Properties See Also Send Feedback

Represents a grammar element that contains phrases or other entities that a user can speak to produce a successful recognition.

The SrgsItem type exposes the following members.

Constructors

 | Name | Description
Public method | SrgsItem()()()() | Initializes a new instance of the SrgsItem class.
Public method | SrgsItem(Int32) | Initializes a new instance of the SrgsItem class and specifies the number of times that its contents must be spoken.
Public method | SrgsItem(String) | Initializes a new instance of the SrgsItem class and specifies its textual contents.
Public method | SrgsItem(array<SrgsElement>[]()[][]) | Initializes a new instance of the SrgsItem class and specifies an array of SrgsElement objects to add to this instance.
Public method | SrgsItem(Int32, Int32) | Initializes a new instance of the SrgsItem class and specifies minimum and maximum repetition counts.
Public method | SrgsItem(Int32, Int32, array<SrgsElement>[]()[][]) | Initializes a new instance of the SrgsItem class, specifies an array of SrgsElement objects to add to this instance, and sets minimum and maximum repetition counts.
Public method | SrgsItem(Int32, Int32, String) | Initializes a new instance of the SrgsItem class, specifies the text associated with the item, and sets minimum and maximum repetition counts.
Top

Properties

 | Name | Description
Public property | Elements | Gets the collection of objects contained by the SrgsItem instance.
Public property | MaxRepeat | Gets the maximum number of times that a user can speak the contents of the SrgsItem.
Public property | MinRepeat | Gets the minimum number of times that a user can speak the contents of the SrgsItem.
Public property | RepeatProbability | Gets or sets the probability that a user will repeat the contents of this SrgsItem instance.
Public property | Weight | Gets or sets a multiplying factor that adjusts the likelihood that an SrgsItem in an SrgsOneOf object will be spoken.
Top

Methods

 | Name | Description
Public method | Add | Adds an object to the collection of objects contained in this SrgsItem instance.
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | SetRepeat(Int32) | Sets the number of times that the contents of an SrgsItem must be spoken.
Public method | SetRepeat(Int32, Int32) | Sets the minimum number of times and the maximum number of times that an item can be spoken.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsItem Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsItem Constructor

[image] [image]

SrgsItem Constructor
SrgsItem Class See Also Send Feedback

Initializes a new instance of the SrgsItem class.

Overload List

 | Name | Description
Public method | SrgsItem()()()() | Initializes a new instance of the SrgsItem class.
Public method | SrgsItem(Int32) | Initializes a new instance of the SrgsItem class and specifies the number of times that its contents must be spoken.
Public method | SrgsItem(String) | Initializes a new instance of the SrgsItem class and specifies its textual contents.
Public method | SrgsItem(array<SrgsElement>[]()[][]) | Initializes a new instance of the SrgsItem class and specifies an array of SrgsElement objects to add to this instance.
Public method | SrgsItem(Int32, Int32) | Initializes a new instance of the SrgsItem class and specifies minimum and maximum repetition counts.
Public method | SrgsItem(Int32, Int32, array<SrgsElement>[]()[][]) | Initializes a new instance of the SrgsItem class, specifies an array of SrgsElement objects to add to this instance, and sets minimum and maximum repetition counts.
Public method | SrgsItem(Int32, Int32, String) | Initializes a new instance of the SrgsItem class, specifies the text associated with the item, and sets minimum and maximum repetition counts.
Top

Remarks

This overloaded constructer for SrgsItem initializes the object with a default repeatCount parameter of 0. To set the repeatCount when instantiating an SrgsItem object, use the SrgsItem constructor. To set a range of repeat counts, for example from 2 to 4, use the SrgsItem(Int32, Int32) constructor.

See Also

Reference

SrgsItem Class
SrgsItem Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsItem Constructor

[image]

SrgsItem Constructor
SrgsItem Class See Also Send Feedback

Initializes a new instance of the SrgsItem class.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New SrgsItem()
C#
public SrgsItem()

See Also

Reference

SrgsItem Class
SrgsItem Members
SrgsItem Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsItem Constructor (Int32)

[image]

SrgsItem Constructor (Int32)
SrgsItem Class See Also Send Feedback

Initializes a new instance of the SrgsItem class and specifies the number of times that its contents must be spoken.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    repeatCount As Integer _
)
Visual Basic (Usage)
Dim repeatCount As Integer

Dim instance As New SrgsItem(repeatCount)
C#
public SrgsItem(
    int repeatCount
)

Parameters

repeatCount
Type: System..::..Int32

The number of times that the item must be spoken.

Exceptions

Exception | Condition
ArgumentOutOfRangeException | repeatCount is negative or is larger than 255.

Remarks

This constructor sets MaxRepeat and MinRepeat properties of the new SrgsItem to the value in repeatCount.

See Also

Reference

SrgsItem Class
SrgsItem Members
SrgsItem Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsItem Constructor (String)

[image]

SrgsItem Constructor (String)
SrgsItem Class See Also Send Feedback

Initializes a new instance of the SrgsItem class and specifies its textual contents.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    text As String _
)
Visual Basic (Usage)
Dim text As String

Dim instance As New SrgsItem(text)
C#
public SrgsItem(
    string text
)

Parameters

text
Type: System..::..String

The text associated with the item.

Exceptions

Exception | Condition
ArgumentNullException | text is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentException | text is an empty string.

See Also

Reference

SrgsItem Class
SrgsItem Members
SrgsItem Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsItem Constructor (SrgsElement[])

[image]

SrgsItem Constructor (array<SrgsElement>[]()[][])
SrgsItem Class See Also Send Feedback

Initializes a new instance of the SrgsItem class and specifies an array of SrgsElement objects to add to this instance.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    ParamArray elements As SrgsElement() _
)
Visual Basic (Usage)
Dim elements As SrgsElement()

Dim instance As New SrgsItem(elements)
C#
public SrgsItem(
    params SrgsElement[] elements
)

Parameters

elements
Type: array< Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsElement >[]()[][]

The array of objects to add to the SrgsItem instance.

Exceptions

Exception | Condition
ArgumentNullException | elements is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentException | Any member of the elements array is nullNothingnullptrunita null reference (Nothing in Visual Basic).

See Also

Reference

SrgsItem Class
SrgsItem Members
SrgsItem Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsItem Constructor (Int32, Int32)

[image]

SrgsItem Constructor (Int32, Int32)
SrgsItem Class See Also Send Feedback

Initializes a new instance of the SrgsItem class and specifies minimum and maximum repetition counts.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    min As Integer, _
    max As Integer _
)
Visual Basic (Usage)
Dim min As Integer
Dim max As Integer

Dim instance As New SrgsItem(min, max)
C#
public SrgsItem(
    int min,
    int max
)

Parameters

min
Type: System..::..Int32

The minimum number of times that the contents of the item must be repeated.

max
Type: System..::..Int32

The maximum number of times that the text in the item can be repeated.

Exceptions

Exception | Condition
ArgumentOutOfRangeException | min is negative or larger than 255. max is negative or larger than 255.
ArgumentException | min is larger than max.

See Also

Reference

SrgsItem Class
SrgsItem Members
SrgsItem Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsItem Constructor (Int32, Int32, SrgsElement[])

[image]

SrgsItem Constructor (Int32, Int32, array<SrgsElement>[]()[][])
SrgsItem Class See Also Send Feedback

Initializes a new instance of the SrgsItem class, specifies an array of SrgsElement objects to add to this instance, and sets minimum and maximum repetition counts.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    min As Integer, _
    max As Integer, _
    ParamArray elements As SrgsElement() _
)
Visual Basic (Usage)
Dim min As Integer
Dim max As Integer
Dim elements As SrgsElement()

Dim instance As New SrgsItem(min, max, _
    elements)
C#
public SrgsItem(
    int min,
    int max,
    params SrgsElement[] elements
)

Parameters

min
Type: System..::..Int32

The minimum number of times that any of the items in the SrgsItem object must be repeated.

max
Type: System..::..Int32

The maximum number of times that the contents of the SrgsItem object must be repeated.

elements
Type: array< Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsElement >[]()[][]

The array of objects to add to the SrgsItem instance.

Exceptions

Exception | Condition
ArgumentNullException | elements is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentException | Any member of the elements array is nullNothingnullptrunita null reference (Nothing in Visual Basic).

See Also

Reference

SrgsItem Class
SrgsItem Members
SrgsItem Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsItem Constructor (Int32, Int32, String)

[image]

SrgsItem Constructor (Int32, Int32, String)
SrgsItem Class See Also Send Feedback

Initializes a new instance of the SrgsItem class, specifies the text associated with the item, and sets minimum and maximum repetition counts.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    min As Integer, _
    max As Integer, _
    text As String _
)
Visual Basic (Usage)
Dim min As Integer
Dim max As Integer
Dim text As String

Dim instance As New SrgsItem(min, max, _
    text)
C#
public SrgsItem(
    int min,
    int max,
    string text
)

Parameters

min
Type: System..::..Int32

The minimum number of times that the item can be repeated.

max
Type: System..::..Int32

The maximum number of times that the item can be repeated.

text
Type: System..::..String

The text associated with the item.

Exceptions

Exception | Condition
ArgumentOutOfRangeException | min is negative or larger than 255. max is negative or larger than 255.
ArgumentException | min is larger than max.

See Also

Reference

SrgsItem Class
SrgsItem Members
SrgsItem Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsItem Methods

[image] [image]

SrgsItem Methods
SrgsItem Class See Also Send Feedback

The SrgsItem type exposes the following members.

Methods

 | Name | Description
Public method | Add | Adds an object to the collection of objects contained in this SrgsItem instance.
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | SetRepeat(Int32) | Sets the number of times that the contents of an SrgsItem must be spoken.
Public method | SetRepeat(Int32, Int32) | Sets the minimum number of times and the maximum number of times that an item can be spoken.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsItem Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method

[image]

SrgsItem..::..Add Method
SrgsItem Class See Also Send Feedback

Adds an object to the collection of objects contained in this SrgsItem instance.

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

Syntax

Visual Basic (Declaration)
Public Sub Add ( _
    element As SrgsElement _
)
Visual Basic (Usage)
Dim instance As SrgsItem
Dim element As SrgsElement

instance.Add(element)
C#
public void Add(
    SrgsElement element
)

Parameters

element
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsElement

The object to add.

Exceptions

Exception | Condition
ArgumentNullException | element is null.

Remarks

The Add(SrgsElement) method appends elements to the Elements property.

See Also

Reference

SrgsItem Class
SrgsItem Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MemberwiseClone Method

[image] [image]

SrgsItem..::..MemberwiseClone Method
SrgsItem Class See Also Send Feedback

Overload List

 | Name | Description
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Top

See Also

Reference

SrgsItem Class
SrgsItem Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetRepeat Method

[image] [image]

SrgsItem..::..SetRepeat Method
SrgsItem Class See Also Send Feedback

Sets the repetition count for an item.

Overload List

 | Name | Description
Public method | SetRepeat(Int32) | Sets the number of times that the contents of an SrgsItem must be spoken.
Public method | SetRepeat(Int32, Int32) | Sets the minimum number of times and the maximum number of times that an item can be spoken.
Top

See Also

Reference

SrgsItem Class
SrgsItem Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetRepeat Method (Int32)

[image]

SrgsItem..::..SetRepeat Method (Int32)
SrgsItem Class See Also Send Feedback

Sets the number of times that the contents of an SrgsItem must be spoken.

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

Syntax

Visual Basic (Declaration)
Public Sub SetRepeat ( _
    count As Integer _
)
Visual Basic (Usage)
Dim instance As SrgsItem
Dim count As Integer

instance.SetRepeat(count)
C#
public void SetRepeat(
    int count
)

Parameters

count
Type: System..::..Int32

The number of times that the item must be spoken.

Exceptions

Exception | Condition
ArgumentOutOfRangeException | count is less than 0 or greater than 255.

Remarks

This method sets the MaxRepeat and MinRepeat properties to the value in count.

See Also

Reference

SrgsItem Class
SrgsItem Members
SetRepeat Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetRepeat Method (Int32, Int32)

[image]

SrgsItem..::..SetRepeat Method (Int32, Int32)
SrgsItem Class See Also Send Feedback

Sets the minimum number of times and the maximum number of times that an item can be spoken.

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

Syntax

Visual Basic (Declaration)
Public Sub SetRepeat ( _
    minRepeat As Integer, _
    maxRepeat As Integer _
)
Visual Basic (Usage)
Dim instance As SrgsItem
Dim minRepeat As Integer
Dim maxRepeat As Integer

instance.SetRepeat(minRepeat, maxRepeat)
C#
public void SetRepeat(
    int minRepeat,
    int maxRepeat
)

Parameters

minRepeat
Type: System..::..Int32

The minimum number of times that the item must be spoken.

maxRepeat
Type: System..::..Int32

The maximum number of times that the item can be spoken.

Exceptions

Exception | Condition
ArgumentOutOfRangeException | minRepeat is less than zero or larger than 255. maxRepeat is less than zero or larger than 255.
ArgumentException | minRepeat is larger than maxRepeat.

See Also

Reference

SrgsItem Class
SrgsItem Members
SetRepeat Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsItem Properties

[image] [image]

SrgsItem Properties
SrgsItem Class See Also Send Feedback

The SrgsItem type exposes the following members.

Properties

 | Name | Description
Public property | Elements | Gets the collection of objects contained by the SrgsItem instance.
Public property | MaxRepeat | Gets the maximum number of times that a user can speak the contents of the SrgsItem.
Public property | MinRepeat | Gets the minimum number of times that a user can speak the contents of the SrgsItem.
Public property | RepeatProbability | Gets or sets the probability that a user will repeat the contents of this SrgsItem instance.
Public property | Weight | Gets or sets a multiplying factor that adjusts the likelihood that an SrgsItem in an SrgsOneOf object will be spoken.
Top

See Also

Reference

SrgsItem Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Elements Property

[image]

SrgsItem..::..Elements Property
SrgsItem Class See Also Send Feedback

Gets the collection of objects contained by the SrgsItem instance.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Elements As Collection(Of SrgsElement)
    Get
Visual Basic (Usage)
Dim instance As SrgsItem
Dim value As Collection(Of SrgsElement)

value = instance.Elements
C#
public Collection<SrgsElement> Elements { get; }

Property Value

Type: System.Collections.ObjectModel..::..Collection <(Of <(<' SrgsElement >)>)>

The collection of objects contained by the SrgsItem instance.

See Also

Reference

SrgsItem Class
SrgsItem Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MaxRepeat Property

[image]

SrgsItem..::..MaxRepeat Property
SrgsItem Class See Also Send Feedback

Gets the maximum number of times that a user can speak the contents of the SrgsItem.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property MaxRepeat As Integer
    Get
Visual Basic (Usage)
Dim instance As SrgsItem
Dim value As Integer

value = instance.MaxRepeat
C#
public int MaxRepeat { get; }

Property Value

Type: System..::..Int32

The maximum number of times that a user can speak the contents of the item.

Remarks

To set this property, use the SetRepeat method.

This property represents a portion of the repeat attribute of the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0.

See Also

Reference

SrgsItem Class
SrgsItem Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MinRepeat Property

[image]

SrgsItem..::..MinRepeat Property
SrgsItem Class See Also Send Feedback

Gets the minimum number of times that a user can speak the contents of the SrgsItem.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property MinRepeat As Integer
    Get
Visual Basic (Usage)
Dim instance As SrgsItem
Dim value As Integer

value = instance.MinRepeat
C#
public int MinRepeat { get; }

Property Value

Type: System..::..Int32

The minimum number of times that a user can speak the contents of the item.

Remarks

To set this property, use the SetRepeat method.

This property represents a portion of the repeat attribute of the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0.

See Also

Reference

SrgsItem Class
SrgsItem Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RepeatProbability Property

[image]

SrgsItem..::..RepeatProbability Property
SrgsItem Class See Also Send Feedback

Gets or sets the probability that a user will repeat the contents of this SrgsItem instance.

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

Syntax

Visual Basic (Declaration)
Public Property RepeatProbability As Single
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsItem
Dim value As Single

value = instance.RepeatProbability

instance.RepeatProbability = value
C#
public float RepeatProbability { get; set; }

Property Value

Type: System..::..Single

The probability, as a floating point value, that the contents of this item will be repeatedly spoken.

Exceptions

Exception | Condition
ArgumentOutOfRangeException | An attempt is made to set RepeatProbability to a value that is negative or larger than 1.0.

Remarks

The property applies only to items whose MinRepeat and MaxRepeat properties have been explicitly set to non-default values, either by a constructor for SrgsItem or by the SetRepeat method.

See Also

Reference

SrgsItem Class
SrgsItem Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Weight Property

[image]

SrgsItem..::..Weight Property
SrgsItem Class See Also Send Feedback

Gets or sets a multiplying factor that adjusts the likelihood that an SrgsItem in an SrgsOneOf object will be spoken.

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

Syntax

Visual Basic (Declaration)
Public Property Weight As Single
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsItem
Dim value As Single

value = instance.Weight

instance.Weight = value
C#
public float Weight { get; set; }

Property Value

Type: System..::..Single

A floating point value that adjusts the likelihood of this item being spoken.

Exceptions

Exception | Condition
ArgumentOutOfRangeException | An attempt is made to set Weight to a negative value.

Remarks

The default value of this property is 1.0, which is equivalent to no weighting of the item. A weight greater than 1.0 positively biases the likelihood that the item will be spoken, and a weight less than 1.0 negatively biases the likelihood that the item will be spoken.

This property is relevant only to SrgsItem objects within an SrgsOneOf instance; it is ignored in all other cases.

See Also

Reference

SrgsItem Class
SrgsItem Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsOneOf Class

[image]

SrgsOneOf Class
Members See Also Send Feedback

Represents a list of alternative words or phrases, any one of which may be used to match speech input.

Inheritance Hierarchy

System..::..Object
System..::..MarshalByRefObject
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsElement
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsOneOf

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class SrgsOneOf _
    Inherits SrgsElement
Visual Basic (Usage)
Dim instance As SrgsOneOf
C#
[SerializableAttribute]
public sealed class SrgsOneOf : SrgsElement

Remarks

A SrgsOneOf object contains a list of alternative words or phrases, any one of which may be recognized when spoken. You can build lists of alternatives from arrays of SrgsItem objects or arrays of String objects. Use the Items property to access the alternative items in the list.

The SrgsOneOf class represents the one-of element from the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0. For information about the SRGS one-of element and details about its support by the Microsoft Speech Platform SDK 11, see one-of Element (Microsoft.Speech).

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SrgsOneOf Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsOneOf Members

[image] [image]

SrgsOneOf Members
SrgsOneOf Class Constructors Methods Properties See Also Send Feedback

Represents a list of alternative words or phrases, any one of which may be used to match speech input.

The SrgsOneOf type exposes the following members.

Constructors

 | Name | Description
Public method | SrgsOneOf()()()() | Initializes a new instance of the SrgsOneOf class.
Public method | SrgsOneOf(array<String>[]()[][]) | Initializes a new instance of the SrgsOneOf class from an array of String objects.
Public method | SrgsOneOf(array<SrgsItem>[]()[][]) | Initializes a new instance of the SrgsOneOf class, specifying one or more alternative items in the passed SrgsItem array.
Top

Properties

 | Name | Description
Public property | Items | Gets the list of all the alternatives contained in the SrgsOneOf element.
Top

Methods

 | Name | Description
Public method | Add | Adds an SrgsItem containing a word or a phrase to the list of alternatives.
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsOneOf Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsOneOf Constructor

[image] [image]

SrgsOneOf Constructor
SrgsOneOf Class See Also Send Feedback

Creates a new instance of the SrgsOneOf class.

Overload List

 | Name | Description
Public method | SrgsOneOf()()()() | Initializes a new instance of the SrgsOneOf class.
Public method | SrgsOneOf(array<String>[]()[][]) | Initializes a new instance of the SrgsOneOf class from an array of String objects.
Public method | SrgsOneOf(array<SrgsItem>[]()[][]) | Initializes a new instance of the SrgsOneOf class, specifying one or more alternative items in the passed SrgsItem array.
Top

Remarks

You can construct an instance of the SrgsOneOf class from an array of String objects, from an array of SrgsItem objects, or as an empty list. Using SrgsItem objects instead of String objects in a list of alternatives lets you apply properties of SrgsItem to each item in the list, such as MinRepeat, MaxRepeat, RepeatProbability, and Weight.

See Also

Reference

SrgsOneOf Class
SrgsOneOf Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsOneOf Constructor

[image]

SrgsOneOf Constructor
SrgsOneOf Class Example See Also Send Feedback

Initializes a new instance of the SrgsOneOf class.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New SrgsOneOf()
C#
public SrgsOneOf()

Examples

The following example uses the SrgsOneOf element to build lists of SrgsItem elements containing country names, any one of which may be used to recognize the containing phrase. The example then adds one of the resulting SrgsOneOf objects to their respective rules for European countries and South American countries. Further on, the example uses the SrgsOneOf object to group rule references to ruleEurope and ruleSAmerica into a list of two alternatives, either one of which may be used to recognize spoken input.

Copy image Copy Code
public void WorldSoccerWinners ()
{

  // Create an SrgsDocument, create a new rule
  // and set its scope to public.
  SrgsDocument document = new SrgsDocument();
  SrgsRule winnerRule = new SrgsRule("WorldCupWinner");
  winnerRule.Scope = SrgsRuleScope.Public;

  // Add the introduction.
  winnerRule.Elements.Add(new SrgsItem("A nation that has won the world cup is: "));

  // Create the rule for the European nations.
  SrgsOneOf oneOfEurope = new SrgsOneOf(new SrgsItem[] {new SrgsItem("England"),
    new SrgsItem("France"), new SrgsItem("Germany"), new SrgsItem("Italy")});
  SrgsRule ruleEurope = (new SrgsRule("EuropeanNations", new SrgsElement[] {oneOfEurope}));

  // Create the rule for the South American nations.
  SrgsOneOf oneOfSAmerica = new SrgsOneOf(new SrgsItem[] {new SrgsItem("Argentina"),
    new SrgsItem("Brazil"), new SrgsItem("Uruguay")});
  SrgsRule ruleSAmerica = (new SrgsRule("SouthAmericanNations", new SrgsElement[] {oneOfSAmerica}));

  // Add references to winnerRule for ruleEurope and ruleSAmerica.
  winnerRule.Elements.Add(new SrgsOneOf(new SrgsItem[] {(new SrgsItem
    (new SrgsRuleRef(ruleEurope))), new SrgsItem(new SrgsRuleRef(ruleSAmerica))}));

  // Add all the rules to the document and make winnerRule
  // the root rule of the document.
  document.Rules.Add(new SrgsRule[] {winnerRule, ruleEurope, ruleSAmerica});
  document.Root = winnerRule;
}

See Also

Reference

SrgsOneOf Class
SrgsOneOf Members
SrgsOneOf Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsOneOf Constructor (String[])

[image]

SrgsOneOf Constructor (array<String>[]()[][])
SrgsOneOf Class Example See Also Send Feedback

Initializes a new instance of the SrgsOneOf class from an array of String objects.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    ParamArray items As String() _
)
Visual Basic (Usage)
Dim items As String()

Dim instance As New SrgsOneOf(items)
C#
public SrgsOneOf(
    params string[] items
)

Parameters

items
Type: array< System..::..String >[]()[][]

The alternative items to add.

Exceptions

Exception | Condition
ArgumentNullException | items is nullNothingnullptrunita null reference (Nothing in Visual Basic). Any element in the items array is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Examples

The following example creates a grammar that recognizes the phrase "A nation that has won the World Cup is" followed by the name of a country that has won the World Cup. The example uses the SrgsOneOf element to build lists of acceptable country names from an array of String objects. The example then adds one of the resulting SrgsOneOf objects to their respective rules for European countries and South American countries.

Copy image Copy Code
public void WorldSoccerWinners ()
{
    // Create a grammar from an SRGSDocument, create a new rule
  // and set its scope to public.
  SrgsDocument srgsGrammar = new SrgsDocument ();
  SrgsRule winnerRule = new SrgsRule ("WorldCupWinner");
  winnerRule.Scope = SrgsRuleScope.Public;

  // Add the introduction.
  winnerRule.Elements.Add (new SrgsItem ("A nation that has won the world cup is"));

  // Create the rule for the European nations.
  SrgsOneOf oneOfEurope = new SrgsOneOf (new string[] {"England","France","Germany","Italy"});
  SrgsRule ruleEurope = (new SrgsRule("EuropeanNations", new SrgsElement[] {oneOfEurope}));

  // Create the rule for the South American nations.
  SrgsOneOf oneOfSAmerica = new SrgsOneOf (new string[] {"Argentina","Brazil","Uruguay"});
  SrgsRule ruleSAmerica = (new SrgsRule("SouthAmericanNations", new SrgsElement[] {oneOfSAmerica}));

  // Add references to winnerRule for ruleEurope and ruleSAmerica.
  winnerRule.Elements.Add(new SrgsOneOf(new SrgsItem[] {(new SrgsItem
    (new SrgsRuleRef(ruleEurope))), new SrgsItem(new SrgsRuleRef(ruleSAmerica))}));

  // Add all the rules to the grammar and make winnerRule
  // the root rule of the grammar.
  srgsGrammar.Rules.Add (new SrgsRule[] {winnerRule, ruleEurope, ruleSAmerica});
  srgsGrammar.Root = winnerRule;
}

See Also

Reference

SrgsOneOf Class
SrgsOneOf Members
SrgsOneOf Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsOneOf Constructor (SrgsItem[])

[image]

SrgsOneOf Constructor (array<SrgsItem>[]()[][])
SrgsOneOf Class Example See Also Send Feedback

Initializes a new instance of the SrgsOneOf class, specifying one or more alternative items in the passed SrgsItem array.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    ParamArray items As SrgsItem() _
)
Visual Basic (Usage)
Dim items As SrgsItem()

Dim instance As New SrgsOneOf(items)
C#
public SrgsOneOf(
    params SrgsItem[] items
)

Parameters

items
Type: array< Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsItem >[]()[][]

The alternative items to add.

Exceptions

Exception | Condition
ArgumentNullException | items is nullNothingnullptrunita null reference (Nothing in Visual Basic). Any element in the items array is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Examples

The following example creates a grammar that recognizes the phrase "A nation that has won the World Cup is" followed by the name of a country that has won the World Cup. It creates a public rule named WorldCupWinner. It then creates two SrgsRule objects using SrgsOneOf objects that contain arrays of new SrgsItem objects. To see the grammar that this example generates, see SrgsRule.

C# Copy image Copy Code
 public void WorldSoccerWinners ()
{

  // Create an SrgsDocument, create a new rule
  // and set its scope to public.
  SrgsDocument document = new SrgsDocument();
  SrgsRule winnerRule = new SrgsRule("WorldCupWinner");
  winnerRule.Scope = SrgsRuleScope.Public;

  // Add the introduction.
  winnerRule.Elements.Add(new SrgsItem("A nation that has won the world cup is: "));

  // Create the rule for the European nations.
  SrgsOneOf oneOfEurope = new SrgsOneOf(new SrgsItem[] {new SrgsItem("England"),new SrgsItem("France"), new SrgsItem("Germany"), new SrgsItem("Italy")});
  SrgsRule ruleEurope = (new SrgsRule("EuropeanNations", new SrgsElement[] {oneOfEurope}));

  // Create the rule for the South American nations.
  SrgsOneOf oneOfSAmerica = new SrgsOneOf(new SrgsItem[] {new SrgsItem("Argentina"),new SrgsItem("Brazil"), new SrgsItem("Uruguay")});
  SrgsRule ruleSAmerica = (new SrgsRule("SouthAmericanNations", new SrgsElement[] {oneOfSAmerica}));

  // Add references to winnerRule for ruleEurope and ruleSAmerica.
  winnerRule.Elements.Add(new SrgsOneOf(new SrgsItem[] {(new SrgsItem
    (new SrgsRuleRef(ruleEurope))), new SrgsItem(new SrgsRuleRef(ruleSAmerica))}));

  // Add all the rules to the document and make winnerRule
  // the root rule of the document.
  document.Rules.Add(new SrgsRule[] {winnerRule, ruleEurope, ruleSAmerica});
  document.Root = winnerRule;
}

See Also

Reference

SrgsOneOf Class
SrgsOneOf Members
SrgsOneOf Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsOneOf Methods

[image] [image]

SrgsOneOf Methods
SrgsOneOf Class See Also Send Feedback

The SrgsOneOf type exposes the following members.

Methods

 | Name | Description
Public method | Add | Adds an SrgsItem containing a word or a phrase to the list of alternatives.
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsOneOf Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method

[image]

SrgsOneOf..::..Add Method
SrgsOneOf Class Example See Also Send Feedback

Adds an SrgsItem containing a word or a phrase to the list of alternatives.

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

Syntax

Visual Basic (Declaration)
Public Sub Add ( _
    item As SrgsItem _
)
Visual Basic (Usage)
Dim instance As SrgsOneOf
Dim item As SrgsItem

instance.Add(item)
C#
public void Add(
    SrgsItem item
)

Parameters

item
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsItem

The item to add to the list of alternatives.

Exceptions

Exception | Condition
ArgumentNullException | item is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Examples

The following example creates a grammar that recognizes the phrase "A nation that has won the World Cup is" followed by the name of a country that has won the World Cup. The example uses the SrgsOneOf object to build lists of acceptable country names from an array of SrgsItem objects. Using the Add(SrgsItem) method, the example appends an SrgsItem that contains the string "Italy" to the SrgsOneOf object oneOfEurope.

Copy image Copy Code
public void WorldSoccerWinners ()
{

  // Create an SrgsDocument, create a new rule
  // and set its scope to public.
  SrgsDocument document = new SrgsDocument();
  SrgsRule winnerRule = new SrgsRule("WorldCupWinner");
  winnerRule.Scope = SrgsRuleScope.Public;

  // Add the introduction.
  winnerRule.Elements.Add(new SrgsItem("A nation that has won the world cup is: "));

  // Create the rule for the European nations.
  SrgsOneOf oneOfEurope = new SrgsOneOf(new SrgsItem[] {new SrgsItem("England"),
    new SrgsItem("France"), new SrgsItem("Germany")});
  oneOfEurope.Add(new SrgsItem("Italy"));
  SrgsRule ruleEurope = (new SrgsRule("EuropeanNations", new SrgsElement[] {oneOfEurope}));

  // Create the rule for the South American nations.
  SrgsOneOf oneOfSAmerica = new SrgsOneOf(new SrgsItem[] {new SrgsItem("Argentina"),
    new SrgsItem("Brazil"), new SrgsItem("Uruguay")});
  SrgsRule ruleSAmerica = (new SrgsRule("SouthAmericanNations", new SrgsElement[] {oneOfSAmerica}));

  // Add references to winnerRule for ruleEurope and ruleSAmerica.
  winnerRule.Elements.Add(new SrgsOneOf(new SrgsItem[] {(new SrgsItem
    (new SrgsRuleRef(ruleEurope))), new SrgsItem(new SrgsRuleRef(ruleSAmerica))}));

  // Add all the rules to the document and make winnerRule
  // the root rule of the document.
  document.Rules.Add(new SrgsRule[] {winnerRule, ruleEurope, ruleSAmerica});
  document.Root = winnerRule;
}

See Also

Reference

SrgsOneOf Class
SrgsOneOf Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MemberwiseClone Method

[image] [image]

SrgsOneOf..::..MemberwiseClone Method
SrgsOneOf Class See Also Send Feedback

Overload List

 | Name | Description
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Top

See Also

Reference

SrgsOneOf Class
SrgsOneOf Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsOneOf Properties

[image] [image]

SrgsOneOf Properties
SrgsOneOf Class See Also Send Feedback

The SrgsOneOf type exposes the following members.

Properties

 | Name | Description
Public property | Items | Gets the list of all the alternatives contained in the SrgsOneOf element.
Top

See Also

Reference

SrgsOneOf Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Items Property

[image]

SrgsOneOf..::..Items Property
SrgsOneOf Class See Also Send Feedback

Gets the list of all the alternatives contained in the SrgsOneOf element.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Items As Collection(Of SrgsItem)
    Get
Visual Basic (Usage)
Dim instance As SrgsOneOf
Dim value As Collection(Of SrgsItem)

value = instance.Items
C#
public Collection<SrgsItem> Items { get; }

Property Value

Type: System.Collections.ObjectModel..::..Collection <(Of <(<' SrgsItem >)>)>

Returns the list of alternatives.

Remarks

The alternative words and phrases returned by this property may have been added to the SrgsOneOf as SrgsItem or String objects.

See Also

Reference

SrgsOneOf Class
SrgsOneOf Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsPhoneticAlphabet Enumeration

[image]

SrgsPhoneticAlphabet Enumeration
See Also Send Feedback

Enumerates the supported phonetic alphabets.

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

Syntax

Visual Basic (Declaration)
Public Enumeration SrgsPhoneticAlphabet
Visual Basic (Usage)
Dim instance As SrgsPhoneticAlphabet
C#
public enum SrgsPhoneticAlphabet

Members

Member name | Description
Sapi | Speech API phone set.
Ipa | International Phonetic Alphabet (IPA) phone set.
Ups | Universal Phone Set (UPS), a machine-readable phone set that is based on the International Phonetic Alphabet (IPA).

Remarks

Phonetic alphabets are composed of phones, which consist of letters, numbers or characters, sometimes in combination. Each phone describes a unique sound of speech. This is in contrast to the Latin alphabet, for which any letter may represent multiple spoken sounds. Consider the different pronunciations of the letter "c" in the words "candy" and "cease", or the different pronunciations of the letter combination "th" in the words "thing" and "those".

In the Microsoft Speech Platform SDK 11, you can use any of three phonetic alphabets to specify custom pronunciations: International Phone Alphabet (IPA), Universal Phone Set (UPS), or the SAPI phone set. The specified phonetic alphabet determines which phone set will be used to define inline pronunciations for SrgsToken objects. The phones specified in Pronunciation must match the phonetic alphabet specified in PhoneticAlphabet.

For more information, see Lexicons and Phonetic Alphabets (Microsoft.Speech).

See Also

Reference

Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRule Class

[image]

SrgsRule Class
Members See Also Send Feedback

Represents a grammar rule.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsRule

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class SrgsRule
Visual Basic (Usage)
Dim instance As SrgsRule
C#
[SerializableAttribute]
public sealed class SrgsRule

Remarks

Use the SrgsRule class to create a new rule at run time or to modify a rule in an existing grammar stream or file at run time.

The words and phrases specified by SrgsRule objects in grammars defined by SrgsDocument instances limit the spoken input that the recognizer must be able to identify.

An SrgsRule object specifies the sequence in which words and phrases must be spoken by ordering the objects that contain them. Words and phrases within a rule are represented by objects such as SrgsItem, SrgsOneOf, SrgsRuleRef, and SrgsToken elements. Use the Elements property to access the collection of child objects that an SrgsRule object contains.

You can determine whether an SrgsRule can be specified in a rule reference from a rule in an external grammar by setting its Scope property.

It is not legal to define an SrgsRule that is empty or that contains only white space.

This class represents the rule element that is defined in the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0. For information about the SRGS rule element and details about its support by the Microsoft Speech Platform SDK 11, see rule Element (Microsoft.Speech).

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SrgsRule Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRule Members

[image] [image]

SrgsRule Members
SrgsRule Class Constructors Methods Properties See Also Send Feedback

Represents a grammar rule.

The SrgsRule type exposes the following members.

Constructors

 | Name | Description
Public method | SrgsRule(String) | Initializes a new instance of the SrgsRule class and specifies the identifier for the rule.
Public method | SrgsRule(String, array<SrgsElement>[]()[][]) | Initializes a new instance of the SrgsRule class from an array of SrgsElement objects.
Top

Properties

 | Name | Description
Public property | Elements | Gets the collection of SrgsElement objects in the SrgsRule instance.
Public property | Id | Gets or sets the identifier for the rule.
Public property | Scope | Gets or sets whether a rule can be activated for recognition and when the rule can be referenced by other rules.
Top

Methods

 | Name | Description
Public method | Add | Adds an SrgsElement to an SrgsRule object.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsRule Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRule Constructor

[image] [image]

SrgsRule Constructor
SrgsRule Class See Also Send Feedback

Initializes a new instance of the SrgsRule class.

Overload List

 | Name | Description
Public method | SrgsRule(String) | Initializes a new instance of the SrgsRule class and specifies the identifier for the rule.
Public method | SrgsRule(String, array<SrgsElement>[]()[][]) | Initializes a new instance of the SrgsRule class from an array of SrgsElement objects.
Top

See Also

Reference

SrgsRule Class
SrgsRule Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRule Constructor (String)

[image]

SrgsRule Constructor (String)
SrgsRule Class Example See Also Send Feedback

Initializes a new instance of the SrgsRule class and specifies the identifier for the rule.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    id As String _
)
Visual Basic (Usage)
Dim id As String

Dim instance As New SrgsRule(id)
C#
public SrgsRule(
    string id
)

Parameters

id
Type: System..::..String

The identifier of the rule.

Exceptions

Exception | Condition
ArgumentNullException | id is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException | id is empty.
FormatException | id is not a proper rule identifier.

Remarks

The SrgsRule..::..SrgsRule constructor initializes the Id property. The identifier must be unique within a given grammar.

The SrgsRule..::..SrgsRule constructor throws a FormatException in the following circumstances:

  • id is not a valid XML name, as defined in Extensible Markup Language (XML) 1.0 (Fifth Edition). To paraphrase this definition, a valid XML name must begin with a letter, an underscore ('_'), or a colon (':') and can be followed by zero or more NameChar characters (also defined in the XML specification).

  • id is "NULL" or "VOID" or "GARBAGE".

  • id contains at least one invalid rule ID character. These characters are: '?', '*', '+', '|', '(', '), '^', '$', '/', ';', '.', '=', '<', '>', '[', ']', '{', '}', '\\', ' ', '\t', '\r', and '\n'.

Examples

The following example creates a grammar that recognizes the phrase "A nation that has won the World Cup is" followed by the name of a country that has won the World Cup. The example creates a SrgsRule object named winnerRule and passes in the identifier WorldCupWinner as a String. The SrgsOneOf object consists of an array of new SrgsItem objects containing alternatives to be recognized by the rule.

Copy image Copy Code
public void WorldSoccerWinners ()
{

  // Create an SrgsDocument, create a new rule
  // and set its scope to public.
  SrgsDocument document = new SrgsDocument();
  SrgsRule winnerRule = new SrgsRule("WorldCupWinner");
  winnerRule.Scope = SrgsRuleScope.Public;

  // Add the introduction.
  winnerRule.Elements.Add(new SrgsItem("A nation that has won the world cup is: "));

  // Create the rule for the European nations.
  SrgsOneOf oneOfEurope = new SrgsOneOf(new SrgsItem[] {new SrgsItem("England"),
    new SrgsItem("France"), new SrgsItem("Germany"), new SrgsItem("Italy")});
  SrgsRule ruleEurope = (new SrgsRule("EuropeanNations", new SrgsElement[] {oneOfEurope}));

  // Create the rule for the South American nations.
  SrgsOneOf oneOfSAmerica = new SrgsOneOf(new SrgsItem[] {new SrgsItem("Argentina"),
    new SrgsItem("Brazil"), new SrgsItem("Uruguay")});
  SrgsRule ruleSAmerica = (new SrgsRule("SouthAmericanNations", new SrgsElement[] {oneOfSAmerica}));

  // Add references to winnerRule for ruleEurope and ruleSAmerica.
  winnerRule.Elements.Add(new SrgsOneOf(new SrgsItem[] {(new SrgsItem
    (new SrgsRuleRef(ruleEurope))), new SrgsItem(new SrgsRuleRef(ruleSAmerica))}));

  // Add all the rules to the document and make winnerRule
  // the root rule of the document.
  document.Rules.Add(new SrgsRule[] {winnerRule, ruleEurope, ruleSAmerica});
  document.Root = winnerRule;
}

See Also

Reference

SrgsRule Class
SrgsRule Members
SrgsRule Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRule Constructor (String, SrgsElement[])

[image]

SrgsRule Constructor (String, array<SrgsElement>[]()[][])
SrgsRule Class Example See Also Send Feedback

Initializes a new instance of the SrgsRule class from an array of SrgsElement objects.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    id As String, _
    ParamArray elements As SrgsElement() _
)
Visual Basic (Usage)
Dim id As String
Dim elements As SrgsElement()

Dim instance As New SrgsRule(id, elements)
C#
public SrgsRule(
    string id,
    params SrgsElement[] elements
)

Parameters

id
Type: System..::..String

The identifier of the rule.

elements
Type: array< Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsElement >[]()[][]

An array of SrgsElement objects.

Exceptions

Exception | Condition
ArgumentNullException | id is nullNothingnullptrunita null reference (Nothing in Visual Basic). elements is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException | id is empty.
FormatException | id is not a proper rule identifier.

Remarks

The SrgsRule constructor initializes the Id property. The identifier must be unique within a given grammar.

The SrgsRule constructor throws a FormatException in the following circumstances:

  • id is not a valid XML name, as defined in Extensible Markup Language (XML) 1.0 (Fifth Edition). To paraphrase this definition, a valid XML name must begin with a letter, an underscore ('_'), or a colon (':') and can be followed by zero or more NameChar characters (also defined in the XML specification).

  • id is "NULL" or "VOID" or "GARBAGE".

  • id contains at least one invalid rule ID character. These characters are: '?', '*', '+', '|', '(', '), '^', '$', '/', ';', '.', '=', '<', '>', '[', ']', '{', '}', '\\', ' ', '\t', '\r', and '\n'.

Examples

The following example creates a grammar that recognizes the phrase "A nation that has won the World Cup is" followed by the name of a country that has won the World Cup. The example creates a public rule named WorldCupWinner. The example then creates two SrgsRule objects, ruleEurope and ruleSAmerica, passing in a String for the rule identifier and an SrgsElement array containing a SrgsOneOf object. Subsequently, the example adds rule references to ruleEurope and ruleSAmerica from the rule WorldCupWinner.

Copy image Copy Code
public void WorldSoccerWinners ()
{
  // Create a grammar from an SRGSDocument, create a new rule
  // and set its scope to public.
  SrgsDocument srgsGrammar = new SrgsDocument ();
  SrgsRule winnerRule = new SrgsRule ("WorldCupWinner");
  winnerRule.Scope = SrgsRuleScope.Public;

  // Add the introduction.
  winnerRule.Elements.Add (new SrgsItem ("A nation that has won the world cup is"));

  // Create the rule for the European nations.
  SrgsOneOf oneOfEurope = new SrgsOneOf(new SrgsItem[] {new SrgsItem("England"), new SrgsItem("France"), new SrgsItem("Germany"), new SrgsItem("Italy")});
  SrgsRule ruleEurope = (new SrgsRule("EuropeanNations", new SrgsElement[] {oneOfEurope}));

  // Create the rule for the South American nations.
  SrgsOneOf oneOfSAmerica = new SrgsOneOf(new SrgsItem[] {new SrgsItem("Argentina"), new SrgsItem("Brazil"), new SrgsItem("Uruguay")});
  SrgsRule ruleSAmerica = (new SrgsRule("SouthAmericanNations", new SrgsElement[] {oneOfSAmerica}));

  // Add references to winnerRule for ruleEurope and ruleSAmerica.
  winnerRule.Elements.Add(new SrgsOneOf(new SrgsItem[] {(new SrgsItem (new SrgsRuleRef(ruleEurope))), new SrgsItem(new SrgsRuleRef(ruleSAmerica))}));

  // Add all the rules to the grammar and make winnerRule
  // the root rule of the grammar.
  document.Rules.Add(new SrgsRule[] {winnerRule, ruleEurope, ruleSAmerica});
  srgsGrammar.Root = winnerRule;
}

The created grammar has the following form.

Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" xmlns="http://www.w3.org/2001/06/grammar" root="WorldCupWinner">
    <rule id="WorldCupWinner" scope="public">
        <item> A nation that has won the world cup is </item>
        <one-of>
            <item>
                <ruleref uri="#EuropeanNations" />
            </item>
            <item>
                <ruleref uri="#SouthAmericanNations" />
            </item>
        </one-of>
    </rule>
    <rule id="EuropeanNations">
        <one-of>
            <item> England </item>
            <item> France </item>
            <item> Germany </item>
            <item> Italy </item>
        </one-of>
    </rule>
    <rule id="SouthAmericanNations">
        <one-of>
            <item> Argentina </item>
            <item> Brazil </item>
            <item> Uruguay </item>
        </one-of>
    </rule>
</grammar>

See Also

Reference

SrgsRule Class
SrgsRule Members
SrgsRule Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRule Methods

[image] [image]

SrgsRule Methods
SrgsRule Class See Also Send Feedback

The SrgsRule type exposes the following members.

Methods

 | Name | Description
Public method | Add | Adds an SrgsElement to an SrgsRule object.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsRule Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method

[image]

SrgsRule..::..Add Method
SrgsRule Class Example See Also Send Feedback

Adds an SrgsElement to an SrgsRule object.

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

Syntax

Visual Basic (Declaration)
Public Sub Add ( _
    element As SrgsElement _
)
Visual Basic (Usage)
Dim instance As SrgsRule
Dim element As SrgsElement

instance.Add(element)
C#
public void Add(
    SrgsElement element
)

Parameters

element
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsElement

An object that inherits from SrgsElement and specifies what can be recognized.

Exceptions

Exception | Condition
ArgumentNullException | element is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Remarks

Typical additions to an SrgsRule object include SrgsItem, SrgsOneOf, SrgsRuleRef, and SrgsToken objects that specify what speakers can say. A valid rule element must contain at least one piece of recognizable text or one rule reference. See Create Grammars Using SrgsGrammar (Microsoft.Speech) for more information.

An SrgsRule object may also contain SrgsSemanticInterpretationTag objects that add semantic values and semantic keys to the rule. The speech recognition engine will return the semantic information, as well as the recognized phrase, when it recognizes the phrase. See Semantic Interpretation Markup (Microsoft.Speech) for more information.

Examples

The following example creates a grammar that recognizes the phrase "A nation that has won the World Cup is" followed by the name of a country that has won the World Cup. After creating the SrgsRule object winnerRule and giving it the string identifier WorldCupWinner, the example uses the Add(SrgsElement) method to append the string "A nation that has won the World Cup is" to the rule. The example then creates two additional rules, ruleEurope and ruleSAmerica. Again using the Add(SrgsElement) method, the example appends an SrgsOneOf object to the WorldCupWinner rule that contains rule references to ruleEurope and ruleSAmerica.

Copy image Copy Code
// Create an SrgsDocument, create a new rule
// and set its scope to public.
SrgsDocument document = new SrgsDocument();
SrgsRule winnerRule = new SrgsRule("WorldCupWinner");
winnerRule.Scope = SrgsRuleScope.Public;

// Add the introduction.
winnerRule.Elements.Add(new SrgsItem("A nation that has won the world cup is: "));

// Create the rule for the European nations.
SrgsOneOf oneOfEurope = new SrgsOneOf(new SrgsItem[] {new SrgsItem("England"), new SrgsItem("France"), new SrgsItem("Germany"), new SrgsItem("Italy")});
SrgsRule ruleEurope = (new SrgsRule("EuropeanNations", new SrgsElement[] {oneOfEurope}));

// Create the rule for the South American nations.
SrgsOneOf oneOfSAmerica = new SrgsOneOf(new SrgsItem[] {new SrgsItem("Argentina"), new SrgsItem("Brazil"), new SrgsItem("Uruguay")});
SrgsRule ruleSAmerica = (new SrgsRule("SouthAmericanNations", new SrgsElement[] {oneOfSAmerica}));

// Add references to winnerRule for ruleEurope and ruleSAmerica.
winnerRule.Elements.Add(new SrgsOneOf(new SrgsItem[] {(new SrgsItem (new SrgsRuleRef(ruleEurope))), new SrgsItem(new SrgsRuleRef(ruleSAmerica))}));

// Add all the rules to the document and make winnerRule
// the root rule of the document.
document.Rules.Add(new SrgsRule[] {winnerRule, ruleEurope, ruleSAmerica});
document.Root = winnerRule;

See Also

Reference

SrgsRule Class
SrgsRule Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
Semantic Interpretation Markup (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRule Properties

[image] [image]

SrgsRule Properties
SrgsRule Class See Also Send Feedback

The SrgsRule type exposes the following members.

Properties

 | Name | Description
Public property | Elements | Gets the collection of SrgsElement objects in the SrgsRule instance.
Public property | Id | Gets or sets the identifier for the rule.
Public property | Scope | Gets or sets whether a rule can be activated for recognition and when the rule can be referenced by other rules.
Top

See Also

Reference

SrgsRule Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Elements Property

[image]

SrgsRule..::..Elements Property
SrgsRule Class See Also Send Feedback

Gets the collection of SrgsElement objects in the SrgsRule instance.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Elements As Collection(Of SrgsElement)
    Get
Visual Basic (Usage)
Dim instance As SrgsRule
Dim value As Collection(Of SrgsElement)

value = instance.Elements
C#
public Collection<SrgsElement> Elements { get; }

Property Value

Type: System.Collections.ObjectModel..::..Collection <(Of <(<' SrgsElement >)>)>

The collection of elements in the rule.

Remarks

The elements in an SrgsRule object can consist of SrgsItem, SrgsOneOf, SrgsRuleRef, SrgsToken, and SrgsSemanticInterpretationTag objects.

See Also

Reference

SrgsRule Class
SrgsRule Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Id Property

[image]

SrgsRule..::..Id Property
SrgsRule Class See Also Send Feedback

Gets or sets the identifier for the rule.

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

Syntax

Visual Basic (Declaration)
Public Property Id As String
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsRule
Dim value As String

value = instance.Id

instance.Id = value
C#
public string Id { get; set; }

Property Value

Type: System..::..String

The identifier for the rule.

Exceptions

Exception | Condition
FormatException | An attempt is made to set Id to an invalid value.

Remarks

The identifier for a rule is a string that contains the name of the rule.

A value used to set Id must adhere to the following rules:

  • The value must be a valid XML name, as defined in Extensible Markup Language (XML) 1.0 (Fifth Edition). To paraphrase this definition, a valid XML name must begin with a letter, an underscore ('_'), or a colon (':') and can be followed by zero or more NameChar characters (also defined in the XML specification).

  • The value can be "NULL" or "VOID" or "GARBAGE".

  • The value cannot contain any invalid rule ID character. These characters are: '?', '*', '+', '|', '(', '), '^', '$', '/', ';', '.', '=', '<', '>', '[', ']', '{', '}', '\\', ' ', '\t', '\r', and '\n'.

See Also

Reference

SrgsRule Class
SrgsRule Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Scope Property

[image]

SrgsRule..::..Scope Property
SrgsRule Class Example See Also Send Feedback

Gets or sets whether a rule can be activated for recognition and when the rule can be referenced by other rules.

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

Syntax

Visual Basic (Declaration)
Public Property Scope As SrgsRuleScope
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsRule
Dim value As SrgsRuleScope

value = instance.Scope

instance.Scope = value
C#
public SrgsRuleScope Scope { get; set; }

Property Value

Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsRuleScope

A value the sets the scope for the rule.

Remarks

The default value for scope is Private. A private rule can only be activated for recognition by a rule reference from the root rule in its containing grammar or from another rule that is referenced from the root rule. A private rule cannot be referenced by an external grammar, unless the private rule is declared as the root rule of its containing grammar.

If its scope is set to Public, an SrgsRule object can be activated for recognition by a reference from a SrgsRuleRef object in the containing grammar or from a rule in an external grammar.

Examples

The following example creates a grammar that recognizes the phrase "A nation that has won the World Cup is" followed by the name of a country that has won the World Cup. It creates a public rule named WorldCupWinner and sets the scope of that rule to Public.

Copy image Copy Code
// Create an SrgsDocument, create a new rule and set its scope to public.
SrgsDocument document = new SrgsDocument();
SrgsRule winnerRule = new SrgsRule("WorldCupWinner");
winnerRule.Scope = SrgsRuleScope.Public;

// Add the introduction.
winnerRule.Elements.Add(new SrgsItem("A nation that has won the world cup is: "));

// Create the rule for the European nations.
SrgsOneOf oneOfEurope = new SrgsOneOf(new SrgsItem[] {new SrgsItem("England"), new SrgsItem("France"), new SrgsItem("Germany"), new SrgsItem("Italy")});
SrgsRule ruleEurope = (new SrgsRule("EuropeanNations", new SrgsElement[] {oneOfEurope}));

// Create the rule for the South American nations.
SrgsOneOf oneOfSAmerica = new SrgsOneOf(new SrgsItem[] {new SrgsItem("Argentina"), new SrgsItem("Brazil"), new SrgsItem("Uruguay")});
SrgsRule ruleSAmerica = (new SrgsRule("SouthAmericanNations", new SrgsElement[] {oneOfSAmerica}));

// Add references to winnerRule for ruleEurope and ruleSAmerica.
winnerRule.Elements.Add(new SrgsOneOf(new SrgsItem[] {(new SrgsItem (new SrgsRuleRef(ruleEurope)), new SrgsItem(new SrgsRuleRef(ruleSAmerica)})));

// Add all the rules to the document and make winnerRule
// the root rule of the document.
document.Rules.Add(new SrgsRule[] {winnerRule, ruleEurope, ruleSAmerica});
document.Root = winnerRule;

The created grammar has the following form.

Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" xmlns="http://www.w3.org/2001/06/grammar" root="WorldCupWinner">
    <rule id="WorldCupWinner" scope="public">
        <item> A nation that has won the world cup is </item>
        <one-of>
            <item>
                <ruleref uri="#EuropeanNations" />
            </item>
            <item>
                <ruleref uri="#SouthAmericanNations" />
            </item>
        </one-of>
    </rule>
    <rule id="EuropeanNations">
        <one-of>
            <item> England< /item>
            <item> France </item>
            <item> Germany </item>
            <item> Italy </item>
        </one-of>
    </rule>
    <rule id="SouthAmericanNations">
        <one-of>
            <item> Argentina </item>
            <item> Brazil </item>
            <item> Uruguay </item>
        </one-of>
    </rule>
</grammar>

See Also

Reference

SrgsRule Class
SrgsRule Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
Speech Recognition Grammar Specification Version 1.0
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRuleRef Class

[image]

SrgsRuleRef Class
Members See Also Send Feedback

Represents the grammar element that specifies a reference to a rule.

Inheritance Hierarchy

System..::..Object
System..::..MarshalByRefObject
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsElement
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsRuleRef

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class SrgsRuleRef _
    Inherits SrgsElement
Visual Basic (Usage)
Dim instance As SrgsRuleRef
C#
[SerializableAttribute]
public sealed class SrgsRuleRef : SrgsElement

Remarks

The SrgsRuleRef class is particularly useful when you want to reuse an SrgsRule element whose contents have already been defined. By reusing existing rules, you can build complex grammars more quickly.

You can use one of the constructors of the SrgsRuleRef class to reference an SrgsRule object or a rule element if the following is true:

  • The SrgsRule object is in the containing grammar and the value of its Scope property is Public or Private.

  • The rule element is in an external grammar and the value of its scope attribute is public.

  • The rule element is in an external grammar, the value of its scope attribute is private, and it is declared as the root rule of the external grammar.

This class represents the ruleref element as defined in the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SrgsRuleRef Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRuleRef Members

[image] [image]

SrgsRuleRef Members
SrgsRuleRef Class Constructors Methods Fields Properties See Also Send Feedback

Represents the grammar element that specifies a reference to a rule.

The SrgsRuleRef type exposes the following members.

Constructors

 | Name | Description
Public method | SrgsRuleRef(Uri) | Initializes a new instance of the SrgsRuleRef class and specifies the location of the external grammar file to reference.
Public method | SrgsRuleRef(SrgsRule) | Initializes a new instance of the SrgsRuleRef class and specifies the rule to reference.
Public method | SrgsRuleRef(Uri, String) | Initializes a new instance of the SrgsRuleRef class, specifying the location of the external grammar file and the identifier of the rule to reference.
Public method | SrgsRuleRef(SrgsRule, String) | Initializes a new instance of the SrgsRuleRef class, specifying the rule to reference and a string that contains a semantic key.
Public method | SrgsRuleRef(Uri, String, String) | Initializes a new instance of the SrgsRuleRef class, specifying the location of the external grammar file, the identifier of the rule, and the string alias of the semantic dictionary.
Top

Properties

 | Name | Description
Public property | Params | Gets the initialization parameters for a SrgsRuleRef object.
Public property | SemanticKey | Gets an alias string for the semantic dictionary.
Public property | Uri | Gets the URI for the rule that this SrgsRuleRef object references.
Top

Methods

 | Name | Description
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | ToString | (Inherited from Object.)
Top

Fields

Name | Description
Dictation | Defines a rule that can match spoken input as defined by the dictation topic associated with this grammar.
Garbage | Defines a rule that can match any speech up to the next rule match, the next token, or until the end of spoken input.
MnemonicSpelling |
Null | Defines a rule that is automatically matched in the absence of any audio input.
Void | Defines a rule that can never be spoken. Inserting VOID into a sequence automatically makes that sequence unspeakable.
Top

See Also

Reference

SrgsRuleRef Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRuleRef Constructor

[image] [image]

SrgsRuleRef Constructor
SrgsRuleRef Class See Also Send Feedback

Initializes a new instance of the SrgsRuleRef class.

Overload List

 | Name | Description
Public method | SrgsRuleRef(Uri) | Initializes a new instance of the SrgsRuleRef class and specifies the location of the external grammar file to reference.
Public method | SrgsRuleRef(SrgsRule) | Initializes a new instance of the SrgsRuleRef class and specifies the rule to reference.
Public method | SrgsRuleRef(Uri, String) | Initializes a new instance of the SrgsRuleRef class, specifying the location of the external grammar file and the identifier of the rule to reference.
Public method | SrgsRuleRef(SrgsRule, String) | Initializes a new instance of the SrgsRuleRef class, specifying the rule to reference and a string that contains a semantic key.
Public method | SrgsRuleRef(Uri, String, String) | Initializes a new instance of the SrgsRuleRef class, specifying the location of the external grammar file, the identifier of the rule, and the string alias of the semantic dictionary.
Top

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRuleRef Constructor (Uri)

[image]

SrgsRuleRef Constructor (Uri)
SrgsRuleRef Class Example See Also Send Feedback

Initializes a new instance of the SrgsRuleRef class and specifies the location of the external grammar file to reference.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    uri As Uri _
)
Visual Basic (Usage)
Dim uri As Uri

Dim instance As New SrgsRuleRef(uri)
C#
public SrgsRuleRef(
    Uri uri
)

Parameters

uri
Type: System..::..Uri

The location of a grammar file outside the containing grammar.

Exceptions

Exception | Condition
ArgumentNullException | uri is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Remarks

This constructor creates a rule reference to an external grammar file. The URI may also include the identifier of a rule to reference, for example http://www.contoso.com/ExternalGrammar.grxml#targetRule. If the uri parameter does not specify a rule identifier, the rule reference points to the root rule of the target grammar. To create a rule reference to an SrgsRule object within the same grammar, use any of the following constructors:

  • SrgsRuleRef(SrgsRule)

  • SrgsRuleRef(SrgsRule, String)

Examples

The following example creates a grammar for an application that returns information about bus shuttle service. The first method, GrammarUrlForRoute, takes a string that specifies a route and appends it to a string specifying the location of a grammar. This specifies a particular rule in that grammar. The method returns a Uri for that rule.

The second method, CreateGrammarForRoute, creates an SrgsDocument element named grammar with a rule reference specified by the Uri passed to it by GrammarUrlForRoute. Note that the variable named _route is a member of an enclosing class.

Copy image Copy Code
private Uri GrammarUrlForRoute(string route)
{
  return new Uri("http://localhost/MyBus/MyBusLocations.grxml#LocationsForRoute" + route);
}

private SrgsDocument CreateGrammarForRoute()
{
  SrgsDocument grammar = new SrgsDocument();
  grammar.Mode = SrgsGrammarMode.Voice;
  SrgsRule rule = new SrgsRule("LocationsForRoute" + _route);
  SrgsRuleRef ruleref = new SrgsRuleRef(GrammarUrlForRoute(_route));

  SrgsSemanticInterpretationTag tag = new SrgsSemanticInterpretationTag ("$.Location = $$");

  rule.Elements.Add(ruleref);
  rule.Elements.Add(tag);
  grammar.Rules.Add(rule);
  grammar.Root = rule;
  return grammar;
}
Note Note

The variable named _route is undeclared and undefined in the preceding sample. It should be declared as a String and contain the route number for a particular bus route before the preceding sample is compiled and run.

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
SrgsRuleRef Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRuleRef Constructor (SrgsRule)

[image]

SrgsRuleRef Constructor (SrgsRule)
SrgsRuleRef Class Example See Also Send Feedback

Initializes a new instance of the SrgsRuleRef class and specifies the rule to reference.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    rule As SrgsRule _
)
Visual Basic (Usage)
Dim rule As SrgsRule

Dim instance As New SrgsRuleRef(rule)
C#
public SrgsRuleRef(
    SrgsRule rule
)

Parameters

rule
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsRule

The object to reference.

Exceptions

Exception | Condition
ArgumentNullException | rule is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Remarks

This constructor creates a rule reference to an SrgsRule object within the containing grammar. To create a rule reference to a rule element in an external grammar file, use any of the following constructors:

  • SrgsRuleRef(Uri)

  • SrgsRuleRef(Uri, String)

  • SrgsRuleRef(Uri, String, String)

Examples

The following example creates a grammar that recognizes the phrase "A nation that has won the World Cup is" followed by the name of a country that has won the World Cup. After creating the SrgsRule object winnerRule and giving it the string identifier WorldCupWinner, the example appends the string "A nation that has won the World Cup is" to the rule. Using SrgsOneOf objects, the example then builds a list of European countries and a list of South American countries, and adds each list to its respective rule, ruleEurope or ruleSAmerica. The example then creates rule references for ruleEurope and ruleSAmerica and adds them to the WorldCupWinner rule.

Copy image Copy Code
public void WorldSoccerWinners ()
{

  // Create an SrgsDocument, create a new rule
  // and set its scope to public.
  SrgsDocument document = new SrgsDocument();
  SrgsRule winnerRule = new SrgsRule("WorldCupWinner");
  winnerRule.Scope = SrgsRuleScope.Public;

  // Add the introduction.
  winnerRule.Elements.Add(new SrgsItem("A nation that has won the world cup is: "));

  // Create the rule for the European nations.
  SrgsOneOf oneOfEurope = new SrgsOneOf(new SrgsItem[] {new SrgsItem("England"),
    new SrgsItem("France"), new SrgsItem("Germany"), new SrgsItem("Italy")});
  SrgsRule ruleEurope = (new SrgsRule("EuropeanNations", new SrgsElement[] {oneOfEurope}));

  // Create the rule for the South American nations.
  SrgsOneOf oneOfSAmerica = new SrgsOneOf(new SrgsItem[] {new SrgsItem("Argentina"),
    new SrgsItem("Brazil"), new SrgsItem("Uruguay")});
  SrgsRule ruleSAmerica = (new SrgsRule("SouthAmericanNations", new SrgsElement[] {oneOfSAmerica}));

  // Add references to winnerRule for ruleEurope and ruleSAmerica.
  winnerRule.Elements.Add(new SrgsOneOf(new SrgsItem[] {(new SrgsItem
    (new SrgsRuleRef(ruleEurope))), new SrgsItem(new SrgsRuleRef(ruleSAmerica))}));

  // Add all the rules to the document and make winnerRule
  // the root rule of the document.
  document.Rules.Add(new SrgsRule[] {winnerRule, ruleEurope, ruleSAmerica});
  document.Root = winnerRule;
}

The created grammar has the following form.

Copy image Copy Code
<grammar version="1.0" xml:lang="en-US" xmlns="http://www.w3.org/2001/06/grammar" root="WorldCupWinner">
    <rule id="WorldCupWinner" scope="public">
        <item> A nation that has won the world cup is </item>
        <one-of>
            <item>
                <ruleref uri="#EuropeanNations" />
            </item>
            <item>
                <ruleref uri="#SouthAmericanNations" />
            </item>
        </one-of>
    </rule>
    <rule id="EuropeanNations">
        <one-of>
            <item> England </item>
            <item> France </item>
            <item> Germany </item>
            <item> Italy </item>
        </one-of>
    </rule>
    <rule id="SouthAmericanNations">
        <one-of>
            <item> Argentina </item>
            <item> Brazil </item>
            <item> Uruguay </item>
        </one-of>
    </rule>
</grammar>

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
SrgsRuleRef Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRuleRef Constructor (Uri, String)

[image]

SrgsRuleRef Constructor (Uri, String)
SrgsRuleRef Class See Also Send Feedback

Initializes a new instance of the SrgsRuleRef class, specifying the location of the external grammar file and the identifier of the rule to reference.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    uri As Uri, _
    rule As String _
)
Visual Basic (Usage)
Dim uri As Uri
Dim rule As String

Dim instance As New SrgsRuleRef(uri, rule)
C#
public SrgsRuleRef(
    Uri uri,
    string rule
)

Parameters

uri
Type: System..::..Uri

The location of a grammar file outside the containing grammar.

rule
Type: System..::..String

The identifier of the rule to reference.

Exceptions

Exception | Condition
ArgumentNullException | uri is nullNothingnullptrunita null reference (Nothing in Visual Basic). rule is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException | rule is empty.

Remarks

This constructor creates a rule reference to an external grammar file. To create a rule reference to an SrgsRule object within the same grammar, use any of the following constructors:

  • SrgsRuleRef(SrgsRule)

  • SrgsRuleRef(SrgsRule, String)

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
SrgsRuleRef Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRuleRef Constructor (SrgsRule, String)

[image]

SrgsRuleRef Constructor (SrgsRule, String)
SrgsRuleRef Class See Also Send Feedback

Initializes a new instance of the SrgsRuleRef class, specifying the rule to reference and a string that contains a semantic key.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    rule As SrgsRule, _
    semanticKey As String _
)
Visual Basic (Usage)
Dim rule As SrgsRule
Dim semanticKey As String

Dim instance As New SrgsRuleRef(rule, semanticKey)
C#
public SrgsRuleRef(
    SrgsRule rule,
    string semanticKey
)

Parameters

rule
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsRule

The object to reference.

semanticKey
Type: System..::..String

The semantic key.

Remarks

This constructor creates a rule reference to an SrgsRule object within the containing grammar. To create a rule reference to a rule element in an external grammar file, use any of the following constructors:

  • SrgsRuleRef(Uri)

  • SrgsRuleRef(Uri, String)

  • SrgsRuleRef(Uri, String, String)

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
SrgsRuleRef Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRuleRef Constructor (Uri, String, String)

[image]

SrgsRuleRef Constructor (Uri, String, String)
SrgsRuleRef Class See Also Send Feedback

Initializes a new instance of the SrgsRuleRef class, specifying the location of the external grammar file, the identifier of the rule, and the string alias of the semantic dictionary.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    uri As Uri, _
    rule As String, _
    semanticKey As String _
)
Visual Basic (Usage)
Dim uri As Uri
Dim rule As String
Dim semanticKey As String

Dim instance As New SrgsRuleRef(uri, rule, _
    semanticKey)
C#
public SrgsRuleRef(
    Uri uri,
    string rule,
    string semanticKey
)

Parameters

uri
Type: System..::..Uri

The location of a grammar file outside the containing grammar.

rule
Type: System..::..String

The identifier of the rule to reference.

semanticKey
Type: System..::..String

An alias string for the semantic dictionary.

Exceptions

Exception | Condition
ArgumentNullException | uri is nullNothingnullptrunita null reference (Nothing in Visual Basic). semanticKey is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException | semanticKey is empty.

Remarks

This constructor creates a rule reference to an external grammar file. To create a rule reference to an SrgsRule object within the same grammar, use any of the following constructors:

  • SrgsRuleRef(SrgsRule)

  • SrgsRuleRef(SrgsRule, String)

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
SrgsRuleRef Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Create Grammars Using SrgsGrammar (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRuleRef Fields

[image] [image]

SrgsRuleRef Fields
SrgsRuleRef Class See Also Send Feedback

The SrgsRuleRef type exposes the following members.

Fields

Name | Description
Dictation | Defines a rule that can match spoken input as defined by the dictation topic associated with this grammar.
Garbage | Defines a rule that can match any speech up to the next rule match, the next token, or until the end of spoken input.
MnemonicSpelling |
Null | Defines a rule that is automatically matched in the absence of any audio input.
Void | Defines a rule that can never be spoken. Inserting VOID into a sequence automatically makes that sequence unspeakable.
Top

See Also

Reference

SrgsRuleRef Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Dictation Field

[image]

SrgsRuleRef..::..Dictation Field
SrgsRuleRef Class See Also Send Feedback

Defines a rule that can match spoken input as defined by the dictation topic associated with this grammar.

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

Syntax

Visual Basic (Declaration)
Public Shared ReadOnly Dictation As SrgsRuleRef
Visual Basic (Usage)
Dim value As SrgsRuleRef

value = SrgsRuleRef.Dictation
C#
public static readonly SrgsRuleRef Dictation

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Garbage Field

[image]

SrgsRuleRef..::..Garbage Field
SrgsRuleRef Class See Also Send Feedback

Defines a rule that can match any speech up to the next rule match, the next token, or until the end of spoken input.

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

Syntax

Visual Basic (Declaration)
Public Shared ReadOnly Garbage As SrgsRuleRef
Visual Basic (Usage)
Dim value As SrgsRuleRef

value = SrgsRuleRef.Garbage
C#
public static readonly SrgsRuleRef Garbage

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MnemonicSpelling Field

[image]

SrgsRuleRef..::..MnemonicSpelling Field
SrgsRuleRef Class See Also Send Feedback

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

Syntax

Visual Basic (Declaration)
Public Shared ReadOnly MnemonicSpelling As SrgsRuleRef
Visual Basic (Usage)
Dim value As SrgsRuleRef

value = SrgsRuleRef.MnemonicSpelling
C#
public static readonly SrgsRuleRef MnemonicSpelling

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Null Field

[image]

SrgsRuleRef..::..Null Field
SrgsRuleRef Class See Also Send Feedback

Defines a rule that is automatically matched in the absence of any audio input.

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

Syntax

Visual Basic (Declaration)
Public Shared ReadOnly Null As SrgsRuleRef
Visual Basic (Usage)
Dim value As SrgsRuleRef

value = SrgsRuleRef.Null
C#
public static readonly SrgsRuleRef Null

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Void Field

[image]

SrgsRuleRef..::..Void Field
SrgsRuleRef Class See Also Send Feedback

Defines a rule that can never be spoken. Inserting VOID into a sequence automatically makes that sequence unspeakable.

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

Syntax

Visual Basic (Declaration)
Public Shared ReadOnly Void As SrgsRuleRef
Visual Basic (Usage)
Dim value As SrgsRuleRef

value = SrgsRuleRef.Void
C#
public static readonly SrgsRuleRef Void

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRuleRef Methods

[image] [image]

SrgsRuleRef Methods
SrgsRuleRef Class See Also Send Feedback

The SrgsRuleRef type exposes the following members.

Methods

 | Name | Description
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsRuleRef Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MemberwiseClone Method

[image] [image]

SrgsRuleRef..::..MemberwiseClone Method
SrgsRuleRef Class See Also Send Feedback

Overload List

 | Name | Description
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Top

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRuleRef Properties

[image] [image]

SrgsRuleRef Properties
SrgsRuleRef Class See Also Send Feedback

The SrgsRuleRef type exposes the following members.

Properties

 | Name | Description
Public property | Params | Gets the initialization parameters for a SrgsRuleRef object.
Public property | SemanticKey | Gets an alias string for the semantic dictionary.
Public property | Uri | Gets the URI for the rule that this SrgsRuleRef object references.
Top

See Also

Reference

SrgsRuleRef Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Params Property

[image]

SrgsRuleRef..::..Params Property
SrgsRuleRef Class See Also Send Feedback

Gets the initialization parameters for a SrgsRuleRef object.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Params As String
    Get
Visual Basic (Usage)
Dim instance As SrgsRuleRef
Dim value As String

value = instance.Params
C#
public string Params { get; }

Property Value

Type: System..::..String

The initialization parameters for a SrgsRuleRef object.

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SemanticKey Property

[image]

SrgsRuleRef..::..SemanticKey Property
SrgsRuleRef Class See Also Send Feedback

Gets an alias string for the semantic dictionary.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property SemanticKey As String
    Get
Visual Basic (Usage)
Dim instance As SrgsRuleRef
Dim value As String

value = instance.SemanticKey
C#
public string SemanticKey { get; }

Property Value

Type: System..::..String

An alias string for the semantic dictionary.

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Uri Property

[image]

SrgsRuleRef..::..Uri Property
SrgsRuleRef Class See Also Send Feedback

Gets the URI for the rule that this SrgsRuleRef object references.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Uri As Uri
    Get
Visual Basic (Usage)
Dim instance As SrgsRuleRef
Dim value As Uri

value = instance.Uri
C#
public Uri Uri { get; }

Property Value

Type: System..::..Uri

The location of the rule to reference.

See Also

Reference

SrgsRuleRef Class
SrgsRuleRef Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRulesCollection Class

[image]

SrgsRulesCollection Class
Members See Also Send Feedback

Represents a collection of SrgsRule objects.

Inheritance Hierarchy

System..::..Object
System.Collections.ObjectModel..::..Collection <(Of <(<' SrgsRule >)>)>
System.Collections.ObjectModel..::..KeyedCollection <(Of <(<' String, SrgsRule >)>)>
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsRulesCollection

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class SrgsRulesCollection _
    Inherits KeyedCollection(Of String, SrgsRule)
Visual Basic (Usage)
Dim instance As SrgsRulesCollection
C#
[SerializableAttribute]
public sealed class SrgsRulesCollection : KeyedCollection<string, SrgsRule>

Remarks

After you define the content for an SrgsRule object, you must add it to the Rules collection of an SrgsDocument instance using the Add(array<SrgsRule>[]()[][]) method. An SrgsRule cannot be used for recognition until it has been added to the Rules collection of an SrgsDocument instance.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SrgsRulesCollection Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRulesCollection Members

[image] [image]

SrgsRulesCollection Members
SrgsRulesCollection Class Constructors Methods Properties Explicit Interface Implementations See Also Send Feedback

Represents a collection of SrgsRule objects.

The SrgsRulesCollection type exposes the following members.

Constructors

 | Name | Description
Public method | SrgsRulesCollection | Initializes a new instance of the SrgsRulesCollection class.
Top

Properties

 | Name | Description
Public property | Comparer | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public property | Count | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Protected property | Dictionary | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public property | Item[([( TKey])]) | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public property | Item[([( Int32])]) | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Protected property | Items | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Top

Methods

 | Name | Description
Public method | Add(T) | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | Add(array<SrgsRule>[]()[][]) | Adds the contents of an array of SrgsRule objects to the SrgsRulesCollection object.
Protected method | ChangeItemKey | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public method | Clear | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Protected method | ClearItems | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public method | Contains(TKey) | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public method | Contains(T) | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | CopyTo | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetEnumerator | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | GetHashCode | (Inherited from Object.)
Protected method | GetKeyForItem | (Overrides KeyedCollection<(Of <(<'TKey, TItem>)>)>..::..GetKeyForItem(TItem).)
Public method | GetType | (Inherited from Object.)
Public method | IndexOf | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | Insert | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Protected method | InsertItem | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | Remove(TKey) | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public method | Remove(T) | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | RemoveAt | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Protected method | RemoveItem | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Protected method | SetItem | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public method | ToString | (Inherited from Object.)
Top

Explicit Interface Implementations

 | Name | Description
Explicit interface implemetation | IList..::..Add | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..Contains | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | ICollection..::..CopyTo | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IEnumerable..::..GetEnumerator | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..IndexOf | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..Insert | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..IsFixedSize | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | ICollection<(Of <<'(T>)>>)..::..IsReadOnly | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..IsReadOnly | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | ICollection..::..IsSynchronized | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..Item | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..Remove | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | ICollection..::..SyncRoot | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Top

See Also

Reference

SrgsRulesCollection Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRulesCollection Constructor

[image]

SrgsRulesCollection Constructor
SrgsRulesCollection Class See Also Send Feedback

Initializes a new instance of the SrgsRulesCollection class.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New SrgsRulesCollection()
C#
public SrgsRulesCollection()

See Also

Reference

SrgsRulesCollection Class
SrgsRulesCollection Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRulesCollection Methods

[image] [image]

SrgsRulesCollection Methods
SrgsRulesCollection Class See Also Send Feedback

The SrgsRulesCollection type exposes the following members.

Methods

 | Name | Description
Public method | Add(T) | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | Add(array<SrgsRule>[]()[][]) | Adds the contents of an array of SrgsRule objects to the SrgsRulesCollection object.
Protected method | ChangeItemKey | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public method | Clear | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Protected method | ClearItems | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public method | Contains(TKey) | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public method | Contains(T) | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | CopyTo | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetEnumerator | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | GetHashCode | (Inherited from Object.)
Protected method | GetKeyForItem | (Overrides KeyedCollection<(Of <(<'TKey, TItem>)>)>..::..GetKeyForItem(TItem).)
Public method | GetType | (Inherited from Object.)
Public method | IndexOf | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | Insert | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Protected method | InsertItem | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | Remove(TKey) | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public method | Remove(T) | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | RemoveAt | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Protected method | RemoveItem | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Protected method | SetItem | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public method | ToString | (Inherited from Object.)
Top

Explicit Interface Implementations

 | Name | Description
Explicit interface implemetation | IList..::..Add | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..Contains | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | ICollection..::..CopyTo | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IEnumerable..::..GetEnumerator | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..IndexOf | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..Insert | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..Remove | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Top

See Also

Reference

SrgsRulesCollection Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method

[image] [image]

SrgsRulesCollection..::..Add Method
SrgsRulesCollection Class See Also Send Feedback

Overload List

 | Name | Description
Public method | Add(T) | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Public method | Add(array<SrgsRule>[]()[][]) | Adds the contents of an array of SrgsRule objects to the SrgsRulesCollection object.
Top

See Also

Reference

SrgsRulesCollection Class
SrgsRulesCollection Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Add Method (SrgsRule[])

[image]

SrgsRulesCollection..::..Add Method (array<SrgsRule>[]()[][])
SrgsRulesCollection Class See Also Send Feedback

Adds the contents of an array of SrgsRule objects to the SrgsRulesCollection object.

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

Syntax

Visual Basic (Declaration)
Public Sub Add ( _
    ParamArray rules As SrgsRule() _
)
Visual Basic (Usage)
Dim instance As SrgsRulesCollection
Dim rules As SrgsRule()

instance.Add(rules)
C#
public void Add(
    params SrgsRule[] rules
)

Parameters

rules
Type: array< Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsRule >[]()[][]

The array of rule objects to add to the SrgsRulesCollection object.

Exceptions

Exception | Condition
ArgumentNullException | rules is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentException | Any SrgsRule object in the rules array is nullNothingnullptrunita null reference (Nothing in Visual Basic).

See Also

Reference

SrgsRulesCollection Class
SrgsRulesCollection Members
Add Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Contains Method

[image] [image]

SrgsRulesCollection..::..Contains Method
SrgsRulesCollection Class See Also Send Feedback

Overload List

 | Name | Description
Public method | Contains(TKey) | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public method | Contains(T) | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Top

See Also

Reference

SrgsRulesCollection Class
SrgsRulesCollection Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetKeyForItem Method

[image]

SrgsRulesCollection..::..GetKeyForItem Method
SrgsRulesCollection Class See Also Send Feedback

This member overrides KeyedCollection<(Of <(<'TKey, TItem>)>)>..::..GetKeyForItem(TItem).

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

Syntax

Visual Basic (Declaration)
Protected Overrides Function GetKeyForItem ( _
    rule As SrgsRule _
) As String
Visual Basic (Usage)
Dim rule As SrgsRule
Dim returnValue As String

returnValue = Me.GetKeyForItem(rule)
C#
protected override string GetKeyForItem(
    SrgsRule rule
)

Parameters

rule
Type: Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsRule

Return Value

Type: System..::..String

See Also

Reference

SrgsRulesCollection Class
SrgsRulesCollection Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Remove Method

[image] [image]

SrgsRulesCollection..::..Remove Method
SrgsRulesCollection Class See Also Send Feedback

Overload List

 | Name | Description
Public method | Remove(TKey) | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public method | Remove(T) | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Top

See Also

Reference

SrgsRulesCollection Class
SrgsRulesCollection Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRulesCollection Properties

[image] [image]

SrgsRulesCollection Properties
SrgsRulesCollection Class See Also Send Feedback

The SrgsRulesCollection type exposes the following members.

Properties

 | Name | Description
Public property | Comparer | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public property | Count | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Protected property | Dictionary | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public property | Item[([( TKey])]) | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public property | Item[([( Int32])]) | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Protected property | Items | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Top

Explicit Interface Implementations

 | Name | Description
Explicit interface implemetation | IList..::..IsFixedSize | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | ICollection<(Of <<'(T>)>>)..::..IsReadOnly | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..IsReadOnly | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | ICollection..::..IsSynchronized | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | IList..::..Item | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Explicit interface implemetation | ICollection..::..SyncRoot | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Top

See Also

Reference

SrgsRulesCollection Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Item Property

[image] [image]

SrgsRulesCollection..::..Item Property
SrgsRulesCollection Class See Also Send Feedback

Overload List

 | Name | Description
Public property | Item[([( TKey])]) | (Inherited from KeyedCollection <(Of <(<' String, SrgsRule >)>)>.)
Public property | Item[([( Int32])]) | (Inherited from Collection <(Of <(<' SrgsRule >)>)>.)
Top

See Also

Reference

SrgsRulesCollection Class
SrgsRulesCollection Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsRuleScope Enumeration

[image]

SrgsRuleScope Enumeration
See Also Send Feedback

Enumerates values for the scope of a SrgsRule object.

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

Syntax

Visual Basic (Declaration)
Public Enumeration SrgsRuleScope
Visual Basic (Usage)
Dim instance As SrgsRuleScope
C#
public enum SrgsRuleScope

Members

Member name | Description
Public | The rule can be the target of a rule reference from an external grammar, which can use the rule to perform recognition. A public rule can always be activated for recognition.
Private | The rule cannot be the target of a rule reference from an external grammar unless it is the root rule of its containing grammar.

See Also

Reference

Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsSemanticInterpretationTag Class

[image]

SrgsSemanticInterpretationTag Class
Members Example See Also Send Feedback

Represents a tag that contains ECMAScript that is run when the rule is matched.

Inheritance Hierarchy

System..::..Object
System..::..MarshalByRefObject
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsElement
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsSemanticInterpretationTag

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class SrgsSemanticInterpretationTag _
    Inherits SrgsElement
Visual Basic (Usage)
Dim instance As SrgsSemanticInterpretationTag
C#
[SerializableAttribute]
public sealed class SrgsSemanticInterpretationTag : SrgsElement

Remarks

The default semantic format for the Microsoft Speech Platform SDK 11 is semantics-ms/1.0. You must specify the script for SrgsSemanticInterpretationTag objects using this format. In the syntax of semantics-ms/1.0:

  • The Rule Variable of a rule is identified by "$".

  • The Rule Variable of a rule that is outside of the containing rule is identified by "$rulename", where rulename is the name of the referenced rule.

For more information see Support for Semantic Markup.

Examples

The following example creates a grammar for choosing the cities for a flight. The example uses SrgsSemanticInterpretationTag to assign a semantic value to each city, which is the code for the city's airport. The example also uses SrgsSemanticInterpretationTag to assign a separate semantic key for each of the two references made by the SrgsRuleRef object named cityRef to the SrgsRule object named cities. The semantic keys identify a recognized city as the departure city or the arrival city for the flight. The handler for the SpeechRecognized event uses the keys to retrieve the semantics of the recognition result.

In the code example, the symbol "$" refers to the Rule Variable of the containing SrgsRule. The expression "$.LeavingFrom" refers to the property named LeavingFrom of the Rule Variable on the rule named bookFlight.

The expression "$flightCities" refers to the Rule Variable on the rule whose Id is flightCities, and which is the target of a rule reference. In the example, the expression "$.LeavingFrom=$flightCities;" assigns the value from the rule whose Id is flightCities to the property named LeavingFrom of the Rule Variable on the rule named bookFlight. See Semantic Results Content (Microsoft.Speech), Grammar Rule Name Referencing (Microsoft.Speech), and Grammar Rule Reference Referencing (Microsoft.Speech) for more information.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;
using Microsoft.Speech.Recognition.SrgsGrammar;

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 a rule for the origin cities, assign a semantic value to each city.
        SrgsRule cities = new SrgsRule("flightCities");
        SrgsItem chi = new SrgsItem("Chicago");
        chi.Add(new SrgsSemanticInterpretationTag("$ = \"ORD\";"));
        SrgsItem bos = new SrgsItem("Boston");
        bos.Add(new SrgsSemanticInterpretationTag("$ = \"BOS\";"));
        SrgsItem mia = new SrgsItem("Miami");
        mia.Add(new SrgsSemanticInterpretationTag("$ = \"MIA\";"));
        SrgsItem dal = new SrgsItem("Dallas");
        dal.Add(new SrgsSemanticInterpretationTag("$ = \"DFW\";"));

        SrgsOneOf airports = new SrgsOneOf(chi, bos, mia, dal);
        cities.Add(airports);
        cities.Scope = SrgsRuleScope.Private;

        // Create a rule reference to rule for cities.
        SrgsRuleRef cityRef = new SrgsRuleRef(cities);

        // Create the root rule for the grammar.
        SrgsRule bookFlight = new SrgsRule("flightBooker");
        bookFlight.Add(new SrgsItem("I want to fly from"));
        bookFlight.Add(cityRef);
        bookFlight.Add(new SrgsSemanticInterpretationTag("$.LeavingFrom=$flightCities;"));
        bookFlight.Add(new SrgsItem("to"));
        bookFlight.Add(cityRef);
        bookFlight.Add(new SrgsSemanticInterpretationTag("$.GoingTo=$flightCities;"));
        bookFlight.Scope = SrgsRuleScope.Public;

        // Initialize the SrgsDocument, set the root rule, add rules to the collection.
        SrgsDocument itinerary = new SrgsDocument(bookFlight);
        itinerary.Rules.Add(cities);

        // Create a Grammar object and load it to the recognizer.
        Grammar g = new Grammar(itinerary);
        g.Name = ("City Chooser");
        recognizer.LoadGrammarAsync(g);

        // Configure recognizer input.
        recognizer.SetInputToDefaultAudioDevice();

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

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

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

    // Write to the console the text and the semantics from the recognition result.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine("Speech recognized: " + e.Result.Text);
      Console.WriteLine();
      Console.WriteLine("Semantic results:");
      Console.WriteLine("  The departure city is: " + e.Result.Semantics["LeavingFrom"].Value);
      Console.WriteLine("  The arrival city is: " + e.Result.Semantics["GoingTo"].Value);
    }
  }
}

The following is the XML form of the grammar generated by the code in the example above.

XML Copy image Copy Code
<?xml version="1.0" encoding="utf-8"?>
<grammar xml:lang="en-US" root="flightBooker" tag-format="semantics-ms/1.0"
version="1.0" xmlns="http://www.w3.org/2001/06/grammar">

  <rule id="flightBooker" scope="public">
    <item> I want to fly from </item>
    <ruleref uri="#flightCities" />
    <tag> $.LeavingFrom=$flightCities; </tag>
    <item> to </item>
    <ruleref uri="#flightCities" />
    <tag> $.GoingTo=$flightCities; </tag>
  </rule>

  <rule id="flightCities" scope="private">
    <one-of>
      <item> Chicago <tag> $="ORD"; </tag></item>
      <item> Boston <tag> $="BOS"; </tag></item>
      <item> Miami <tag> $="MIA"; </tag></item>
      <item> Dallas <tag> $="DFW"; </tag></item>
    </one-of>
  </rule>

</grammar>

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SrgsSemanticInterpretationTag Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsSemanticInterpretationTag Members

[image] [image]

SrgsSemanticInterpretationTag Members
SrgsSemanticInterpretationTag Class Constructors Methods Properties See Also Send Feedback

Represents a tag that contains ECMAScript that is run when the rule is matched.

The SrgsSemanticInterpretationTag type exposes the following members.

Constructors

 | Name | Description
Public method | SrgsSemanticInterpretationTag()()()() | Creates an instance of the SrgsSemanticInterpretationTag class.
Public method | SrgsSemanticInterpretationTag(String) | Creates an instance of the SrgsSemanticInterpretationTag class, specifying the script contents of the tag.
Top

Properties

 | Name | Description
Public property | Script | Gets or sets the ECMAScript for the tag.
Top

Methods

 | Name | Description
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsSemanticInterpretationTag Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsSemanticInterpretationTag Constructor

[image] [image]

SrgsSemanticInterpretationTag Constructor
SrgsSemanticInterpretationTag Class See Also Send Feedback

Creates an instance of the SrgsSemanticInterpretationTag class.

Overload List

 | Name | Description
Public method | SrgsSemanticInterpretationTag()()()() | Creates an instance of the SrgsSemanticInterpretationTag class.
Public method | SrgsSemanticInterpretationTag(String) | Creates an instance of the SrgsSemanticInterpretationTag class, specifying the script contents of the tag.
Top

See Also

Reference

SrgsSemanticInterpretationTag Class
SrgsSemanticInterpretationTag Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsSemanticInterpretationTag Constructor

[image]

SrgsSemanticInterpretationTag Constructor
SrgsSemanticInterpretationTag Class See Also Send Feedback

Creates an instance of the SrgsSemanticInterpretationTag class.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New SrgsSemanticInterpretationTag()
C#
public SrgsSemanticInterpretationTag()

Remarks

This constructor creates a semantic interpretation tag whose Script property contains an empty string.

See Also

Reference

SrgsSemanticInterpretationTag Class
SrgsSemanticInterpretationTag Members
SrgsSemanticInterpretationTag Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsSemanticInterpretationTag Constructor (String)

[image]

SrgsSemanticInterpretationTag Constructor (String)
SrgsSemanticInterpretationTag Class See Also Send Feedback

Creates an instance of the SrgsSemanticInterpretationTag class, specifying the script contents of the tag.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    script As String _
)
Visual Basic (Usage)
Dim script As String

Dim instance As New SrgsSemanticInterpretationTag(script)
C#
public SrgsSemanticInterpretationTag(
    string script
)

Parameters

script
Type: System..::..String

A string that contains the ECMAScript for the tag.

Exceptions

Exception | Condition
ArgumentNullException | script is nullNothingnullptrunita null reference (Nothing in Visual Basic).

Remarks

This constructor creates a semantic interpretation tag whose Script property is set to the value in script.

See Also

Reference

SrgsSemanticInterpretationTag Class
SrgsSemanticInterpretationTag Members
SrgsSemanticInterpretationTag Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsSemanticInterpretationTag Methods

[image] [image]

SrgsSemanticInterpretationTag Methods
SrgsSemanticInterpretationTag Class See Also Send Feedback

The SrgsSemanticInterpretationTag type exposes the following members.

Methods

 | Name | Description
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsSemanticInterpretationTag Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MemberwiseClone Method

[image] [image]

SrgsSemanticInterpretationTag..::..MemberwiseClone Method
SrgsSemanticInterpretationTag Class See Also Send Feedback

Overload List

 | Name | Description
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Top

See Also

Reference

SrgsSemanticInterpretationTag Class
SrgsSemanticInterpretationTag Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsSemanticInterpretationTag Properties

[image] [image]

SrgsSemanticInterpretationTag Properties
SrgsSemanticInterpretationTag Class See Also Send Feedback

The SrgsSemanticInterpretationTag type exposes the following members.

Properties

 | Name | Description
Public property | Script | Gets or sets the ECMAScript for the tag.
Top

See Also

Reference

SrgsSemanticInterpretationTag Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Script Property

[image]

SrgsSemanticInterpretationTag..::..Script Property
SrgsSemanticInterpretationTag Class See Also Send Feedback

Gets or sets the ECMAScript for the tag.

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

Syntax

Visual Basic (Declaration)
Public Property Script As String
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsSemanticInterpretationTag
Dim value As String

value = instance.Script

instance.Script = value
C#
public string Script { get; set; }

Property Value

Type: System..::..String

A string that contains the semantic interpretation script for the tag.

Exceptions

Exception | Condition
ArgumentNullException | An attempt is made to set Script to nullNothingnullptrunita null reference (Nothing in Visual Basic).

See Also

Reference

SrgsSemanticInterpretationTag Class
SrgsSemanticInterpretationTag Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsText Class

[image]

SrgsText Class
Members Example See Also Send Feedback

Represents the textual content of grammar elements defined by the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0.

Inheritance Hierarchy

System..::..Object
System..::..MarshalByRefObject
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsElement
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsText

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class SrgsText _
    Inherits SrgsElement
Visual Basic (Usage)
Dim instance As SrgsText
C#
[SerializableAttribute]
public sealed class SrgsText : SrgsElement

Remarks

The SrgsText class represents the text found within a set of SRGS element tags. When an SrgsItem object is constructed with a String parameter, a SrgsText object is created with its Text property initialized to the value of that parameter. The Text object is then added to the Elements collection on the SrgsItem object.

Examples

The following C# code example demonstrates how to use the SrgsText class to modify the textual contents of SrgsItem objects. The example changes the initial text values of the SrgsItem objects (Large, Larger, and Largest) to Small, Medium, and Large, respectively.

C# Copy image Copy Code
// Create SrgsItem objects and specify their text.
SrgsItem smallItem = new SrgsItem("Large");
SrgsItem mediumItem = new SrgsItem("Larger");
SrgsItem largeItem = new SrgsItem("Largest");

SrgsText textOfItem = null;

//  Change the text of smallItem.
if (smallItem.Elements[0] is SrgsText)
{
  textOfItem = smallItem.Elements[0] as SrgsText;
  textOfItem.Text = "Small";
}

//  Change the text of mediumItem.
if (mediumItem.Elements[0] is SrgsText)
{
  textOfItem = mediumItem.Elements[0] as SrgsText;
  textOfItem.Text = "Medium";
}

// Change the text of largeItem.
if (largeItem.Elements[0] is SrgsText)
{
  textOfItem = largeItem.Elements[0] as SrgsText;
  textOfItem.Text = "Large";
}

// Create an SrgsOneOf object and add smallItem, mediumItem,
// and largeItem as alternatives.
SrgsOneOf itemSize = new SrgsOneOf(new SrgsItem[]
  { smallItem, mediumItem, largeItem });

// Create a new SrgsRule from the SrgsOneOf object, and specifiy its identifier.
SrgsRule size = new SrgsRule("Sizes", itemSize);

// Create an SrgsDocument object.
// Add the SrgsRule object to the collection of rules and make it the root rule.
SrgsDocument document = new SrgsDocument();
document.Rules.Add(size);
document.Root = size;

// Write the SrgsDocument to an XML grammar file.
string srgsDocumentFile = Path.Combine(Path.GetTempPath(), "srgsDocumentFile.xml");
XmlWriter writer = XmlWriter.Create(srgsDocumentFile);
document.WriteSrgs(writer);
writer.Close();

The following shows how the modified text of the SrgsItem objects would appear as item elements in the output XML grammar file.

XML Copy image Copy Code
<!-- SRGS XML Fragment -->
<one-of>
  <item>Small</item>
  <item>Medium</item>
  <item>Large</item>
</one-of>

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SrgsText Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
SrgsItem
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsText Members

[image] [image]

SrgsText Members
SrgsText Class Constructors Methods Properties See Also Send Feedback

Represents the textual content of grammar elements defined by the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0.

The SrgsText type exposes the following members.

Constructors

 | Name | Description
Public method | SrgsText()()()() | Initializes a new instance of the SrgsText class.
Public method | SrgsText(String) | Initializes a new instance of the SrgsText class, specifying the text of the instance.
Top

Properties

 | Name | Description
Public property | Text | Gets or sets the text contained within the SrgsText class instance.
Top

Methods

 | Name | Description
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsText Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsText Constructor

[image] [image]

SrgsText Constructor
SrgsText Class See Also Send Feedback

Initializes a new instance of the SrgsText class.

Overload List

 | Name | Description
Public method | SrgsText()()()() | Initializes a new instance of the SrgsText class.
Public method | SrgsText(String) | Initializes a new instance of the SrgsText class, specifying the text of the instance.
Top

Remarks

There are two constructors for the SrgsText class.

See Also

Reference

SrgsText Class
SrgsText Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsText Constructor

[image]

SrgsText Constructor
SrgsText Class See Also Send Feedback

Initializes a new instance of the SrgsText class.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New SrgsText()
C#
public SrgsText()

Remarks

This constructor is the default constructor for the SrgsText class.

See Also

Reference

SrgsText Class
SrgsText Members
SrgsText Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsText Constructor (String)

[image]

SrgsText Constructor (String)
SrgsText Class See Also Send Feedback

Initializes a new instance of the SrgsText class, specifying the text of the instance.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    text As String _
)
Visual Basic (Usage)
Dim text As String

Dim instance As New SrgsText(text)
C#
public SrgsText(
    string text
)

Parameters

text
Type: System..::..String

The value used to set the Text()()()() property on the SrgsText instance.

Exceptions

Exception | Condition
ArgumentNullException | text is nullNothingnullptrunita null reference (Nothing in Visual Basic).

See Also

Reference

SrgsText Class
SrgsText Members
SrgsText Overload
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsText Methods

[image] [image]

SrgsText Methods
SrgsText Class See Also Send Feedback

The SrgsText type exposes the following members.

Methods

 | Name | Description
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsText Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MemberwiseClone Method

[image] [image]

SrgsText..::..MemberwiseClone Method
SrgsText Class See Also Send Feedback

Overload List

 | Name | Description
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Top

See Also

Reference

SrgsText Class
SrgsText Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsText Properties

[image] [image]

SrgsText Properties
SrgsText Class See Also Send Feedback

The SrgsText type exposes the following members.

Properties

 | Name | Description
Public property | Text | Gets or sets the text contained within the SrgsText class instance.
Top

See Also

Reference

SrgsText Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Text Property

[image]

SrgsText..::..Text Property
SrgsText Class See Also Send Feedback

Gets or sets the text contained within the SrgsText class instance.

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

Syntax

Visual Basic (Declaration)
Public Property Text As String
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsText
Dim value As String

value = instance.Text

instance.Text = value
C#
public string Text { get; set; }

Property Value

Type: System..::..String

The text contained within the SrgsText instance.

Exceptions

Exception | Condition
ArgumentNullException | An attempt is made to set Text to nullNothingnullptrunita null reference (Nothing in Visual Basic).

See Also

Reference

SrgsText Class
SrgsText Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsToken Class

[image]

SrgsToken Class
Members See Also Send Feedback

Represents a word or short phrase that can be recognized.

Inheritance Hierarchy

System..::..Object
System..::..MarshalByRefObject
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsElement
Microsoft.Speech.Recognition.SrgsGrammar..::..SrgsToken

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class SrgsToken _
    Inherits SrgsElement
Visual Basic (Usage)
Dim instance As SrgsToken
C#
[SerializableAttribute]
public sealed class SrgsToken : SrgsElement

Remarks

Using the members of the SrgsToken class, you can specify three forms of a word: the Display form, the Text form, and a custom Pronunciation for the word.

If multiple words are stored in a single SrgsToken object, each is treated as a different token internally and in the result.

This class represents the token element defined by the World Wide Web Consortium (W3C) Speech Recognition Grammar Specification (SRGS) Version 1.0.. For information about the SRGS token element and details about its support by the Microsoft Speech Platform SDK 11, see token Element (Microsoft.Speech).

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SrgsToken Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsToken Members

[image] [image]

SrgsToken Members
SrgsToken Class Constructors Methods Properties See Also Send Feedback

Represents a word or short phrase that can be recognized.

The SrgsToken type exposes the following members.

Constructors

 | Name | Description
Public method | SrgsToken | Initializes a new instance of the SrgsToken class and specifies the text to be recognized.
Top

Properties

 | Name | Description
Public property | Display | Gets or sets the display form of the text to be spoken.
Public property | Pronunciation | Gets or sets the string that defines the pronunciation for the token.
Public property | Text | Gets or sets the text contained within the SrgsToken class instance.
Top

Methods

 | Name | Description
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsToken Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsToken Constructor

[image]

SrgsToken Constructor
SrgsToken Class See Also Send Feedback

Initializes a new instance of the SrgsToken class and specifies the text to be recognized.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    text As String _
)
Visual Basic (Usage)
Dim text As String

Dim instance As New SrgsToken(text)
C#
public SrgsToken(
    string text
)

Parameters

text
Type: System..::..String

The text of the new SrgsToken class instance.

Exceptions

Exception | Condition
ArgumentNullException | text is nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException | text is empty.

Remarks

Creates an SrgsToken object whose Text property is set initially to the value of the text parameter.

See Also

Reference

SrgsToken Class
SrgsToken Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsToken Methods

[image] [image]

SrgsToken Methods
SrgsToken Class See Also Send Feedback

The SrgsToken type exposes the following members.

Methods

 | Name | Description
Public method | CreateObjRef | (Inherited from MarshalByRefObject.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetLifetimeService | (Inherited from MarshalByRefObject.)
Public method | GetType | (Inherited from Object.)
Public method | InitializeLifetimeService | (Inherited from MarshalByRefObject.)
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SrgsToken Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


MemberwiseClone Method

[image] [image]

SrgsToken..::..MemberwiseClone Method
SrgsToken Class See Also Send Feedback

Overload List

 | Name | Description
Protected method | MemberwiseClone()()()() | (Inherited from Object.)
Protected method | MemberwiseClone(Boolean) | (Inherited from MarshalByRefObject.)
Top

See Also

Reference

SrgsToken Class
SrgsToken Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SrgsToken Properties

[image] [image]

SrgsToken Properties
SrgsToken Class See Also Send Feedback

The SrgsToken type exposes the following members.

Properties

 | Name | Description
Public property | Display | Gets or sets the display form of the text to be spoken.
Public property | Pronunciation | Gets or sets the string that defines the pronunciation for the token.
Public property | Text | Gets or sets the text contained within the SrgsToken class instance.
Top

See Also

Reference

SrgsToken Class
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Display Property

[image]

SrgsToken..::..Display Property
SrgsToken Class See Also Send Feedback

Gets or sets the display form of the text to be spoken.

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

Syntax

Visual Basic (Declaration)
Public Property Display As String
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsToken
Dim value As String

value = instance.Display

instance.Display = value
C#
public string Display { get; set; }

Property Value

Type: System..::..String

A representation of the token as it should be displayed.

Exceptions

Exception | Condition
ArgumentNullException | An attempt is made to set Display to nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException | An attempt is made to assign an empty string to Display.

Remarks

Although they typically represent the same value, the Display form may be different than the Text form for a word or phrase in a SrgsToken. For example, the display form may be an acronym, such as "USA", while the text that will be spoken, and to which the Pronunciation applies, is "United States of America".

See Also

Reference

SrgsToken Class
SrgsToken Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Pronunciation Property

[image]

SrgsToken..::..Pronunciation Property
SrgsToken Class Example See Also Send Feedback

Gets or sets the string that defines the pronunciation for the token.

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

Syntax

Visual Basic (Declaration)
Public Property Pronunciation As String
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsToken
Dim value As String

value = instance.Pronunciation

instance.Pronunciation = value
C#
public string Pronunciation { get; set; }

Property Value

Type: System..::..String

Returns a string containing phones from the phonetic alphabet specified in PhoneticAlphabet.

Exceptions

Exception | Condition
ArgumentNullException | An attempt is made to set Pronunciation to nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException | An attempt is made to assign an empty string to Pronunciation.

Remarks

Phones are letters or symbols that describe the sounds of speech. Microsoft.Speech supports three phonetic alphabets for specifying custom pronunciations: the Universal Phone Set (UPS), the Speech API (SAPI) Phone set, and the International Phonetic Alphabet (IPA). The phones specified in Pronunciation must match the phonetic alphabet specified in PhoneticAlphabet. See Lexicons and Phonetic Alphabets (Microsoft.Speech) for more information.

The phones specified in Pronunciation indicate how the contents of Text should be pronounced for successful recognition. The speech recognition engine uses the pronunciation specified in Pronunciation to match speech input and returns the string contained by Text in the recognition result.

If the phones are not space-delimited or the specified string contains an unrecognized phone, the recognition engine does not recognize the specified pronunciation as a valid pronunciation of the word contained by Text.

Pronunciations specified in Pronunciation take precedence over pronunciations specified in lexicons associated with a grammar or a recognition engine. Also, the pronunciation in the Pronunciation property applies only to the single occurrence of the word or phrase contained by Text.

Examples

The grammar in the following example contains slang words and also has an uncommon word: "whatchamacallit". Adding a custom, inline pronunciation using the Pronunciation property of the SrgsToken class can improve the accuracy of recognition for the word "whatchamacallit" as well as for the entire phrase that contains it. The example uses phones from the Microsoft Universal Phone Set (UPS) to define the custom pronunciations.

Copy image Copy Code
using System;
using Microsoft.Speech.Recognition;
using Microsoft.Speech.Recognition.SrgsGrammar;

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

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

        // Build the SrgsOneOf objects with alternative choices for the slang phrase.
        SrgsOneOf gimme = new SrgsOneOf(
          new string[] { "give me", "gimme", "hand me", "ha'me" });
        SrgsOneOf the = new SrgsOneOf(new string[] { "the", "duh" });

        // Build the one-of element that contains the pronunciation.
        SrgsItem thing = new SrgsItem("thingamajig");
        SrgsItem whatcha = new SrgsItem();
        SrgsToken callit = new SrgsToken("whatchamacallit");
        callit.Pronunciation = "W AE T CH AE M AE K AA L IH T";
        whatcha.Add(callit);
        SrgsOneOf what = new SrgsOneOf(new SrgsItem[] {thing, whatcha});

        // Create the rule from the SrgsOneOf objects.
        SrgsRule slangRule = new SrgsRule("slang", gimme, the, what);

        // Build an SrgsDocument object from the rule and set the phonetic alphabet.
        SrgsDocument tokenPron = new SrgsDocument(slangRule);
        tokenPron.PhoneticAlphabet = SrgsPhoneticAlphabet.Ups;

        // Create a Grammar object from the SrgsDocument and load it to the recognizer.
        Grammar g_Slang = new Grammar(tokenPron);
        g_Slang.Name = ("Slang Pronunciation");
        recognizer.LoadGrammarAsync(g_Slang);

        // Configure recognizer input.
        recognizer.SetInputToDefaultAudioDevice();

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

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

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

    // Handle the SpeechRecognized event.
    static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      Console.WriteLine("Recognized phrase: " + e.Result.Text);
      Console.WriteLine("Confidence: " + e.Result.Confidence);
      Console.WriteLine("  Word summary: ");
      foreach (RecognizedWordUnit word in e.Result.Words)
      {
        Console.WriteLine(
          "    Lexical form ({1})" +
          " Pronunciation ({0})" +
          " Confidence ({2})",
          word.Pronunciation, word.LexicalForm, word.Confidence);
      }
    }
  }
}

See Also

Reference

SrgsToken Class
SrgsToken Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace

Other Resources

Lexicons and Phonetic Alphabets (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Text Property

[image]

SrgsToken..::..Text Property
SrgsToken Class See Also Send Feedback

Gets or sets the text contained within the SrgsToken class instance.

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

Syntax

Visual Basic (Declaration)
Public Property Text As String
    Get
    Set
Visual Basic (Usage)
Dim instance As SrgsToken
Dim value As String

value = instance.Text

instance.Text = value
C#
public string Text { get; set; }

Property Value

Type: System..::..String

The text contained within the SrgsToken class instance.

Exceptions

Exception | Condition
ArgumentNullException | An attempt is made to set Text to nullNothingnullptrunita null reference (Nothing in Visual Basic).
ArgumentOutOfRangeException | An attempt is made to assign an empty string to Text.
ArgumentException | An attempt is made to assign a string that contains a quotation mark (") to Text.

Remarks

Although they typically represent the same value, the Text form may be different than the Display form for a word or phrase in a SrgsToken. For example, the Display form may be an acronym, such as "USA", while the text that will be spoken, and to which the Pronunciation applies, is "United States of America".

The default value for the Text property is an empty string—"".

See Also

Reference

SrgsToken Class
SrgsToken Members
Microsoft.Speech.Recognition.SrgsGrammar Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Microsoft.Speech.Synthesis Namespace

[image]

Microsoft.Speech.Synthesis Namespace
Send Feedback

The Microsoft.Speech.Synthesis namespace contains classes for initializing and configuring a speech synthesis engine, for creating prompts, for generating speech, for responding to events, and for modifying voice characteristics. Speech synthesis is often referred to as text-to-speech or TTS.

Initialize and Configure

The SpeechSynthesizer class provides access to the functionality of a speech synthesis engine that is installed on the host computer. Installed speech synthesis engines are represented by a voice, for example Microsoft Helen for US English.

The Microsoft Speech Platform Runtime 11 and Microsoft Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech. See InstalledVoice.

To configure a SpeechSynthesizer instance to use one of the installed voices, call the SelectVoice(String) or SelectVoiceByHints()()()() methods. To get information about which voices are installed, use the GetInstalledVoices()()()() method.

You can route the output of the SpeechSynthesizer to a stream, a file, the default audio device, or to a null device by using one of the methods in the SpeechSynthesizer class whose name begins with "SetOutputTo".

Create Prompts

Use one the methods of the PromptBuilder class whose name begins with "Append" to build content for prompts from text, Speech Synthesis Markup Language (SSML), files containing text or SSML markup, or prerecorded audio files.

See Construct a Complex Prompt (Microsoft.Speech)in the Microsoft Speech Programming Guide for more information and examples.

Generate Speech

To generate speech from a string or from a Prompt or PromptBuilder object, use the Speak()()()() or the SpeakAsync()()()() methods. To generate speech from SSML markup, use the SpeakSsml(String) or the SpeakSsmlAsync(String) methods. See Speech Synthesis Markup Language Reference (Microsoft.Speech)for a guide to SSML markup.

You can guide the pronunciation of words by using the AppendTextWithHint()()()() or AppendTextWithPronunciation(String, String) methods, and by adding or removing lexicons for a SpeechSynthesizer instance using the AddLexicon(Uri, String) and RemoveLexicon(Uri) methods.

Respond to Events

The SpeechSynthesizer class includes events that inform a speech application that the SpeechSynthesizer encountered a specific feature in a prompt, as reported by the SpeakProgressEventArgs, BookmarkReachedEventArgs, and VoiceChangeEventArgs classes.

To get information about the beginning and end of the speaking of a prompt by the SpeechSynthesizer, use the SpeakStartedEventArgs and SpeakCompletedEventArgs classes.

See Use Speech Synthesis Events (Microsoft.Speech) in the Microsoft Speech Programming Guide for more information and examples.

Modify Voice Characteristics

The PromptStyle class and StartStyle(PromptStyle) and AppendText()()()() methods let you modify characteristics of a SpeechSynthesizer voice using Emphasis, Rate, and Volume parameters. To modify characteristics of a voice such as culture, age, and gender, use one of the StartVoice()()()() methods of the PromptBuilder class or the SelectVoiceByHints()()()() methods of the SpeechSynthesizer class.

See Control Voice Attributes (Microsoft.Speech) for more information.

Classes

 | Class | Description
Public class | BookmarkReachedEventArgs | Returns data from the BookmarkReached event.
Public class | FilePrompt | Represents a prompt created from a file.
Public class | InstalledVoice | Contains information about an installed speech synthesis voice.
Public class | Prompt | Represents information about what can be rendered, either text or an audio file, by the SpeechSynthesizer.
Public class | PromptBuilder | Creates an empty Prompt object and provides methods for adding content, selecting voices, controlling voice attributes, and controlling the pronunciation of spoken words.
Public class | PromptEventArgs | Represents the base class for EventArgs classes in the Microsoft.Speech.Synthesis namespace.
Public class | PromptStyle | Defines a style for speaking prompts that consists of settings for emphasis, rate, and volume.
Public class | ProprietaryEngineEventArgs | Returns data from an event raised by a proprietary speech synthesis engine.
Public class | SpeakCompletedEventArgs | Returns notification from the SpeakCompleted event.
Public class | SpeakProgressEventArgs | Returns data from the SpeakProgress event.
Public class | SpeakStartedEventArgs | Returns notification from the SpeakStarted event.
Public class | SpeechSynthesizer | Provides access to the functionality of an installed a speech synthesis engine.
Public class | StateChangedEventArgs | Returns data from the StateChanged event.
Public class | VoiceChangeEventArgs | Returns data from the VoiceChange event.
Public class | VoiceInfo | Represents an installed speech synthesis engine.

Enumerations

 | Enumeration | Description
Public enumeration | PromptBreak | Enumerates values for intervals of prosodic separation (breaks) between word boundaries.
Public enumeration | PromptEmphasis | Enumerates values for the levels of speaking emphasis in prompts.
Public enumeration | PromptRate | Enumerates values for the speaking rate of prompts.
Public enumeration | PromptVolume | Enumerates values for volume levels (loudness) in prompts.
Public enumeration | SayAs | Enumerates the content types for the speaking of elements such as times, dates, and currency.
Public enumeration | SynthesisMediaType | Enumerates the types of media files.
Public enumeration | SynthesisTextFormat | Enumerates the types of text formats that may be used to construct a Prompt object.
Public enumeration | SynthesizerState | Enumerates values for the state of the SpeechSynthesizer.
Public enumeration | VoiceAge | Defines the values for the age of a synthesized voice.
Public enumeration | VoiceGender | Defines the values for the gender of synthesized voices.
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


BookmarkReachedEventArgs Class

[image]

BookmarkReachedEventArgs Class
Members Example See Also Send Feedback

Returns data from the BookmarkReached event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
System.ComponentModel..::..AsyncCompletedEventArgs
Microsoft.Speech.Synthesis..::..PromptEventArgs
Microsoft.Speech.Synthesis..::..BookmarkReachedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class BookmarkReachedEventArgs _
    Inherits PromptEventArgs
Visual Basic (Usage)
Dim instance As BookmarkReachedEventArgs
C#
public class BookmarkReachedEventArgs : PromptEventArgs

Remarks

An instance of BookmarkReachedEventArgs is created when the SpeechSynthesizer object raises the BookmarkReached event. The SpeechSynthesizer raises the BookmarkReached event when it encounters a bookmark while processing any of the Speak()()()(), SpeakAsync()()()(), SpeakSsml(String), or SpeakSsmlAsync(String) methods. To obtain the name and location of the bookmark that triggered the event, access the Bookmark and the AudioPosition properties in the handler for the event.

Examples

The following example creates a prompt that includes two bookmarks and sends the output to a WAV file for playback. The handler for the BookmarkReached event writes the name of the bookmark and its position in the audio stream when the event was raised to the console.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\test\weather.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\test\weather.wav");

        // Build a prompt and append bookmarks.
        PromptBuilder builder = new PromptBuilder(
          new System.Globalization.CultureInfo("en-US"));
        builder.AppendText(
          "The weather forecast for today is partly cloudy with some sun breaks.");
        builder.AppendBookmark("Daytime forecast");
        builder.AppendText(
          "Tonight's weather will be cloudy with a 30% chance of showers.");
        builder.AppendBookmark("Nightime forecast");

        // Add a handler for the BookmarkReached event.
        synth.BookmarkReached +=
          new EventHandler<BookmarkReachedEventArgs>(synth_BookmarkReached);

        // Speak the prompt and play back the output file.
        synth.Speak(builder);
        m_SoundPlayer.Play();
      }

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

    // Write the name and position of the bookmark to the console.
    static void synth_BookmarkReached(object sender, BookmarkReachedEventArgs e)
    {
      Console.WriteLine("Bookmark ({0}) reached at: {1} ",
        e.Bookmark, e.AudioPosition);
    }
  }
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

BookmarkReachedEventArgs Members
Microsoft.Speech.Synthesis Namespace
AppendBookmark(String)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


BookmarkReachedEventArgs Members

[image] [image]

BookmarkReachedEventArgs Members
BookmarkReachedEventArgs Class Methods Properties See Also Send Feedback

Returns data from the BookmarkReached event.

The BookmarkReachedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioPosition | Gets the time offset at which the bookmark was reached.
Public property | Bookmark | Gets the name of the bookmark that was reached.
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Prompt | Gets the prompt associated with the event. (Inherited from PromptEventArgs.)
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

BookmarkReachedEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


BookmarkReachedEventArgs Methods

[image] [image]

BookmarkReachedEventArgs Methods
BookmarkReachedEventArgs Class See Also Send Feedback

The BookmarkReachedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

BookmarkReachedEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


BookmarkReachedEventArgs Properties

[image] [image]

BookmarkReachedEventArgs Properties
BookmarkReachedEventArgs Class See Also Send Feedback

The BookmarkReachedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioPosition | Gets the time offset at which the bookmark was reached.
Public property | Bookmark | Gets the name of the bookmark that was reached.
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Prompt | Gets the prompt associated with the event. (Inherited from PromptEventArgs.)
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

See Also

Reference

BookmarkReachedEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioPosition Property

[image]

BookmarkReachedEventArgs..::..AudioPosition Property
BookmarkReachedEventArgs Class See Also Send Feedback

Gets the time offset at which the bookmark was reached.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioPosition As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As BookmarkReachedEventArgs
Dim value As TimeSpan

value = instance.AudioPosition
C#
public TimeSpan AudioPosition { get; }

Property Value

Type: System..::..TimeSpan

Returns the location in the audio input stream of a synthesis engine when the event was raised.

See Also

Reference

BookmarkReachedEventArgs Class
BookmarkReachedEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Bookmark Property

[image]

BookmarkReachedEventArgs..::..Bookmark Property
BookmarkReachedEventArgs Class See Also Send Feedback

Gets the name of the bookmark that was reached.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Bookmark As String
    Get
Visual Basic (Usage)
Dim instance As BookmarkReachedEventArgs
Dim value As String

value = instance.Bookmark
C#
public string Bookmark { get; }

Property Value

Type: System..::..String

Returns a value for the name of the bookmark.

See Also

Reference

BookmarkReachedEventArgs Class
BookmarkReachedEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


FilePrompt Class

[image]

FilePrompt Class
Members See Also Send Feedback

Represents a prompt created from a file.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Synthesis..::..Prompt
Microsoft.Speech.Synthesis..::..FilePrompt

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

Syntax

Visual Basic (Declaration)
Public Class FilePrompt _
    Inherits Prompt
Visual Basic (Usage)
Dim instance As FilePrompt
C#
public class FilePrompt : Prompt

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

FilePrompt Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


FilePrompt Members

[image] [image]

FilePrompt Members
FilePrompt Class Constructors Methods Properties See Also Send Feedback

Represents a prompt created from a file.

The FilePrompt type exposes the following members.

Constructors

 | Name | Description
Public method | FilePrompt(String, SynthesisMediaType) | Creates a new instance of the FilePrompt class, specifying the path to the file and its media type.
Public method | FilePrompt(Uri, SynthesisMediaType) | Creates a new instance of the FilePrompt class, specifying the location of the file and its media type.
Top

Properties

 | Name | Description
Public property | IsCompleted | Gets whether the Prompt has finished playing. (Inherited from Prompt.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

FilePrompt Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


FilePrompt Constructor

[image] [image]

FilePrompt Constructor
FilePrompt Class See Also Send Feedback

Creates a new instance of the FilePrompt class.

Overload List

 | Name | Description
Public method | FilePrompt(String, SynthesisMediaType) | Creates a new instance of the FilePrompt class, specifying the path to the file and its media type.
Public method | FilePrompt(Uri, SynthesisMediaType) | Creates a new instance of the FilePrompt class, specifying the location of the file and its media type.
Top

See Also

Reference

FilePrompt Class
FilePrompt Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


FilePrompt Constructor (String, SynthesisMediaType)

[image]

FilePrompt Constructor (String, SynthesisMediaType)
FilePrompt Class See Also Send Feedback

Creates a new instance of the FilePrompt class, specifying the path to the file and its media type.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    path As String, _
    media As SynthesisMediaType _
)
Visual Basic (Usage)
Dim path As String
Dim media As SynthesisMediaType

Dim instance As New FilePrompt(path, media)
C#
public FilePrompt(
    string path,
    SynthesisMediaType media
)

Parameters

path
Type: System..::..String

The path of the file containing the prompt content.

media
Type: Microsoft.Speech.Synthesis..::..SynthesisMediaType

The media type of the file.

See Also

Reference

FilePrompt Class
FilePrompt Members
FilePrompt Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


FilePrompt Constructor (Uri, SynthesisMediaType)

[image]

FilePrompt Constructor (Uri, SynthesisMediaType)
FilePrompt Class See Also Send Feedback

Creates a new instance of the FilePrompt class, specifying the location of the file and its media type.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    promptFile As Uri, _
    media As SynthesisMediaType _
)
Visual Basic (Usage)
Dim promptFile As Uri
Dim media As SynthesisMediaType

Dim instance As New FilePrompt(promptFile, _
    media)
C#
public FilePrompt(
    Uri promptFile,
    SynthesisMediaType media
)

Parameters

promptFile
Type: System..::..Uri

The URI of the file containing the prompt content.

media
Type: Microsoft.Speech.Synthesis..::..SynthesisMediaType

The media type of the file.

See Also

Reference

FilePrompt Class
FilePrompt Members
FilePrompt Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


FilePrompt Methods

[image] [image]

FilePrompt Methods
FilePrompt Class See Also Send Feedback

The FilePrompt type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

FilePrompt Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


FilePrompt Properties

[image] [image]

FilePrompt Properties
FilePrompt Class See Also Send Feedback

The FilePrompt type exposes the following members.

Properties

 | Name | Description
Public property | IsCompleted | Gets whether the Prompt has finished playing. (Inherited from Prompt.)
Top

See Also

Reference

FilePrompt Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InstalledVoice Class

[image]

InstalledVoice Class
Members See Also Send Feedback

Contains information about an installed speech synthesis voice.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Synthesis..::..InstalledVoice

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

Syntax

Visual Basic (Declaration)
Public Class InstalledVoice
Visual Basic (Usage)
Dim instance As InstalledVoice
C#
public class InstalledVoice

Remarks

Use this class to get information about an installed voice, including its culture (language-country/region), name, gender, age, and whether it is enabled. A voice is a speech synthesis engine with specific characteristics, the most defining of which is the single language that it supports.

The Microsoft Speech Platform Runtime 11 and Microsoft Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech.

The language packs are different for each version of the Speech Platform Runtime. You must download the language pack version that matches the version of the Speech Platform Runtime that you have installed. The language packs for the Speech Platform SDK 11 are for server-based applications and are different than the languages that ship with Windows Vista or Windows 7. Use the following links to download the version of the server language packs that match your Speech Platform Runtime version:

  • Server Language Packs v11.0

  • Server Language Packs v10.2

  • Server Language Packs v10.1

  • Server Language Packs v10.0

See Language Support for a list of languages for which you can download language packs.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

InstalledVoice Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InstalledVoice Members

[image] [image]

InstalledVoice Members
InstalledVoice Class Methods Properties See Also Send Feedback

Contains information about an installed speech synthesis voice.

The InstalledVoice type exposes the following members.

Properties

 | Name | Description
Public property | Enabled | Gets or sets whether a voice can be used to generate speech.
Public property | VoiceInfo | Gets information about a voice, such as culture, name, gender, and age.
Top

Methods

 | Name | Description
Public method | Equals | Determines if a given object is an instance of InstalledVoice and equal to the current instance of InstalledVoice. (Overrides Object..::..Equals(Object).)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Overrides Object..::..GetHashCode()()()().)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

InstalledVoice Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InstalledVoice Methods

[image] [image]

InstalledVoice Methods
InstalledVoice Class See Also Send Feedback

The InstalledVoice type exposes the following members.

Methods

 | Name | Description
Public method | Equals | Determines if a given object is an instance of InstalledVoice and equal to the current instance of InstalledVoice. (Overrides Object..::..Equals(Object).)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Overrides Object..::..GetHashCode()()()().)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

InstalledVoice Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Equals Method

[image]

InstalledVoice..::..Equals Method
InstalledVoice Class See Also Send Feedback

Determines if a given object is an instance of InstalledVoice and equal to the current instance of InstalledVoice.

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

Syntax

Visual Basic (Declaration)
Public Overrides Function Equals ( _
    obj As Object _
) As Boolean
Visual Basic (Usage)
Dim instance As InstalledVoice
Dim obj As Object
Dim returnValue As Boolean

returnValue = instance.Equals(obj)
C#
public override bool Equals(
    Object obj
)

Parameters

obj
Type: System..::..Object

An object that can be cast to an instance of InstalledVoice.

Return Value

Type: System..::..Boolean

Returns true if the current instance of InstalledVoice and that obtained from the obj argument are equal, otherwise returns false.

Remarks

The method returns false if the Object provided by the obj argument cannot be cast to InstalledVoice.

See Also

Reference

InstalledVoice Class
InstalledVoice Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetHashCode Method

[image]

InstalledVoice..::..GetHashCode Method
InstalledVoice Class See Also Send Feedback

This member overrides Object..::..GetHashCode()()()().

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

Syntax

Visual Basic (Declaration)
Public Overrides Function GetHashCode As Integer
Visual Basic (Usage)
Dim instance As InstalledVoice
Dim returnValue As Integer

returnValue = instance.GetHashCode()
C#
public override int GetHashCode()

Return Value

Type: System..::..Int32

See Also

Reference

InstalledVoice Class
InstalledVoice Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InstalledVoice Properties

[image] [image]

InstalledVoice Properties
InstalledVoice Class See Also Send Feedback

The InstalledVoice type exposes the following members.

Properties

 | Name | Description
Public property | Enabled | Gets or sets whether a voice can be used to generate speech.
Public property | VoiceInfo | Gets information about a voice, such as culture, name, gender, and age.
Top

See Also

Reference

InstalledVoice Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Enabled Property

[image]

InstalledVoice..::..Enabled Property
InstalledVoice Class See Also Send Feedback

Gets or sets whether a voice can be used to generate speech.

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

Syntax

Visual Basic (Declaration)
Public Property Enabled As Boolean
    Get
    Set
Visual Basic (Usage)
Dim instance As InstalledVoice
Dim value As Boolean

value = instance.Enabled

instance.Enabled = value
C#
public bool Enabled { get; set; }

Property Value

Type: System..::..Boolean

Returns a bool that represents the enabled state of the voice.

Remarks

The value of the Enabled property is true by default. When an application calls GetInstalledVoices()()()(), the method verifies that each of the voices it finds in the registry meets certain minimum criteria. For any voice that fails verification, GetInstalledVoices()()()() sets its Enabled property to false. An application cannot select a voice whose Enabled property is false. Typically, applications will not set a voice's Enabled property.

See Also

Reference

InstalledVoice Class
InstalledVoice Members
Microsoft.Speech.Synthesis Namespace
SpeechSynthesizer..::..SelectVoice
SpeechSynthesizer..::..SelectVoiceByHints
PromptBuilder..::..StartVoice
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceInfo Property

[image]

InstalledVoice..::..VoiceInfo Property
InstalledVoice Class See Also Send Feedback

Gets information about a voice, such as culture, name, gender, and age.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property VoiceInfo As VoiceInfo
    Get
Visual Basic (Usage)
Dim instance As InstalledVoice
Dim value As VoiceInfo

value = instance.VoiceInfo
C#
public VoiceInfo VoiceInfo { get; }

Property Value

Type: Microsoft.Speech.Synthesis..::..VoiceInfo

The information about an installed voice.

See Also

Reference

InstalledVoice Class
InstalledVoice Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prompt Class

[image]

Prompt Class
Members See Also Send Feedback

Represents information about what can be rendered, either text or an audio file, by the SpeechSynthesizer.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Synthesis..::..Prompt
Microsoft.Speech.Synthesis..::..FilePrompt

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

Syntax

Visual Basic (Declaration)
Public Class Prompt
Visual Basic (Usage)
Dim instance As Prompt
C#
public class Prompt

Remarks

A Prompt object can contain plain text, text formatted with markup language, or audio files.

An empty Prompt object is created with each new instance of PromptBuilder. The PromptBuilder class provides methods for adding content, including text, SSML markup, bookmarks, and prerecorded audio files (such as .wav files), to the empty Prompt object that it contains. Typically, applications will use PromptBuilder, rather than a Prompt object, to create prompts and populate them with content.

To generate speech from the contents of a Prompt object, use the Speak(Prompt) method.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

Prompt Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prompt Members

[image] [image]

Prompt Members
Prompt Class Constructors Methods Properties See Also Send Feedback

Represents information about what can be rendered, either text or an audio file, by the SpeechSynthesizer.

The Prompt type exposes the following members.

Constructors

 | Name | Description
Public method | Prompt(String) | Creates a new instance of the Prompt class and specifies the text to be spoken.
Public method | Prompt(PromptBuilder) | Creates a new instance of the Prompt class from a PromptBuilder object.
Public method | Prompt(String, SynthesisTextFormat) | Creates a new instance of the Prompt class and specifies the text to be spoken and whether its format is plain text or markup language.
Top

Properties

 | Name | Description
Public property | IsCompleted | Gets whether the Prompt has finished playing.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

Prompt Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prompt Constructor

[image] [image]

Prompt Constructor
Prompt Class See Also Send Feedback

Creates a new instance of the Prompt class.

Overload List

 | Name | Description
Public method | Prompt(String) | Creates a new instance of the Prompt class and specifies the text to be spoken.
Public method | Prompt(PromptBuilder) | Creates a new instance of the Prompt class from a PromptBuilder object.
Public method | Prompt(String, SynthesisTextFormat) | Creates a new instance of the Prompt class and specifies the text to be spoken and whether its format is plain text or markup language.
Top

See Also

Reference

Prompt Class
Prompt Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prompt Constructor (String)

[image]

Prompt Constructor (String)
Prompt Class See Also Send Feedback

Creates a new instance of the Prompt class and specifies the text to be spoken.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    textToSpeak As String _
)
Visual Basic (Usage)
Dim textToSpeak As String

Dim instance As New Prompt(textToSpeak)
C#
public Prompt(
    string textToSpeak
)

Parameters

textToSpeak
Type: System..::..String

The text to be spoken.

See Also

Reference

Prompt Class
Prompt Members
Prompt Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prompt Constructor (PromptBuilder)

[image]

Prompt Constructor (PromptBuilder)
Prompt Class See Also Send Feedback

Creates a new instance of the Prompt class from a PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    promptBuilder As PromptBuilder _
)
Visual Basic (Usage)
Dim promptBuilder As PromptBuilder

Dim instance As New Prompt(promptBuilder)
C#
public Prompt(
    PromptBuilder promptBuilder
)

Parameters

promptBuilder
Type: Microsoft.Speech.Synthesis..::..PromptBuilder

The content to be spoken.

See Also

Reference

Prompt Class
Prompt Members
Prompt Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prompt Constructor (String, SynthesisTextFormat)

[image]

Prompt Constructor (String, SynthesisTextFormat)
Prompt Class See Also Send Feedback

Creates a new instance of the Prompt class and specifies the text to be spoken and whether its format is plain text or markup language.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    textToSpeak As String, _
    media As SynthesisTextFormat _
)
Visual Basic (Usage)
Dim textToSpeak As String
Dim media As SynthesisTextFormat

Dim instance As New Prompt(textToSpeak, _
    media)
C#
public Prompt(
    string textToSpeak,
    SynthesisTextFormat media
)

Parameters

textToSpeak
Type: System..::..String

The text to be spoken.

media
Type: Microsoft.Speech.Synthesis..::..SynthesisTextFormat

A value that specifies the format of the text.

See Also

Reference

Prompt Class
Prompt Members
Prompt Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prompt Methods

[image] [image]

Prompt Methods
Prompt Class See Also Send Feedback

The Prompt type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

Prompt Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prompt Properties

[image] [image]

Prompt Properties
Prompt Class See Also Send Feedback

The Prompt type exposes the following members.

Properties

 | Name | Description
Public property | IsCompleted | Gets whether the Prompt has finished playing.
Top

See Also

Reference

Prompt Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


IsCompleted Property

[image]

Prompt..::..IsCompleted Property
Prompt Class See Also Send Feedback

Gets whether the Prompt has finished playing.

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

Syntax

Visual Basic (Declaration)
Public Property IsCompleted As Boolean
    Get
    Friend Set
Visual Basic (Usage)
Dim instance As Prompt
Dim value As Boolean

value = instance.IsCompleted
C#
public bool IsCompleted { get; internal set; }

Property Value

Type: System..::..Boolean

Returns false if the prompt has completed; otherwise true.

See Also

Reference

Prompt Class
Prompt Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptBreak Enumeration

[image]

PromptBreak Enumeration
See Also Send Feedback

Enumerates values for intervals of prosodic separation (breaks) between word boundaries.

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

Syntax

Visual Basic (Declaration)
Public Enumeration PromptBreak
Visual Basic (Usage)
Dim instance As PromptBreak
C#
public enum PromptBreak

Members

Member name | Description
None | Indicates no break.
ExtraSmall | Indicates an extra small pause.
Small | Indicates a small pause.
Medium | Indicates a medium pause.
Large | Indicates a large pause.
ExtraLarge | Indicates an extra large pause.

Remarks

The values in the PromptBreak enumeration represent a range of separation intervals (pauses) between word boundaries. The speech synthesis engine determines the exact duration of the interval. When a break is requested, one of these values is passed to the text-to-speech (TTS) engine, which contains a mapping between these values and the corresponding millisecond break values.

The value None represents the absence of a pause between word boundaries and can be used to remove a break where one would normally occur. The remaining values are listed in order of increasing durations for breaks.

See Also

Reference

Microsoft.Speech.Synthesis Namespace
Prompt
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptBuilder Class

[image]

PromptBuilder Class
Members See Also Send Feedback

Creates an empty Prompt object and provides methods for adding content, selecting voices, controlling voice attributes, and controlling the pronunciation of spoken words.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Synthesis..::..PromptBuilder

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class PromptBuilder
Visual Basic (Usage)
Dim instance As PromptBuilder
C#
[SerializableAttribute]
public sealed class PromptBuilder

Remarks

With PromptBuilder, you can add a variety of content types to a prompt, including plain text, SSML markup (as a string or a file), recorded audio, or even another PromptBuilder object.

To append text to a PromptBuilder object and optionally control voice attributes such as emphasis, rate, and volume, use one of the AppendText()()()() methods. You can also control voice attributes as a group with the StartStyle(PromptStyle) and EndStyle()()()() methods.

You can append text and control what is spoken or how it is pronounced using the AppendTextWithHint()()()(), AppendTextWithAlias(String, String), AppendTextWithPronunciation(String, String), AppendSsml()()()(), or AppendSsmlMarkup(String) methods.

Change the currently selected speaking voice in the prompt using one of the overloaded StartVoice()()()() methods, naming a specific voice to use or specifying required voice characteristics, such as age and gender.

To generate speech from a PromptBuilder object, you can pass it as an argument to the Speak(PromptBuilder) method.

For more information, see Construct a Complex Prompt (Microsoft.Speech)

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptBuilder Members

[image] [image]

PromptBuilder Members
PromptBuilder Class Constructors Methods Properties See Also Send Feedback

Creates an empty Prompt object and provides methods for adding content, selecting voices, controlling voice attributes, and controlling the pronunciation of spoken words.

The PromptBuilder type exposes the following members.

Constructors

 | Name | Description
Public method | PromptBuilder()()()() | Creates a new instance of the PromptBuilder class.
Public method | PromptBuilder(CultureInfo) | Creates a new instance of the PromptBuilder class and specifies a culture.
Top

Properties

 | Name | Description
Public property | Culture | Gets or sets the culture information for the PromptBuilder object.
Public property | Id | Gets or sets a value that is the identifier for a PromptBuilder instance.
Public property | IsEmpty | Gets whether the PromptBuilder is empty.
Top

Methods

 | Name | Description
Public method | AddPromptDatabase |
Public method | AppendAudio(String) | Appends the specified audio file to the PromptBuilder.
Public method | AppendAudio(Uri) | Appends the audio file at the specified URI to the PromptBuilder.
Public method | AppendAudio(Uri, String) | Appends the specified audio file and alternate text to the PromptBuilder.
Public method | AppendBookmark | Appends a bookmark to the PromptBuilder object.
Public method | AppendBreak()()()() | Appends a break to the PromptBuilder object.
Public method | AppendBreak(TimeSpan) | Appends a break of the specified duration to the PromptBuilder object.
Public method | AppendBreak(PromptBreak) | Appends a break of the specified strength (duration) to the PromptBuilder object.
Public method | AppendPromptBuilder | Appends a PromptBuilder object to a PromptBuilder object.
Public method | AppendSsml | Appends the specified XML file containing SSML to the PromptBuilder object.
Public method | AppendSsmlMarkup | Appends the specified string containing SSML markup into the PromptBuilder object.
Public method | AppendText(String) | Specifies text to append to the PromptBuilder object.
Public method | AppendText(String, PromptEmphasis) | Appends text to the PromptBuilder object and specifies the degree of emphasis for the text.
Public method | AppendText(String, PromptRate) | Appends text to the PromptBuilder object and specifies the speaking rate for the text.
Public method | AppendText(String, PromptVolume) | Appends text to the PromptBuilder object and specifies a volume for the text to be spoken.
Public method | AppendText(String, array<Object>[]()[][]) | Appends text to the PromptBuilder object and specifies formatting for the text.
Public method | AppendTextWithAlias | Appends text to the PromptBuilder object and specifies the alias text to be spoken in place of the appended text.
Public method | AppendTextWithHint(String, SayAs) | Appends text to the PromptBuilder object and specifies the content type using a member of the SayAs enumeration.
Public method | AppendTextWithHint(String, String) | Appends text to the PromptBuilder object and a String that specifies the content type of the text.
Public method | AppendTextWithPronunciation | Appends text to the PromptBuilder object and specifies the pronunciation for the text.
Public method | ClearContent | Clears the content from the PromptBuilder object.
Public method | EndParagraph | Specifies the end of a paragraph in the PromptBuilder object.
Public method | EndSentence | Specifies the end of a sentence in the PromptBuilder object.
Public method | EndStyle | Specifies the end of a style in the PromptBuilder object.
Public method | EndVoice | Specifies the end of use of a voice in the PromptBuilder object.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | RemovePromptDatabase |
Public method | SetText(String) | Replaces the current content in a PromptBuilder object with a string.
Public method | SetText(String, array<Object>[]()[][]) | Replaces the current content in a PromptBuilder object with a string and specifies formatting for the contents of the string.
Public method | StartParagraph()()()() | Specifies the start of a paragraph in the PromptBuilder object.
Public method | StartParagraph(CultureInfo) | Specifies the start of a paragraph in the specified culture in the PromptBuilder object.
Public method | StartSentence()()()() | Specifies the start of a sentence in the PromptBuilder object.
Public method | StartSentence(CultureInfo) | Specifies the start of a sentence in the specified culture in the PromptBuilder object.
Public method | StartStyle | Specifies the start of a style in the PromptBuilder object.
Public method | StartVoice(CultureInfo) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the culture of the voice to use.
Public method | StartVoice(String) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the name of the voice to use.
Public method | StartVoice(VoiceGender) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the gender of the voice to use.
Public method | StartVoice(VoiceInfo) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies criteria for the new voice.
Public method | StartVoice(VoiceGender, VoiceAge) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the gender and the age of the voice to use.
Public method | StartVoice(VoiceGender, VoiceAge, Int32) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies its gender, age, and a preferred voice that matches the specified gender and age.
Public method | ToString | (Inherited from Object.)
Public method | ToXml | Returns the SSML generated from the PromptBuilder object.
Top

See Also

Reference

PromptBuilder Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptBuilder Constructor

[image] [image]

PromptBuilder Constructor
PromptBuilder Class See Also Send Feedback

Creates a new instance of the PromptBuilder class.

Overload List

 | Name | Description
Public method | PromptBuilder()()()() | Creates a new instance of the PromptBuilder class.
Public method | PromptBuilder(CultureInfo) | Creates a new instance of the PromptBuilder class and specifies a culture.
Top

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptBuilder Constructor

[image]

PromptBuilder Constructor
PromptBuilder Class Example See Also Send Feedback

Creates a new instance of the PromptBuilder class.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New PromptBuilder()
C#
public PromptBuilder()

Examples

The following example creates a new PromptBuilder instance and adds a text string to it.

C# Copy image Copy Code
using Microsoft.Speech.Synthesis;

public void MySimpleText ()
{
    PromptBuilder builder = new PromptBuilder ();
    builder.AppendText("Hello world!");
}

The following markup shows the equivalent in Speech Synthesis Markup Language (SSML), (xml:lang is a required attribute of the speak element):

Copy image Copy Code
<speak version="1.0"
 xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="en-US">
  Hello world!
</speak>

See Also

Reference

PromptBuilder Class
PromptBuilder Members
PromptBuilder Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptBuilder Constructor (CultureInfo)

[image]

PromptBuilder Constructor (CultureInfo)
PromptBuilder Class Example See Also Send Feedback

Creates a new instance of the PromptBuilder class and specifies a culture.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    culture As CultureInfo _
)
Visual Basic (Usage)
Dim culture As CultureInfo

Dim instance As New PromptBuilder(culture)
C#
public PromptBuilder(
    CultureInfo culture
)

Parameters

culture
Type: System.Globalization..::..CultureInfo

Provides information about a specific culture, such as its language, the name of the culture, the writing system, the calendar used, and how to format dates and sort strings.

Remarks

This constructor sets the value for the Culture property. For a given language code specified in the culture parameter, a speech synthesis engine that supports that language code must be installed to correctly pronounce words in the specified language. Use the GetInstalledVoices()()()() methods and VoiceInfo class to obtain the names and attributes of installed text-to-speech (TTS) voices that you can select.

The Microsoft Speech Platform Runtime 11 and Microsoft Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech. See InstalledVoice for more information.

The Speech Platform SDK 11 accepts all valid language-country codes as values for culture. See Language Identifier Constants and Strings for a comprehensive list of language codes.

Note Note

Speech synthesis is often referred to as text-to-speech or TTS. An installed TTS engine is also referred to as a voice. A language pack for speech synthesis contains a TTS engine, or voice.

Examples

The following example creates a PromptBuilder object that counts from one to four in French. The French speaking voice is specified by the culture parameter in the PromptBuilder(CultureInfo) constructor. The SpeechSynthesizer object automatically selects and uses the default voice for the language specified in the culture parameter. Correct pronunciation of the numbers will only be achieved if a language pack for French has been installed. If no language is specified or if the specified language is not installed, SpeechSynthesizer object uses the default language for the host system. Using a voice in a language other than French will speak the numbers, but will not pronounce them correctly.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\test\cultures.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\test\cultures.wav");

        PromptBuilder cultures = new PromptBuilder(
          new System.Globalization.CultureInfo("fr-FR"));

        // Count in French.

        cultures.AppendText("un, deux, trois, quatre");

        // Speak the prompt and play back the output file.
        synth.Speak(cultures);
        m_SoundPlayer.Play();
      }

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

See Also

Reference

PromptBuilder Class
PromptBuilder Members
PromptBuilder Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptBuilder Methods

[image] [image]

PromptBuilder Methods
PromptBuilder Class See Also Send Feedback

The PromptBuilder type exposes the following members.

Methods

 | Name | Description
Public method | AddPromptDatabase |
Public method | AppendAudio(String) | Appends the specified audio file to the PromptBuilder.
Public method | AppendAudio(Uri) | Appends the audio file at the specified URI to the PromptBuilder.
Public method | AppendAudio(Uri, String) | Appends the specified audio file and alternate text to the PromptBuilder.
Public method | AppendBookmark | Appends a bookmark to the PromptBuilder object.
Public method | AppendBreak()()()() | Appends a break to the PromptBuilder object.
Public method | AppendBreak(TimeSpan) | Appends a break of the specified duration to the PromptBuilder object.
Public method | AppendBreak(PromptBreak) | Appends a break of the specified strength (duration) to the PromptBuilder object.
Public method | AppendPromptBuilder | Appends a PromptBuilder object to a PromptBuilder object.
Public method | AppendSsml | Appends the specified XML file containing SSML to the PromptBuilder object.
Public method | AppendSsmlMarkup | Appends the specified string containing SSML markup into the PromptBuilder object.
Public method | AppendText(String) | Specifies text to append to the PromptBuilder object.
Public method | AppendText(String, PromptEmphasis) | Appends text to the PromptBuilder object and specifies the degree of emphasis for the text.
Public method | AppendText(String, PromptRate) | Appends text to the PromptBuilder object and specifies the speaking rate for the text.
Public method | AppendText(String, PromptVolume) | Appends text to the PromptBuilder object and specifies a volume for the text to be spoken.
Public method | AppendText(String, array<Object>[]()[][]) | Appends text to the PromptBuilder object and specifies formatting for the text.
Public method | AppendTextWithAlias | Appends text to the PromptBuilder object and specifies the alias text to be spoken in place of the appended text.
Public method | AppendTextWithHint(String, SayAs) | Appends text to the PromptBuilder object and specifies the content type using a member of the SayAs enumeration.
Public method | AppendTextWithHint(String, String) | Appends text to the PromptBuilder object and a String that specifies the content type of the text.
Public method | AppendTextWithPronunciation | Appends text to the PromptBuilder object and specifies the pronunciation for the text.
Public method | ClearContent | Clears the content from the PromptBuilder object.
Public method | EndParagraph | Specifies the end of a paragraph in the PromptBuilder object.
Public method | EndSentence | Specifies the end of a sentence in the PromptBuilder object.
Public method | EndStyle | Specifies the end of a style in the PromptBuilder object.
Public method | EndVoice | Specifies the end of use of a voice in the PromptBuilder object.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | RemovePromptDatabase |
Public method | SetText(String) | Replaces the current content in a PromptBuilder object with a string.
Public method | SetText(String, array<Object>[]()[][]) | Replaces the current content in a PromptBuilder object with a string and specifies formatting for the contents of the string.
Public method | StartParagraph()()()() | Specifies the start of a paragraph in the PromptBuilder object.
Public method | StartParagraph(CultureInfo) | Specifies the start of a paragraph in the specified culture in the PromptBuilder object.
Public method | StartSentence()()()() | Specifies the start of a sentence in the PromptBuilder object.
Public method | StartSentence(CultureInfo) | Specifies the start of a sentence in the specified culture in the PromptBuilder object.
Public method | StartStyle | Specifies the start of a style in the PromptBuilder object.
Public method | StartVoice(CultureInfo) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the culture of the voice to use.
Public method | StartVoice(String) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the name of the voice to use.
Public method | StartVoice(VoiceGender) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the gender of the voice to use.
Public method | StartVoice(VoiceInfo) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies criteria for the new voice.
Public method | StartVoice(VoiceGender, VoiceAge) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the gender and the age of the voice to use.
Public method | StartVoice(VoiceGender, VoiceAge, Int32) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies its gender, age, and a preferred voice that matches the specified gender and age.
Public method | ToString | (Inherited from Object.)
Public method | ToXml | Returns the SSML generated from the PromptBuilder object.
Top

See Also

Reference

PromptBuilder Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AddPromptDatabase Method

[image]

PromptBuilder..::..AddPromptDatabase Method
PromptBuilder Class See Also Send Feedback

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

Syntax

Visual Basic (Declaration)
Public Sub AddPromptDatabase ( _
    promptDatabase As Uri _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim promptDatabase As Uri

instance.AddPromptDatabase(promptDatabase)
C#
public void AddPromptDatabase(
    Uri promptDatabase
)

Parameters

promptDatabase
Type: System..::..Uri

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendAudio Method

[image] [image]

PromptBuilder..::..AppendAudio Method
PromptBuilder Class See Also Send Feedback

Overload List

 | Name | Description
Public method | AppendAudio(String) | Appends the specified audio file to the PromptBuilder.
Public method | AppendAudio(Uri) | Appends the audio file at the specified URI to the PromptBuilder.
Public method | AppendAudio(Uri, String) | Appends the specified audio file and alternate text to the PromptBuilder.
Top

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendAudio Method (String)

[image]

PromptBuilder..::..AppendAudio Method (String)
PromptBuilder Class See Also Send Feedback

Appends the specified audio file to the PromptBuilder.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendAudio ( _
    path As String _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim path As String

instance.AppendAudio(path)
C#
public void AppendAudio(
    string path
)

Parameters

path
Type: System..::..String

A fully qualified path to the audio file.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendAudio Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendAudio Method (Uri)

[image]

PromptBuilder..::..AppendAudio Method (Uri)
PromptBuilder Class Example See Also Send Feedback

Appends the audio file at the specified URI to the PromptBuilder.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendAudio ( _
    audioFile As Uri _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim audioFile As Uri

instance.AppendAudio(audioFile)
C#
public void AppendAudio(
    Uri audioFile
)

Parameters

audioFile
Type: System..::..Uri

URI for the audio file.

Remarks

The audio file can be in WMA format provided that both of the following conditions are met.

  • The WMA codec is available.

  • The target operating system has the appropriate Windows features installed or enabled.

    • A computer running Microsoft Windows Server 2003 x64 Editions must have Windows Media Format 9.5 Software Development Kit (SDK) x64 Edition installed.

    • A computer running Microsoft Windows Server 2008 or Windows Server 2008 R2 must have the Desktop Experience feature installed, as described in the following procedure.

    • Windows Vista and Windows 7 already have the Desktop Experience feature enabled automatically.

To install the Desktop Experience feature (Windows Server 2008, Windows Server 2008 R2)

  1. On the Start menu, click Server Management.

  2. In the Server Management dialog box, in the Features Summary pane, click Add Features.

  3. In the Select Features dialog box, select the Desktop Experience check box, and then click Install.

Examples

The following example initializes a new instance to the PromptBuilder class and then adds text, followed by an audio file, to it.

C# Copy image Copy Code
using Microsoft.Speech.PromptBuilder;

public void SimpleConcatenation()
{

    // Concatenate a prompt fragment from a .wav file
    PromptBuilder builder = new PromptBuilder ();
    builder.AppendText("How are you today?");
    builder.AppendAudio(new Uri ("http://www.speech.microsoft.com/ding.wav"));
}

The following markup shows the equivalent SSML.

Copy image Copy Code
<speak xmlns="http://www.w3.org/2001/10/synthesis"
       xmlns:ms="http://www.microsoft.com/speech/synthesis" xml:lang="en">
  How are you today?
  <audio src="http://www.speech.microsoft.com/ding.wav" />
</speak>

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendAudio Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendAudio Method (Uri, String)

[image]

PromptBuilder..::..AppendAudio Method (Uri, String)
PromptBuilder Class Example See Also Send Feedback

Appends the specified audio file and alternate text to the PromptBuilder.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendAudio ( _
    audioFile As Uri, _
    alternateText As String _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim audioFile As Uri
Dim alternateText As String

instance.AppendAudio(audioFile, alternateText)
C#
public void AppendAudio(
    Uri audioFile,
    string alternateText
)

Parameters

audioFile
Type: System..::..Uri

URI for the audio file.

alternateText
Type: System..::..String

A string containing alternate text representing the audio.

Remarks

The audio file can be in WMA format provided that both of the following conditions are met.

  • The WMA codec is available.

  • The target operating system has the appropriate Windows features installed or enabled.

    • A computer running Microsoft Windows Server 2003 x64 Editions must have Windows Media Format 9.5 Software Development Kit (SDK) x64 Edition installed.

    • A computer running Microsoft Windows Server 2008 or Windows Server 2008 R2 must have the Desktop Experience feature installed, as described in the following procedure.

    • Windows Vista and Windows 7 already have the Desktop Experience feature enabled automatically.

To install the Desktop Experience feature (Windows Server 2008, Windows Server 2008 R2)

  1. On the Start menu, click Server Management.

  2. In the Server Management dialog box, in the Features Summary pane, click Add Features.

  3. In the Select Features dialog box, select the Desktop Experience check box, and then click Install.

Examples

The following examples adds an audio file to a PromptBuilder instance and specifies text to speak if the audio file cannot be played.

Copy image Copy Code
using Microsoft.Speech.PromptBuilder;

public void SimpleConcatenation()
{

    // Concatenate a prompt fragment from a .wav file.
    PromptBuilder builder = new PromptBuilder ();
    builder.AppendAudio(new Uri ("C:\\OnHold.wav"), "Your call will be answered in the order it was received");
}

The following markup shows the equivalent SSML markup.

Copy image Copy Code
<speak xmlns="http://www.w3.org/2001/10/synthesis"
       xmlns:ms="http://www.microsoft.com/speech/synthesis" xml:lang="en">

  <audio src="C:\OnHold.wav"> Your call will be answered in the order it was received. </audio>

</speak>

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendAudio Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendBookmark Method

[image]

PromptBuilder..::..AppendBookmark Method
PromptBuilder Class Example See Also Send Feedback

Appends a bookmark to the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendBookmark ( _
    bookmarkName As String _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim bookmarkName As String

instance.AppendBookmark(bookmarkName)
C#
public void AppendBookmark(
    string bookmarkName
)

Parameters

bookmarkName
Type: System..::..String

A string containing the name of the appended bookmark.

Remarks

A speech synthesis engine will generate a BookmarkReached event if it encounters a bookmark while speaking a prompt using any of the Speak()()()(), SpeakAsync()()()(), SpeakSsml(String), or SpeakSsmlAsync(String) methods.

Examples

The following example creates a prompt that includes two bookmarks and sends the output to a WAV file for playback. The handler for the BookmarkReached event writes the name of the bookmark and its position in the audio stream when the event was raised to the console.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\test\weather.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\test\weather.wav");

        // Build a prompt and append bookmarks.
        PromptBuilder builder = new PromptBuilder(
          new System.Globalization.CultureInfo("en-US"));
        builder.AppendText(
          "The weather forecast for today is partly cloudy with some sun breaks.");
        builder.AppendBookmark("Daytime forecast");
        builder.AppendText(
          "Tonight's weather will be cloudy with a 30% chance of showers.");
        builder.AppendBookmark("Nightime forecast");

        // Add a handler for the BookmarkReached event.
        synth.BookmarkReached +=
          new EventHandler<BookmarkReachedEventArgs>(synth_BookmarkReached);

        // Speak the prompt and play back the output file.
        synth.Speak(builder);
        m_SoundPlayer.Play();
      }

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

    // Write the name and position of the bookmark to the console.
    static void synth_BookmarkReached(object sender, BookmarkReachedEventArgs e)
    {
      Console.WriteLine("Bookmark ({0}) reached at: {1} ",
        e.Bookmark, e.AudioPosition);
    }
  }
}

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendBreak Method

[image] [image]

PromptBuilder..::..AppendBreak Method
PromptBuilder Class See Also Send Feedback

Appends a break (pause) to the PromptBuilder.

Overload List

 | Name | Description
Public method | AppendBreak()()()() | Appends a break to the PromptBuilder object.
Public method | AppendBreak(TimeSpan) | Appends a break of the specified duration to the PromptBuilder object.
Public method | AppendBreak(PromptBreak) | Appends a break of the specified strength (duration) to the PromptBuilder object.
Top

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendBreak Method

[image]

PromptBuilder..::..AppendBreak Method
PromptBuilder Class See Also Send Feedback

Appends a break to the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendBreak
Visual Basic (Usage)
Dim instance As PromptBuilder

instance.AppendBreak()
C#
public void AppendBreak()

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendBreak Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendBreak Method (TimeSpan)

[image]

PromptBuilder..::..AppendBreak Method (TimeSpan)
PromptBuilder Class See Also Send Feedback

Appends a break of the specified duration to the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendBreak ( _
    duration As TimeSpan _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim duration As TimeSpan

instance.AppendBreak(duration)
C#
public void AppendBreak(
    TimeSpan duration
)

Parameters

duration
Type: System..::..TimeSpan

The time in ticks, where one tick equals 100 nanoseconds.

Remarks

A break can be used to control pauses or other prosodic boundaries between words. A break is optional. If a break is not present, the synthesizer determines the break between words depending on the linguistic context.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendBreak Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendBreak Method (PromptBreak)

[image]

PromptBuilder..::..AppendBreak Method (PromptBreak)
PromptBuilder Class Example See Also Send Feedback

Appends a break of the specified strength (duration) to the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendBreak ( _
    strength As PromptBreak _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim strength As PromptBreak

instance.AppendBreak(strength)
C#
public void AppendBreak(
    PromptBreak strength
)

Parameters

strength
Type: Microsoft.Speech.Synthesis..::..PromptBreak

Indicates the duration of the break.

Remarks

The values in the PromptBreak enumeration represent a range of separation intervals (pauses) between word boundaries. The speech synthesis engine determines the exact duration of the interval. When a break is requested, one of these values is passed to the text-to-speech (TTS) engine, which contains a mapping between these values and the corresponding millisecond break values.

Examples

The following example builds a prompt containing two sentences separated by a break and sends the output to a WAV file for playback.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\test\weather.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\test\weather.wav");

        // Build a prompt with two sentences separated by a break.
        PromptBuilder builder = new PromptBuilder(
          new System.Globalization.CultureInfo("en-US"));
        builder.AppendText(
          "Tonight's movie showings in theater A are at 5:45, 7:15, and 8:45");
        builder.AppendBreak(PromptBreak.Medium);
        builder.AppendText(
          "Tonight's movie showings in theater B are at 5:15, 7:15, and 9:15");

        // Speak the prompt and play back the output file.
        synth.Speak(builder);
        m_SoundPlayer.Play();
      }

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

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendBreak Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendPromptBuilder Method

[image]

PromptBuilder..::..AppendPromptBuilder Method
PromptBuilder Class Example See Also Send Feedback

Appends a PromptBuilder object to a PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendPromptBuilder ( _
    promptBuilder As PromptBuilder _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim promptBuilder As PromptBuilder

instance.AppendPromptBuilder(promptBuilder)
C#
public void AppendPromptBuilder(
    PromptBuilder promptBuilder
)

Parameters

promptBuilder
Type: Microsoft.Speech.Synthesis..::..PromptBuilder

The content to append.

Examples

The example that follows creates two PromptBuilder instances and then appends them to a third PromptBuilder.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\test\showtimes.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\test\showtimes.wav");

        // Build child prompts.
        PromptBuilder theatreA = new PromptBuilder();
        theatreA.AppendText(
          "Tonight's movie showings in theater A are at 5:45, 7:15, and 9:30");
        theatreA.AppendBreak(PromptBreak.Large);
        PromptBuilder theatreB = new PromptBuilder();
        theatreB.AppendText(
          "Tonight's movie showings in theater B are at 5:15, 7:15, and 9:15");

        // Build the parent prompt and append the two child prompts.
        PromptBuilder showTimes = new PromptBuilder(
          new System.Globalization.CultureInfo("en-US"));
        showTimes.AppendText(
          "The following are the show times for tonight's movies:");
        showTimes.AppendPromptBuilder(theatreA);
        showTimes.AppendPromptBuilder(theatreB);

        // Speak the prompt and play back the output file.
        synth.Speak(showTimes);
        m_SoundPlayer.Play();
      }

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

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendSsml Method

[image]

PromptBuilder..::..AppendSsml Method
PromptBuilder Class Example See Also Send Feedback

Appends the specified XML file containing SSML to the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendSsml ( _
    ssmlFile As XmlReader _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim ssmlFile As XmlReader

instance.AppendSsml(ssmlFile)
C#
public void AppendSsml(
    XmlReader ssmlFile
)

Parameters

ssmlFile
Type: System.Xml..::..XmlReader

A fully qualified name to the XML file to append.

Examples

The following example creates a PromptBuilder object from an XmlReader object that references a file containing Speech Synthesis Markup Language (SSML) markup.

Copy image Copy Code
using System;
using System.Xml;
using System.IO;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\test\weather.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\test\weather.wav");

        // Create the path to the SSML file.
        string weatherFile = Path.GetFullPath("c:\\test\\Weather.xml");
        PromptBuilder builder = null;

        // Create an XML Reader from the file, create a PromptBuilder and
        // append the XmlReader.
        if (File.Exists(weatherFile))
        {
          XmlReader reader = XmlReader.Create(weatherFile);
          builder = new PromptBuilder();
          builder.AppendSsml(reader);
          reader.Close();
        }

        // Speak the prompt and play back the output file.
        synth.Speak(builder);
        m_SoundPlayer.Play();
      }

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

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendSsmlMarkup Method

[image]

PromptBuilder..::..AppendSsmlMarkup Method
PromptBuilder Class See Also Send Feedback

Appends the specified string containing SSML markup into the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendSsmlMarkup ( _
    ssmlMarkup As String _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim ssmlMarkup As String

instance.AppendSsmlMarkup(ssmlMarkup)
C#
public void AppendSsmlMarkup(
    string ssmlMarkup
)

Parameters

ssmlMarkup
Type: System..::..String

A string containing SSML markup.

Remarks

You must use the appropriate escape characters when appending SSML markup. Notice the backward-slashes preceding the quotation marks enclosing the value of the interpret-as attribute in the following example:

C# Copy image Copy Code
builder.AppendSsmlMarkup("<say-as interpret-as = \"characters\"> chair </say-as>");
Note Note

The string used as an argument to AppendSsmlMarkup(String) cannot include a speak element.

When using AppendSsmlMarkup(String) to specify inline pronunciations in a phoneme element, you can use phones from any of the following phonetic alphabets, provided that the current speech engine supports it:

  • International Phonetic Alphabet (IPA)

  • Universal Phone Set (UPS)

  • SAPI Phone Set

Any SSML-compliant speech engine will speak phones from the IPA.

You can also append a file containing SSML markup using the AppendSsml(XmlReader) method. To append text to be spoken that is not formatted with markup language, use one of the AppendText()()()(), AppendTextWithAlias(String, String), AppendTextWithHint()()()(), or AppendTextWithPronunciation(String, String) methods.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendText Method

[image] [image]

PromptBuilder..::..AppendText Method
PromptBuilder Class See Also Send Feedback

Overload List

 | Name | Description
Public method | AppendText(String) | Specifies text to append to the PromptBuilder object.
Public method | AppendText(String, PromptEmphasis) | Appends text to the PromptBuilder object and specifies the degree of emphasis for the text.
Public method | AppendText(String, PromptRate) | Appends text to the PromptBuilder object and specifies the speaking rate for the text.
Public method | AppendText(String, PromptVolume) | Appends text to the PromptBuilder object and specifies a volume for the text to be spoken.
Public method | AppendText(String, array<Object>[]()[][]) | Appends text to the PromptBuilder object and specifies formatting for the text.
Top

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendText Method (String)

[image]

PromptBuilder..::..AppendText Method (String)
PromptBuilder Class See Also Send Feedback

Specifies text to append to the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendText ( _
    textToSpeak As String _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim textToSpeak As String

instance.AppendText(textToSpeak)
C#
public void AppendText(
    string textToSpeak
)

Parameters

textToSpeak
Type: System..::..String

A string containing the text to be spoken.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendText Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendText Method (String, PromptEmphasis)

[image]

PromptBuilder..::..AppendText Method (String, PromptEmphasis)
PromptBuilder Class See Also Send Feedback

Appends text to the PromptBuilder object and specifies the degree of emphasis for the text.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendText ( _
    textToSpeak As String, _
    emphasis As PromptEmphasis _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim textToSpeak As String
Dim emphasis As PromptEmphasis

instance.AppendText(textToSpeak, emphasis)
C#
public void AppendText(
    string textToSpeak,
    PromptEmphasis emphasis
)

Parameters

textToSpeak
Type: System..::..String

A string containing the text to be spoken.

emphasis
Type: Microsoft.Speech.Synthesis..::..PromptEmphasis

The value for the emphasis or stress to apply to the text.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendText Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendText Method (String, PromptRate)

[image]

PromptBuilder..::..AppendText Method (String, PromptRate)
PromptBuilder Class See Also Send Feedback

Appends text to the PromptBuilder object and specifies the speaking rate for the text.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendText ( _
    textToSpeak As String, _
    rate As PromptRate _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim textToSpeak As String
Dim rate As PromptRate

instance.AppendText(textToSpeak, rate)
C#
public void AppendText(
    string textToSpeak,
    PromptRate rate
)

Parameters

textToSpeak
Type: System..::..String

A string containing the text to be spoken.

rate
Type: Microsoft.Speech.Synthesis..::..PromptRate

The value for the speaking rate to apply to the text.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendText Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendText Method (String, PromptVolume)

[image]

PromptBuilder..::..AppendText Method (String, PromptVolume)
PromptBuilder Class See Also Send Feedback

Appends text to the PromptBuilder object and specifies a volume for the text to be spoken.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendText ( _
    textToSpeak As String, _
    volume As PromptVolume _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim textToSpeak As String
Dim volume As PromptVolume

instance.AppendText(textToSpeak, volume)
C#
public void AppendText(
    string textToSpeak,
    PromptVolume volume
)

Parameters

textToSpeak
Type: System..::..String

A string containing the text to be spoken.

volume
Type: Microsoft.Speech.Synthesis..::..PromptVolume

The value for the speaking volume (loudness) to apply to the text.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendText Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendText Method (String, Object[])

[image]

PromptBuilder..::..AppendText Method (String, array<Object>[]()[][])
PromptBuilder Class Example See Also Send Feedback

Appends text to the PromptBuilder object and specifies formatting for the text.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendText ( _
    textToSpeak As String, _
    ParamArray args As Object() _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim textToSpeak As String
Dim args As Object()

instance.AppendText(textToSpeak, args)
C#
public void AppendText(
    string textToSpeak,
    params Object[] args
)

Parameters

textToSpeak
Type: System..::..String

A string containing the text to be spoken.

args
Type: array< System..::..Object >[]()[][]

Objects that determine the formatting of the string specified by textToSpeak.

Remarks

This method uses the object array specified by args as parameters to Format()()()().

Examples

The following example uses the AppendText(String, array<Object>[]()[][]) method to set the formatting of a string to InvariantCulture.

Copy image Copy Code
public void AppendText(string textToSpeak, params object[] args)
{
  AppendText(String.Format(CultureInfo.InvariantCulture, textToSpeak, args));
}

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendText Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendTextWithAlias Method

[image]

PromptBuilder..::..AppendTextWithAlias Method
PromptBuilder Class Example See Also Send Feedback

Appends text to the PromptBuilder object and specifies the alias text to be spoken in place of the appended text.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendTextWithAlias ( _
    textToSpeak As String, _
    substitute As String _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim textToSpeak As String
Dim substitute As String

instance.AppendTextWithAlias(textToSpeak, _
    substitute)
C#
public void AppendTextWithAlias(
    string textToSpeak,
    string substitute
)

Parameters

textToSpeak
Type: System..::..String

A string containing the text representation.

substitute
Type: System..::..String

A string containing the text to be spoken.

Remarks

This allows a document to contain both a spoken and a written form for a prompt. For example, the written form could be an acronym, such as SAPI, and the spoken form could be the expanded text for the acronym, in this case Speech Application Programming Interface.

Examples

The following example appends a text string ("Speech Synthesis Markup Language") and its alias ("SSML") to a PromptBuilder object. The synthesizer will pronounce "S S M L".

Copy image Copy Code
PromptBuilder alias = new PromptBuilder();
alias.AppendTextWithAlias("Speech Synthesis Markup Language","SSML");

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendTextWithHint Method

[image] [image]

PromptBuilder..::..AppendTextWithHint Method
PromptBuilder Class See Also Send Feedback

Appends text to the PromptBuilder object and specifies the content type of the text.

Overload List

 | Name | Description
Public method | AppendTextWithHint(String, SayAs) | Appends text to the PromptBuilder object and specifies the content type using a member of the SayAs enumeration.
Public method | AppendTextWithHint(String, String) | Appends text to the PromptBuilder object and a String that specifies the content type of the text.
Top

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendTextWithHint Method (String, SayAs)

[image]

PromptBuilder..::..AppendTextWithHint Method (String, SayAs)
PromptBuilder Class See Also Send Feedback

Appends text to the PromptBuilder object and specifies the content type using a member of the SayAs enumeration.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendTextWithHint ( _
    textToSpeak As String, _
    sayAs As SayAs _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim textToSpeak As String
Dim sayAs As SayAs

instance.AppendTextWithHint(textToSpeak, _
    sayAs)
C#
public void AppendTextWithHint(
    string textToSpeak,
    SayAs sayAs
)

Parameters

textToSpeak
Type: System..::..String

A string containing the text to be spoken.

sayAs
Type: Microsoft.Speech.Synthesis..::..SayAs

The content type of the text.

Remarks

The content type specified by sayAs can provide guidance to the speech synthesis engine about how to pronounce the contents of textToSpeak.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendTextWithHint Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendTextWithHint Method (String, String)

[image]

PromptBuilder..::..AppendTextWithHint Method (String, String)
PromptBuilder Class See Also Send Feedback

Appends text to the PromptBuilder object and a String that specifies the content type of the text.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendTextWithHint ( _
    textToSpeak As String, _
    sayAs As String _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim textToSpeak As String
Dim sayAs As String

instance.AppendTextWithHint(textToSpeak, _
    sayAs)
C#
public void AppendTextWithHint(
    string textToSpeak,
    string sayAs
)

Parameters

textToSpeak
Type: System..::..String

A string containing the text to be spoken.

sayAs
Type: System..::..String

The content type of the text.

Remarks

You can use this method to specify a content type that is not included in the SayAs enumeration. However, the TTS engine must support the parameter that you specify.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
AppendTextWithHint Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AppendTextWithPronunciation Method

[image]

PromptBuilder..::..AppendTextWithPronunciation Method
PromptBuilder Class Example See Also Send Feedback

Appends text to the PromptBuilder object and specifies the pronunciation for the text.

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

Syntax

Visual Basic (Declaration)
Public Sub AppendTextWithPronunciation ( _
    textToSpeak As String, _
    pronunciation As String _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim textToSpeak As String
Dim pronunciation As String

instance.AppendTextWithPronunciation(textToSpeak, _
    pronunciation)
C#
public void AppendTextWithPronunciation(
    string textToSpeak,
    string pronunciation
)

Parameters

textToSpeak
Type: System..::..String

A string containing the written form of the word using the conventional alphabet for a language.

pronunciation
Type: System..::..String

A string containing phones to be spoken from the International Phonetic Alphabet (IPA).

Remarks

The synthesizer speaks the contents of the Pronunciation parameter, not the contents of the textToSpeak parameter.

Pronunciations specified inline in prompts apply only to the individual occurrence of a word and override pronunciations of the speech engine or any of its currently active lexicons. Typically, you will use inline pronunciations for custom pronunciations of existing words or for pronunciation of uncommon words, such as proper names, which the speech synthesis engine may not pronounce as well as expected.

Inline pronunciations must be specified using phones from the International Phonetic Alphabet (IPA). A phone is a letter or character that represents a discreet sound of speech. Speech engines that comply with the Speech Synthesis Markup Language (SSML) Version 1.0 specification will pronounce phones from the IPA. To specify inline pronunciations using other phonetic alphabets, see AppendSsmlMarkup(String). For more information see Lexicons and Phonetic Alphabets (Microsoft.Speech).

Some phones in the IPA alphabet have the same representations as letters in the Latin alphabet. In those cases, it is possible to type the Latin character and have the proper representation for a phone. Because the Latin characters as commonly used in text may represent several phones of the IPA phone set, simply typing the Latin character might not result in the precise IPA phone desired. Other phones of the IPA alphabet need to be represented in code as character references consisting of an ampersand (&), the number sign (#), and a Unicode number for the desired phone in hexadecimal or decimal, all followed by a semicolon (;). For example, a schwa (&#x0259;) would be represented by &#x0259;.

The IPA publishes a chart that maps its phoneme set to Unicode numbers.

Examples

The following example initializes a new instance of the PromptBuilder class. It then appends the text string "My name is" to the instance. Finally, it appends a string containing the proper name "DuBois" and specifies the pronunciation of the name.

C# Copy image Copy Code
public void ProperName()
{
    PromptBuilder builder = new PromptBuilder();
    builder.AppendText("My name is");

    // Add a proper name and its pronunciation.
    builder.AppendTextWithPronunciation("DuBois", "duˈbwɑ");
}

The following markup shows the SSML that this PromptBuilder object generates.

Copy image Copy Code
<speak xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="en-us">
  My name is <phoneme ph="duˈbwɑ"> DuBois </phoneme>
</speak>

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace

Other Resources

International Phonetic Association
Lexicons and Phonetic Alphabets (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ClearContent Method

[image]

PromptBuilder..::..ClearContent Method
PromptBuilder Class See Also Send Feedback

Clears the content from the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub ClearContent
Visual Basic (Usage)
Dim instance As PromptBuilder

instance.ClearContent()
C#
public void ClearContent()

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EndParagraph Method

[image]

PromptBuilder..::..EndParagraph Method
PromptBuilder Class See Also Send Feedback

Specifies the end of a paragraph in the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub EndParagraph
Visual Basic (Usage)
Dim instance As PromptBuilder

instance.EndParagraph()
C#
public void EndParagraph()

Remarks

Long prompts can be rendered more like human speech if they are broken into sentences and paragraphs.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EndSentence Method

[image]

PromptBuilder..::..EndSentence Method
PromptBuilder Class See Also Send Feedback

Specifies the end of a sentence in the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub EndSentence
Visual Basic (Usage)
Dim instance As PromptBuilder

instance.EndSentence()
C#
public void EndSentence()

Remarks

Long prompts can be rendered more like human speech if they are broken into sentences and paragraphs.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EndStyle Method

[image]

PromptBuilder..::..EndStyle Method
PromptBuilder Class See Also Send Feedback

Specifies the end of a style in the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub EndStyle
Visual Basic (Usage)
Dim instance As PromptBuilder

instance.EndStyle()
C#
public void EndStyle()

Remarks

The EndStyle()()()() method stops the current speaking style. The speaking style reverts to the setting that was in effect before the StartStyle(PromptStyle) method initiated a new speaking style.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EndVoice Method

[image]

PromptBuilder..::..EndVoice Method
PromptBuilder Class See Also Send Feedback

Specifies the end of use of a voice in the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub EndVoice
Visual Basic (Usage)
Dim instance As PromptBuilder

instance.EndVoice()
C#
public void EndVoice()

Remarks

The EndVoice()()()() method stops the use of the current voice for speech output. The voice reverts to the setting that was in effect before the StartVoice()()()() method initiated a new voice.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RemovePromptDatabase Method

[image]

PromptBuilder..::..RemovePromptDatabase Method
PromptBuilder Class See Also Send Feedback

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

Syntax

Visual Basic (Declaration)
Public Sub RemovePromptDatabase ( _
    promptDatabase As Uri _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim promptDatabase As Uri

instance.RemovePromptDatabase(promptDatabase)
C#
public void RemovePromptDatabase(
    Uri promptDatabase
)

Parameters

promptDatabase
Type: System..::..Uri

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetText Method

[image] [image]

PromptBuilder..::..SetText Method
PromptBuilder Class See Also Send Feedback

Replaces the current content in a PromptBuilder object with new content.

Overload List

 | Name | Description
Public method | SetText(String) | Replaces the current content in a PromptBuilder object with a string.
Public method | SetText(String, array<Object>[]()[][]) | Replaces the current content in a PromptBuilder object with a string and specifies formatting for the contents of the string.
Top

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetText Method (String)

[image]

PromptBuilder..::..SetText Method (String)
PromptBuilder Class See Also Send Feedback

Replaces the current content in a PromptBuilder object with a string.

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

Syntax

Visual Basic (Declaration)
Public Sub SetText ( _
    textToSpeak As String _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim textToSpeak As String

instance.SetText(textToSpeak)
C#
public void SetText(
    string textToSpeak
)

Parameters

textToSpeak
Type: System..::..String

The new content for the PromptBuilder object.

Remarks

This method calls ClearContent()()()() and then AppendText(String), using textToSpeak as the string.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
SetText Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetText Method (String, Object[])

[image]

PromptBuilder..::..SetText Method (String, array<Object>[]()[][])
PromptBuilder Class See Also Send Feedback

Replaces the current content in a PromptBuilder object with a string and specifies formatting for the contents of the string.

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

Syntax

Visual Basic (Declaration)
Public Sub SetText ( _
    textToSpeak As String, _
    ParamArray args As Object() _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim textToSpeak As String
Dim args As Object()

instance.SetText(textToSpeak, args)
C#
public void SetText(
    string textToSpeak,
    params Object[] args
)

Parameters

textToSpeak
Type: System..::..String

The new content for the PromptBuilder object.

args
Type: array< System..::..Object >[]()[][]

Objects that determine the formatting of the string specified by textToSpeak.

Remarks

This method calls ClearContent()()()() and then AppendText(String, array<Object>[]()[][]). The SetText(String, array<Object>[]()[][]) method uses the object array specified by args as parameters to Format()()()().

See Also

Reference

PromptBuilder Class
PromptBuilder Members
SetText Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartParagraph Method

[image] [image]

PromptBuilder..::..StartParagraph Method
PromptBuilder Class See Also Send Feedback

Specifies the start of a paragraph in the PromptBuilder object, and optionally specifies a language.

Overload List

 | Name | Description
Public method | StartParagraph()()()() | Specifies the start of a paragraph in the PromptBuilder object.
Public method | StartParagraph(CultureInfo) | Specifies the start of a paragraph in the specified culture in the PromptBuilder object.
Top

Remarks

Long prompts can be rendered more like human speech if they are broken into sentences and paragraphs.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartParagraph Method

[image]

PromptBuilder..::..StartParagraph Method
PromptBuilder Class See Also Send Feedback

Specifies the start of a paragraph in the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub StartParagraph
Visual Basic (Usage)
Dim instance As PromptBuilder

instance.StartParagraph()
C#
public void StartParagraph()

Remarks

Long prompts can be rendered more like human speech if they are broken into sentences and paragraphs.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
StartParagraph Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartParagraph Method (CultureInfo)

[image]

PromptBuilder..::..StartParagraph Method (CultureInfo)
PromptBuilder Class Example See Also Send Feedback

Specifies the start of a paragraph in the specified culture in the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub StartParagraph ( _
    culture As CultureInfo _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim culture As CultureInfo

instance.StartParagraph(culture)
C#
public void StartParagraph(
    CultureInfo culture
)

Parameters

culture
Type: System.Globalization..::..CultureInfo

Provides information about a specific culture, such as the language, the name of the culture, the writing system, the calendar used, and how to format dates and sort strings.

Remarks

The culture parameter for a paragraph can be different than the Culture property of the PromptBuilder object that contains it.

For a given language code specified in the culture parameter, a speech synthesis engine that supports that language code must be installed to correctly pronounce words in the specified language. Use the GetInstalledVoices()()()() methods and VoiceInfo class to obtain the names and attributes of installed text-to-speech (TTS) voices that you can select.

The Microsoft Speech Platform Runtime 11 and Microsoft Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech. See InstalledVoice for more information.

The Speech Platform SDK 11 accepts all valid language-country codes as values for culture. See Language Identifier Constants and Strings for a comprehensive list of language codes.

Note Note

Speech synthesis is often referred to as text-to-speech or TTS. An installed TTS engine is also referred to as a voice. A language pack for speech synthesis contains a TTS engine, or voice.

Examples

The following example creates a PromptBuilder object that counts to ten; beginning in English, then in French, and finishing in German. Correct pronunciation of all the numbers will only be achieved if language packs for English, French, and German have been installed. The SpeechSynthesizer object automatically selects and uses the default voice for the language specified in the culture parameter of each StartParagraph(CultureInfo) constructor. If no language is specified in a prompt, or if the specified language is not installed, SpeechSynthesizer object uses the default language for the host system.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\test\cultures.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\test\cultures.wav");

        PromptBuilder cultures = new PromptBuilder();

        // Count in English.
        cultures.StartParagraph(
          new System.Globalization.CultureInfo("en-US"));
        cultures.AppendText("one, two, three");
        cultures.EndParagraph();

        // Count in French.
        cultures.StartParagraph(
          new System.Globalization.CultureInfo("fr-FR"));
        cultures.AppendText("quatre, cinq, six");
        cultures.EndParagraph();

        // Count in German.
        cultures.StartParagraph(
          new System.Globalization.CultureInfo("de-DE"));
        cultures.AppendText("sieben, acht, neun, zehn");
        cultures.EndParagraph();

        // Speak the prompt and play back the output file.
        synth.Speak(cultures);
        m_SoundPlayer.Play();
      }

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

See Also

Reference

PromptBuilder Class
PromptBuilder Members
StartParagraph Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartSentence Method

[image] [image]

PromptBuilder..::..StartSentence Method
PromptBuilder Class See Also Send Feedback

Specifies the start of a sentence in the PromptBuilder object, and optionally specifies a language.

Overload List

 | Name | Description
Public method | StartSentence()()()() | Specifies the start of a sentence in the PromptBuilder object.
Public method | StartSentence(CultureInfo) | Specifies the start of a sentence in the specified culture in the PromptBuilder object.
Top

Remarks

Long prompts can be rendered more like human speech if they are broken into sentences and paragraphs.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartSentence Method

[image]

PromptBuilder..::..StartSentence Method
PromptBuilder Class See Also Send Feedback

Specifies the start of a sentence in the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub StartSentence
Visual Basic (Usage)
Dim instance As PromptBuilder

instance.StartSentence()
C#
public void StartSentence()

Remarks

Long prompts can be rendered more like human speech if they are broken into sentences and paragraphs.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
StartSentence Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartSentence Method (CultureInfo)

[image]

PromptBuilder..::..StartSentence Method (CultureInfo)
PromptBuilder Class Example See Also Send Feedback

Specifies the start of a sentence in the specified culture in the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub StartSentence ( _
    culture As CultureInfo _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim culture As CultureInfo

instance.StartSentence(culture)
C#
public void StartSentence(
    CultureInfo culture
)

Parameters

culture
Type: System.Globalization..::..CultureInfo

Provides information about a specific culture, such as the language, the name of the culture, the writing system, the calendar used, and how to format dates and sort strings.

Remarks

The culture parameter for a sentence can be different than the culture parameter for the paragraph that contains it or than the Culture property of the PromptBuilder object that contains it.

For a given language code specified in the culture parameter, a speech synthesis engine that supports that language code must be installed to correctly pronounce words in the specified language. Use the GetInstalledVoices()()()() methods and VoiceInfo class to obtain the names and attributes of installed text-to-speech (TTS) voices that you can select.

The Microsoft Speech Platform Runtime 11 and Microsoft Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech. See InstalledVoice for more information.

The Speech Platform SDK 11 accepts all valid language-country codes as values for culture. See Language Identifier Constants and Strings for a comprehensive list of language codes.

Note Note

Speech synthesis is often referred to as text-to-speech or TTS. An installed TTS engine is also referred to as a voice. A language pack for speech synthesis contains a TTS engine, or voice.

Examples

The following example creates a PromptBuilder object that counts to ten; beginning in English, then in French, and finishing in German. Correct pronunciation of all the numbers will only be achieved if language packs for English, French, and German have been installed. The SpeechSynthesizer object automatically selects and uses the default voice for the language specified in the culture parameter of the StartParagraph(CultureInfo) and StartSentence(CultureInfo) constructors. If no language is specified in a prompt, or if the specified language is not installed, SpeechSynthesizer object uses the default language for the host system.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\test\cultures.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\test\cultures.wav");

        PromptBuilder cultures = new PromptBuilder();

        // Count in English.
        cultures.StartParagraph(
          new System.Globalization.CultureInfo("en-US"));
        cultures.AppendText("one, two, three");

        // Count in French.
        cultures.StartSentence(
          new System.Globalization.CultureInfo("fr-FR"));
        cultures.AppendText("quatre, cinq, six");
        cultures.EndSentence();

        // Count in German.
        cultures.StartSentence(
          new System.Globalization.CultureInfo("de-DE"));
        cultures.AppendText("sieben, acht, neun, zehn");
        cultures.EndSentence();

        cultures.EndParagraph();

        // Speak the prompt and play back the output file.
        synth.Speak(cultures);
        m_SoundPlayer.Play();
      }

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

See Also

Reference

PromptBuilder Class
PromptBuilder Members
StartSentence Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartStyle Method

[image]

PromptBuilder..::..StartStyle Method
PromptBuilder Class See Also Send Feedback

Specifies the start of a style in the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub StartStyle ( _
    style As PromptStyle _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim style As PromptStyle

instance.StartStyle(style)
C#
public void StartStyle(
    PromptStyle style
)

Parameters

style
Type: Microsoft.Speech.Synthesis..::..PromptStyle

The style to start.

Remarks

The StartStyle(PromptStyle) method takes a PromptStyle object as its argument. You can use the properties of the PromptStyle object to set the emphasis, speaking rate, and volume (loudness) to apply to speech output while the style is in effect. To stop using the current style, call the EndStyle()()()() method.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartVoice Method

[image] [image]

PromptBuilder..::..StartVoice Method
PromptBuilder Class See Also Send Feedback

Instructs the synthesizer to change the voice in a PromptBuilder object.

Overload List

 | Name | Description
Public method | StartVoice(CultureInfo) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the culture of the voice to use.
Public method | StartVoice(String) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the name of the voice to use.
Public method | StartVoice(VoiceGender) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the gender of the voice to use.
Public method | StartVoice(VoiceInfo) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies criteria for the new voice.
Public method | StartVoice(VoiceGender, VoiceAge) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the gender and the age of the voice to use.
Public method | StartVoice(VoiceGender, VoiceAge, Int32) | Instructs the synthesizer to change the voice in the PromptBuilder object and specifies its gender, age, and a preferred voice that matches the specified gender and age.
Top

Remarks

Use the GetInstalledVoices()()()() methods and VoiceInfo class to obtain the names and attributes of installed text-to-speech (TTS) voices that you can select. When an application calls GetInstalledVoices()()()(), the method verifies that each of the voices it finds in the registry meets certain minimum criteria. For any voice that fails verification, GetInstalledVoices()()()() sets its Enabled property to False. An application cannot call any of the StartVoice()()()() methods on a voice whose Enabled property is False. Typically, applications will not set a voice's Enabled property.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartVoice Method (CultureInfo)

[image]

PromptBuilder..::..StartVoice Method (CultureInfo)
PromptBuilder Class Example See Also Send Feedback

Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the culture of the voice to use.

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

Syntax

Visual Basic (Declaration)
Public Sub StartVoice ( _
    culture As CultureInfo _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim culture As CultureInfo

instance.StartVoice(culture)
C#
public void StartVoice(
    CultureInfo culture
)

Parameters

culture
Type: System.Globalization..::..CultureInfo

Provides information about a specific culture, such as the language, the name of the culture, the writing system, the calendar used, and how to format dates and sort strings.

Remarks

If a voice with the specified culture is found, it will be used. If a voice with the specified culture cannot be found, the default voice will be used.

Use the GetInstalledVoices()()()() methods and VoiceInfo class to obtain the names and attributes of installed text-to-speech (TTS) voices that you can select.

For a given language code specified in the culture parameter, a speech synthesis engine that supports that language code must be installed to correctly pronounce words in the specified language.

The Microsoft Speech Platform Runtime 11 and Microsoft Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech. See InstalledVoice for more information.

The Speech Platform SDK 11 accepts all valid language-country codes as values for culture. See Language Identifier Constants and Strings for a comprehensive list of language codes.

Note Note

Speech synthesis is often referred to as text-to-speech or TTS. An installed TTS engine is also referred to as a voice. A language pack for speech synthesis contains a TTS engine, or voice.

Examples

The following example creates a PromptBuilder object that presents menu options; beginning in English, then in French, and finishing in German. Correct pronunciation for each phrase will only be achieved if language packs for English, French, and German have been installed. The SpeechSynthesizer object automatically selects and uses the default voice for the language specified in the culture parameter of the StartVoice(CultureInfo) method.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\test\cultures.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\test\cultures.wav");

        PromptBuilder cultures = new PromptBuilder(
          new System.Globalization.CultureInfo("en-US"));

        // Present menu options in English, French, and German.
        cultures.AppendText("For English, press 1.");

        cultures.StartVoice(new System.Globalization.CultureInfo("fr-FR"));
        cultures.AppendText("Pour le français, appuyez sur 2");
        cultures.EndVoice();

        cultures.StartVoice(new System.Globalization.CultureInfo("de-DE"));
        cultures.AppendText("Für deutsche, drücken Sie 3");
        cultures.EndVoice();

        // Speak the prompt and play back the output file.
        synth.Speak(cultures);
        m_SoundPlayer.Play();
      }
      Console.WriteLine();
      Console.WriteLine("Press any key to exit...");
      Console.ReadKey();
    }
  }
}

See Also

Reference

PromptBuilder Class
PromptBuilder Members
StartVoice Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartVoice Method (String)

[image]

PromptBuilder..::..StartVoice Method (String)
PromptBuilder Class Example See Also Send Feedback

Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the name of the voice to use.

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

Syntax

Visual Basic (Declaration)
Public Sub StartVoice ( _
    name As String _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim name As String

instance.StartVoice(name)
C#
public void StartVoice(
    string name
)

Parameters

name
Type: System..::..String

The name of the voice to use.

Remarks

Use the GetInstalledVoices()()()() methods and VoiceInfo class to obtain the names and attributes of installed text-to-speech (TTS) voices that you can select.

Examples

To specify a voice, the name parameter must contain the exact and entire contents of the Name property. The following code fragment initializes a PromptBuilder in English and changes the voice to French.

Copy image Copy Code
// Change the voice to French in a PromptBuilder.
PromptBuilder builder = new PromptBuilder(
  new System.Globalization.CultureInfo("en-US"));
builder.StartVoice(
  "Microsoft Server Speech Text to Speech Voice (fr-FR, Hortense)");
builder.AppendText("Nous sommes arrivé");
builder.EndVoice();

See Also

Reference

PromptBuilder Class
PromptBuilder Members
StartVoice Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartVoice Method (VoiceGender)

[image]

PromptBuilder..::..StartVoice Method (VoiceGender)
PromptBuilder Class See Also Send Feedback

Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the gender of the voice to use.

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

Syntax

Visual Basic (Declaration)
Public Sub StartVoice ( _
    gender As VoiceGender _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim gender As VoiceGender

instance.StartVoice(gender)
C#
public void StartVoice(
    VoiceGender gender
)

Parameters

gender
Type: Microsoft.Speech.Synthesis..::..VoiceGender

The gender of the voice to use.

Remarks

Use the GetInstalledVoices()()()() methods and VoiceInfo class to obtain the names and attributes of installed text-to-speech (TTS) voices that you can select.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
StartVoice Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartVoice Method (VoiceInfo)

[image]

PromptBuilder..::..StartVoice Method (VoiceInfo)
PromptBuilder Class See Also Send Feedback

Instructs the synthesizer to change the voice in the PromptBuilder object and specifies criteria for the new voice.

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

Syntax

Visual Basic (Declaration)
Public Sub StartVoice ( _
    voice As VoiceInfo _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim voice As VoiceInfo

instance.StartVoice(voice)
C#
public void StartVoice(
    VoiceInfo voice
)

Parameters

voice
Type: Microsoft.Speech.Synthesis..::..VoiceInfo

The criteria for the voice to use.

Remarks

Use the GetInstalledVoices()()()() methods and VoiceInfo class to obtain the names and attributes of installed text-to-speech (TTS) voices that you can select.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
StartVoice Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartVoice Method (VoiceGender, VoiceAge)

[image]

PromptBuilder..::..StartVoice Method (VoiceGender, VoiceAge)
PromptBuilder Class See Also Send Feedback

Instructs the synthesizer to change the voice in the PromptBuilder object and specifies the gender and the age of the voice to use.

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

Syntax

Visual Basic (Declaration)
Public Sub StartVoice ( _
    gender As VoiceGender, _
    age As VoiceAge _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim gender As VoiceGender
Dim age As VoiceAge

instance.StartVoice(gender, age)
C#
public void StartVoice(
    VoiceGender gender,
    VoiceAge age
)

Parameters

gender
Type: Microsoft.Speech.Synthesis..::..VoiceGender

The gender of the voice to use.

age
Type: Microsoft.Speech.Synthesis..::..VoiceAge

The age of the voice to use.

Remarks

Use the GetInstalledVoices()()()() methods and VoiceInfo class to obtain the names and attributes of installed text-to-speech (TTS) voices that you can select.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
StartVoice Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StartVoice Method (VoiceGender, VoiceAge, Int32)

[image]

PromptBuilder..::..StartVoice Method (VoiceGender, VoiceAge, Int32)
PromptBuilder Class See Also Send Feedback

Instructs the synthesizer to change the voice in the PromptBuilder object and specifies its gender, age, and a preferred voice that matches the specified gender and age.

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

Syntax

Visual Basic (Declaration)
Public Sub StartVoice ( _
    gender As VoiceGender, _
    age As VoiceAge, _
    voiceAlternate As Integer _
)
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim gender As VoiceGender
Dim age As VoiceAge
Dim voiceAlternate As Integer

instance.StartVoice(gender, age, voiceAlternate)
C#
public void StartVoice(
    VoiceGender gender,
    VoiceAge age,
    int voiceAlternate
)

Parameters

gender
Type: Microsoft.Speech.Synthesis..::..VoiceGender

The gender of the voice to use.

age
Type: Microsoft.Speech.Synthesis..::..VoiceAge

The age of the voice to use.

voiceAlternate
Type: System..::..Int32

An integer that specifies a preferred voice when more than one voice matches the gender and age parameters.

Remarks

A speech synthesis engine counts the matches it finds for the specified parameters, and returns the voice when the count equals the voiceAlternate parameter.

Use the GetInstalledVoices()()()() methods and VoiceInfo class to obtain the names and attributes of installed text-to-speech (TTS) voices that you can select.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
StartVoice Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ToXml Method

[image]

PromptBuilder..::..ToXml Method
PromptBuilder Class See Also Send Feedback

Returns the SSML generated from the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Function ToXml As String
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim returnValue As String

returnValue = instance.ToXml()
C#
public string ToXml()

Return Value

Type: System..::..String

Returns the SSML generated from the PromptBuilder object as a single line.

Remarks

The ToXml method makes no attempt to format the returned SSML in any way.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptBuilder Properties

[image] [image]

PromptBuilder Properties
PromptBuilder Class See Also Send Feedback

The PromptBuilder type exposes the following members.

Properties

 | Name | Description
Public property | Culture | Gets or sets the culture information for the PromptBuilder object.
Public property | Id | Gets or sets a value that is the identifier for a PromptBuilder instance.
Public property | IsEmpty | Gets whether the PromptBuilder is empty.
Top

See Also

Reference

PromptBuilder Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Culture Property

[image]

PromptBuilder..::..Culture Property
PromptBuilder Class See Also Send Feedback

Gets or sets the culture information for the PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Property Culture As CultureInfo
    Get
    Set
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim value As CultureInfo

value = instance.Culture

instance.Culture = value
C#
public CultureInfo Culture { get; set; }

Property Value

Type: System.Globalization..::..CultureInfo

Remarks

The Microsoft Speech Platform SDK 11 accepts all valid language-country codes as values for Culture. For a given language code specified in the Culture property, a speech synthesis engine that supports that language code must be installed to correctly pronounce words in the specified language.

If the Culture property specifies only a language code, (such as "en" for English or "es" for Spanish), and not a country/region code, then any installed speech synthesis voice that expresses support for that generic, region-independent language may produce acceptable pronunciations for words in the specified language. See Language Identifier Constants and Strings for a comprehensive list of language codes.

Note Note

Speech synthesis is often referred to as text-to-speech or TTS. An installed TTS engine is also referred to as a voice. A language pack for speech synthesis contains a TTS engine, or voice.

The Microsoft Speech Platform Runtime 11 and Microsoft Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech.

The language packs are different for each version of the Speech Platform Runtime. You must download the language pack version that matches the version of the Speech Platform Runtime that you have installed. The language packs for the Speech Platform SDK 11 are for server-based applications and are different than the languages that ship with Windows Vista or Windows 7. Use the following links to download the version of the server language packs that match your Speech Platform Runtime version:

  • Server Language Packs v11.0

  • Server Language Packs v10.2

  • Server Language Packs v10.1

  • Server Language Packs v10.0

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Id Property

[image]

PromptBuilder..::..Id Property
PromptBuilder Class See Also Send Feedback

Gets or sets a value that is the identifier for a PromptBuilder instance.

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

Syntax

Visual Basic (Declaration)
Public Property Id As String
    Get
    Set
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim value As String

value = instance.Id

instance.Id = value
C#
public string Id { get; set; }

Property Value

Type: System..::..String

Returns the identifier for PromptBuilder instance.

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


IsEmpty Property

[image]

PromptBuilder..::..IsEmpty Property
PromptBuilder Class See Also Send Feedback

Gets whether the PromptBuilder is empty.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property IsEmpty As Boolean
    Get
Visual Basic (Usage)
Dim instance As PromptBuilder
Dim value As Boolean

value = instance.IsEmpty
C#
public bool IsEmpty { get; }

Property Value

Type: System..::..Boolean

See Also

Reference

PromptBuilder Class
PromptBuilder Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptEmphasis Enumeration

[image]

PromptEmphasis Enumeration
See Also Send Feedback

Enumerates values for the levels of speaking emphasis in prompts.

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

Syntax

Visual Basic (Declaration)
Public Enumeration PromptEmphasis
Visual Basic (Usage)
Dim instance As PromptEmphasis
C#
public enum PromptEmphasis

Members

Member name | Description
NotSet | Indicates that no emphasis value is specified.
Strong | Indicates a strong level of emphasis.
Moderate | Indicates a moderate level of emphasis.
None | Indicates no emphasis.
Reduced | Indicates a reduced level of emphasis.

Remarks

Members of the PromptEmphasis enumeration are used by the PromptStyle(PromptEmphasis) constructor, by the AppendText(String, PromptEmphasis) method, and by the StartStyle(PromptStyle) method to specify the level of emphasis for spoken text. The Emphasis property gets the emphasis for a PromptStyle object using a PromptEmphasis instance.

See Also

Reference

Microsoft.Speech.Synthesis Namespace
Prompt
PromptBuilder
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptEventArgs Class

[image]

PromptEventArgs Class
Members See Also Send Feedback

Represents the base class for EventArgs classes in the Microsoft.Speech.Synthesis namespace.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
System.ComponentModel..::..AsyncCompletedEventArgs
Microsoft.Speech.Synthesis..::..PromptEventArgs
Microsoft.Speech.Synthesis..::..BookmarkReachedEventArgs
Microsoft.Speech.Synthesis..::..ProprietaryEngineEventArgs
Microsoft.Speech.Synthesis..::..SpeakCompletedEventArgs
Microsoft.Speech.Synthesis..::..SpeakProgressEventArgs
Microsoft.Speech.Synthesis..::..SpeakStartedEventArgs
Microsoft.Speech.Synthesis..::..VoiceChangeEventArgs

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

Syntax

Visual Basic (Declaration)
Public MustInherit Class PromptEventArgs _
    Inherits AsyncCompletedEventArgs
Visual Basic (Usage)
Dim instance As PromptEventArgs
C#
public abstract class PromptEventArgs : AsyncCompletedEventArgs

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

PromptEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptEventArgs Members

[image] [image]

PromptEventArgs Members
PromptEventArgs Class Methods Properties See Also Send Feedback

Represents the base class for EventArgs classes in the Microsoft.Speech.Synthesis namespace.

The PromptEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Prompt | Gets the prompt associated with the event.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

PromptEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptEventArgs Methods

[image] [image]

PromptEventArgs Methods
PromptEventArgs Class See Also Send Feedback

The PromptEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

PromptEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptEventArgs Properties

[image] [image]

PromptEventArgs Properties
PromptEventArgs Class See Also Send Feedback

The PromptEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Prompt | Gets the prompt associated with the event.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

See Also

Reference

PromptEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Prompt Property

[image]

PromptEventArgs..::..Prompt Property
PromptEventArgs Class See Also Send Feedback

Gets the prompt associated with the event.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Prompt As Prompt
    Get
Visual Basic (Usage)
Dim instance As PromptEventArgs
Dim value As Prompt

value = instance.Prompt
C#
public Prompt Prompt { get; }

Property Value

Type: Microsoft.Speech.Synthesis..::..Prompt

The Prompt object associated with the event.

See Also

Reference

PromptEventArgs Class
PromptEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptRate Enumeration

[image]

PromptRate Enumeration
See Also Send Feedback

Enumerates values for the speaking rate of prompts.

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

Syntax

Visual Basic (Declaration)
Public Enumeration PromptRate
Visual Basic (Usage)
Dim instance As PromptRate
C#
public enum PromptRate

Members

Member name | Description
NotSet | Indicates no rate is specified.
ExtraFast | Indicates an extra-fast rate.
Fast | Indicates a fast rate.
Medium | Indicates a medium rate.
Slow | Indicates a slow rate.
ExtraSlow | Indicates an extra-slow rate.

Remarks

Members of the PromptRate enumeration are used by the PromptStyle(PromptRate) constructor, by the AppendText(String, PromptRate) method, and by the StartStyle(PromptStyle) method to specify the rate of speech for spoken text. The Rate property gets the rate for a PromptStyle object using a PromptRate instance.

See Also

Reference

Microsoft.Speech.Synthesis Namespace
Prompt
PromptBuilder
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptStyle Class

[image]

PromptStyle Class
Members See Also Send Feedback

Defines a style for speaking prompts that consists of settings for emphasis, rate, and volume.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Synthesis..::..PromptStyle

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class PromptStyle
Visual Basic (Usage)
Dim instance As PromptStyle
C#
[SerializableAttribute]
public sealed class PromptStyle

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

PromptStyle Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptStyle Members

[image] [image]

PromptStyle Members
PromptStyle Class Constructors Methods Properties See Also Send Feedback

Defines a style for speaking prompts that consists of settings for emphasis, rate, and volume.

The PromptStyle type exposes the following members.

Constructors

 | Name | Description
Public method | PromptStyle()()()() | Initializes a new instance of the PromptStyle class.
Public method | PromptStyle(PromptEmphasis) | Initializes a new instance of the PromptStyle class and specifies the setting for the emphasis of the style.
Public method | PromptStyle(PromptRate) | Initializes a new instance of the PromptStyle class and specifies the setting for the speaking rate of the style.
Public method | PromptStyle(PromptVolume) | Initializes a new instance of the PromptStyle class and specifies the setting for the speaking volume of the style.
Top

Properties

 | Name | Description
Public property | Emphasis | Gets or sets the setting for the emphasis of the style.
Public property | Rate | Gets or sets the setting for the speaking rate of the style.
Public property | Volume | Gets or sets the setting for the volume (loudness) of the style.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

PromptStyle Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptStyle Constructor

[image] [image]

PromptStyle Constructor
PromptStyle Class See Also Send Feedback

Initializes a new instance of the PromptStyle class.

Overload List

 | Name | Description
Public method | PromptStyle()()()() | Initializes a new instance of the PromptStyle class.
Public method | PromptStyle(PromptEmphasis) | Initializes a new instance of the PromptStyle class and specifies the setting for the emphasis of the style.
Public method | PromptStyle(PromptRate) | Initializes a new instance of the PromptStyle class and specifies the setting for the speaking rate of the style.
Public method | PromptStyle(PromptVolume) | Initializes a new instance of the PromptStyle class and specifies the setting for the speaking volume of the style.
Top

See Also

Reference

PromptStyle Class
PromptStyle Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptStyle Constructor

[image]

PromptStyle Constructor
PromptStyle Class See Also Send Feedback

Initializes a new instance of the PromptStyle class.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New PromptStyle()
C#
public PromptStyle()

See Also

Reference

PromptStyle Class
PromptStyle Members
PromptStyle Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptStyle Constructor (PromptEmphasis)

[image]

PromptStyle Constructor (PromptEmphasis)
PromptStyle Class See Also Send Feedback

Initializes a new instance of the PromptStyle class and specifies the setting for the emphasis of the style.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    emphasis As PromptEmphasis _
)
Visual Basic (Usage)
Dim emphasis As PromptEmphasis

Dim instance As New PromptStyle(emphasis)
C#
public PromptStyle(
    PromptEmphasis emphasis
)

Parameters

emphasis
Type: Microsoft.Speech.Synthesis..::..PromptEmphasis

The setting for the emphasis of the style.

See Also

Reference

PromptStyle Class
PromptStyle Members
PromptStyle Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptStyle Constructor (PromptRate)

[image]

PromptStyle Constructor (PromptRate)
PromptStyle Class See Also Send Feedback

Initializes a new instance of the PromptStyle class and specifies the setting for the speaking rate of the style.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    rate As PromptRate _
)
Visual Basic (Usage)
Dim rate As PromptRate

Dim instance As New PromptStyle(rate)
C#
public PromptStyle(
    PromptRate rate
)

Parameters

rate
Type: Microsoft.Speech.Synthesis..::..PromptRate

The setting for the speaking rate of the style.

See Also

Reference

PromptStyle Class
PromptStyle Members
PromptStyle Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptStyle Constructor (PromptVolume)

[image]

PromptStyle Constructor (PromptVolume)
PromptStyle Class See Also Send Feedback

Initializes a new instance of the PromptStyle class and specifies the setting for the speaking volume of the style.

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

Syntax

Visual Basic (Declaration)
Public Sub New ( _
    volume As PromptVolume _
)
Visual Basic (Usage)
Dim volume As PromptVolume

Dim instance As New PromptStyle(volume)
C#
public PromptStyle(
    PromptVolume volume
)

Parameters

volume
Type: Microsoft.Speech.Synthesis..::..PromptVolume

The setting for the volume (loudness) of the style.

See Also

Reference

PromptStyle Class
PromptStyle Members
PromptStyle Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptStyle Methods

[image] [image]

PromptStyle Methods
PromptStyle Class See Also Send Feedback

The PromptStyle type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

PromptStyle Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptStyle Properties

[image] [image]

PromptStyle Properties
PromptStyle Class See Also Send Feedback

The PromptStyle type exposes the following members.

Properties

 | Name | Description
Public property | Emphasis | Gets or sets the setting for the emphasis of the style.
Public property | Rate | Gets or sets the setting for the speaking rate of the style.
Public property | Volume | Gets or sets the setting for the volume (loudness) of the style.
Top

See Also

Reference

PromptStyle Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Emphasis Property

[image]

PromptStyle..::..Emphasis Property
PromptStyle Class See Also Send Feedback

Gets or sets the setting for the emphasis of the style.

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

Syntax

Visual Basic (Declaration)
Public Property Emphasis As PromptEmphasis
    Get
    Set
Visual Basic (Usage)
Dim instance As PromptStyle
Dim value As PromptEmphasis

value = instance.Emphasis

instance.Emphasis = value
C#
public PromptEmphasis Emphasis { get; set; }

Property Value

Type: Microsoft.Speech.Synthesis..::..PromptEmphasis

Returns the setting for the emphasis of the style.

See Also

Reference

PromptStyle Class
PromptStyle Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Rate Property

[image]

PromptStyle..::..Rate Property
PromptStyle Class See Also Send Feedback

Gets or sets the setting for the speaking rate of the style.

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

Syntax

Visual Basic (Declaration)
Public Property Rate As PromptRate
    Get
    Set
Visual Basic (Usage)
Dim instance As PromptStyle
Dim value As PromptRate

value = instance.Rate

instance.Rate = value
C#
public PromptRate Rate { get; set; }

Property Value

Type: Microsoft.Speech.Synthesis..::..PromptRate

Returns the setting for the speaking rate of the style.

See Also

Reference

PromptStyle Class
PromptStyle Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Volume Property

[image]

PromptStyle..::..Volume Property
PromptStyle Class See Also Send Feedback

Gets or sets the setting for the volume (loudness) of the style.

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

Syntax

Visual Basic (Declaration)
Public Property Volume As PromptVolume
    Get
    Set
Visual Basic (Usage)
Dim instance As PromptStyle
Dim value As PromptVolume

value = instance.Volume

instance.Volume = value
C#
public PromptVolume Volume { get; set; }

Property Value

Type: Microsoft.Speech.Synthesis..::..PromptVolume

Returns the setting for the volume (loudness) of the style.

See Also

Reference

PromptStyle Class
PromptStyle Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PromptVolume Enumeration

[image]

PromptVolume Enumeration
See Also Send Feedback

Enumerates values for volume levels (loudness) in prompts.

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

Syntax

Visual Basic (Declaration)
Public Enumeration PromptVolume
Visual Basic (Usage)
Dim instance As PromptVolume
C#
public enum PromptVolume

Members

Member name | Description
NotSet | Indicates that the volume level is not set.
Silent | Indicates a muted volume level.
ExtraSoft | Indicates an extra soft volume level.
Soft | Indicates a soft volume level.
Medium | Indicates a medium volume level.
Loud | Indicates a loud volume level.
ExtraLoud | Indicates an extra loud volume level.
Default | Indicates the engine-specific default volume level.

Remarks

Members of the PromptVolume enumeration are used by the PromptStyle(PromptVolume) constructor, by the AppendText(String, PromptVolume) method, and by the StartStyle(PromptStyle) method to specify the volume level for spoken text. The Volume property gets the volume for a PromptStyle object using a PromptVolume instance.

See Also

Reference

Microsoft.Speech.Synthesis Namespace
Prompt
PromptBuilder
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ProprietaryEngineEventArgs Class

[image]

ProprietaryEngineEventArgs Class
Members See Also Send Feedback

Returns data from an event raised by a proprietary speech synthesis engine.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
System.ComponentModel..::..AsyncCompletedEventArgs
Microsoft.Speech.Synthesis..::..PromptEventArgs
Microsoft.Speech.Synthesis..::..ProprietaryEngineEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class ProprietaryEngineEventArgs _
    Inherits PromptEventArgs
Visual Basic (Usage)
Dim instance As ProprietaryEngineEventArgs
C#
public class ProprietaryEngineEventArgs : PromptEventArgs

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

ProprietaryEngineEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ProprietaryEngineEventArgs Members

[image] [image]

ProprietaryEngineEventArgs Members
ProprietaryEngineEventArgs Class Methods Properties See Also Send Feedback

Returns data from an event raised by a proprietary speech synthesis engine.

The ProprietaryEngineEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | EventId | Gets the identifier of the event raised by a proprietary speech synthesis engine.
Public property | Prompt | Gets the prompt associated with the event. (Inherited from PromptEventArgs.)
Public property | ProprietaryData | Gets the data from the event raised by a proprietary speech synthesis engine.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

ProprietaryEngineEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ProprietaryEngineEventArgs Methods

[image] [image]

ProprietaryEngineEventArgs Methods
ProprietaryEngineEventArgs Class See Also Send Feedback

The ProprietaryEngineEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

ProprietaryEngineEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ProprietaryEngineEventArgs Properties

[image] [image]

ProprietaryEngineEventArgs Properties
ProprietaryEngineEventArgs Class See Also Send Feedback

The ProprietaryEngineEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | EventId | Gets the identifier of the event raised by a proprietary speech synthesis engine.
Public property | Prompt | Gets the prompt associated with the event. (Inherited from PromptEventArgs.)
Public property | ProprietaryData | Gets the data from the event raised by a proprietary speech synthesis engine.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

See Also

Reference

ProprietaryEngineEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


EventId Property

[image]

ProprietaryEngineEventArgs..::..EventId Property
ProprietaryEngineEventArgs Class See Also Send Feedback

Gets the identifier of the event raised by a proprietary speech synthesis engine.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property EventId As Integer
    Get
Visual Basic (Usage)
Dim instance As ProprietaryEngineEventArgs
Dim value As Integer

value = instance.EventId
C#
public int EventId { get; }

Property Value

Type: System..::..Int32

See Also

Reference

ProprietaryEngineEventArgs Class
ProprietaryEngineEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ProprietaryData Property

[image]

ProprietaryEngineEventArgs..::..ProprietaryData Property
ProprietaryEngineEventArgs Class See Also Send Feedback

Gets the data from the event raised by a proprietary speech synthesis engine.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property ProprietaryData As IntPtr
    Get
Visual Basic (Usage)
Dim instance As ProprietaryEngineEventArgs
Dim value As IntPtr

value = instance.ProprietaryData
C#
public IntPtr ProprietaryData { get; }

Property Value

Type: System..::..IntPtr

See Also

Reference

ProprietaryEngineEventArgs Class
ProprietaryEngineEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SayAs Enumeration

[image]

SayAs Enumeration
See Also Send Feedback

Enumerates the content types for the speaking of elements such as times, dates, and currency.

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

Syntax

Visual Basic (Declaration)
Public Enumeration SayAs
Visual Basic (Usage)
Dim instance As SayAs
C#
public enum SayAs

Members

Member name | Description
SpellOut | Spell the word. For example, say "clock" as "C L O C K".
NumberOrdinal | Speak a number as an ordinal number. For example, speak "3rd" as "third".
NumberCardinal | Speak a number as a cardinal number. For example, speak "3" as "three."
Date | Speak a number sequence as a date. For example, speak "05/19/2004" or "19.5.2004" as "may nineteenth two thousand four".
DayMonthYear | Speak a number sequence as a date including the day, month, and year. For example, speak "12/05/2004" as "May twelfth two thousand four".
MonthDayYear | Speak a number sequence as a date including the day, month, and year. For example, speak "12/05/2004" as "December fifth two thousand four".
YearMonthDay | Speak a number sequence as a date including the day, month, and year. For example, speak "2004/05/12" as "May twelfth two thousand four".
YearMonth | Speak a number sequence as a year and month. For example, speak "2004/05" as "May two thousand four".
MonthYear | Speak a number sequence as a month and year. For example, speak "05/2004" as "May two thousand four".
MonthDay | Speak a number sequence as a month and day. For example, speak "05/12" as "may twelfth", and speak "12/5" as "December 5th".
DayMonth | Speak a number sequence as a day and month. For example, speak "12/05" as "May twelfth", and speak "05/12" as "December 5th".
Year | Speak a number as a year. For example, speak "1998" as "nineteen ninety-eight".
Month | Speak a word as a month. For example, speak "June" as "June".
Day | Speak a number as the day in a date. For example, speak "3rd" as "third".
Time | Speak a number sequence as a time. For example, speak "9:45" as "nine forty-five", and speak "9:45am" as "nine forty-five A M".
Time24 | Speak a number sequence as a time using the 24-hour clock. For example, speak "18:00" as "eighteen hundred hours".
Time12 | Speak a number sequence as a time using the 12-hour clock. For example, speak "03:25" as "three twenty-five".
Telephone | Speak a number sequence as a U.S. telephone number. For example, speak "(306) 555-1212" as "Area code three zero six five five five one two one two".
Currency | Speak a number as an amount of currency. For example, speak "$514.97" as five hundred fourteen dollars and 97 cents.
Text | Speak the word or phrase as text. For example, speak "timeline" as "timeline".

Remarks

The AppendTextWithHint(String, SayAs) method uses members of the SayAs enumeration to specify the content type of the appended text, which the speech synthesis engine can use to inform its pronunciation.

See Also

Reference

Microsoft.Speech.Synthesis Namespace
AppendTextWithHint(String, SayAs)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakCompletedEventArgs Class

[image]

SpeakCompletedEventArgs Class
Members See Also Send Feedback

Returns notification from the SpeakCompleted event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
System.ComponentModel..::..AsyncCompletedEventArgs
Microsoft.Speech.Synthesis..::..PromptEventArgs
Microsoft.Speech.Synthesis..::..SpeakCompletedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class SpeakCompletedEventArgs _
    Inherits PromptEventArgs
Visual Basic (Usage)
Dim instance As SpeakCompletedEventArgs
C#
public class SpeakCompletedEventArgs : PromptEventArgs

Remarks

The SpeakCompletedEventArgs class has no properties, and does not return data from the SpeakCompleted event. It is provided to enable application authors to write event handlers for the SpeakCompleted event. The SpeechSynthesizer raises the SpeakCompleted event at the completion of any of the SpeakAsync()()()() or SpeakSsmlAsync(String) methods.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SpeakCompletedEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakCompletedEventArgs Members

[image] [image]

SpeakCompletedEventArgs Members
SpeakCompletedEventArgs Class Methods Properties See Also Send Feedback

Returns notification from the SpeakCompleted event.

The SpeakCompletedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Prompt | Gets the prompt associated with the event. (Inherited from PromptEventArgs.)
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeakCompletedEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakCompletedEventArgs Methods

[image] [image]

SpeakCompletedEventArgs Methods
SpeakCompletedEventArgs Class See Also Send Feedback

The SpeakCompletedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeakCompletedEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakCompletedEventArgs Properties

[image] [image]

SpeakCompletedEventArgs Properties
SpeakCompletedEventArgs Class See Also Send Feedback

The SpeakCompletedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Prompt | Gets the prompt associated with the event. (Inherited from PromptEventArgs.)
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

See Also

Reference

SpeakCompletedEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakProgressEventArgs Class

[image]

SpeakProgressEventArgs Class
Members Example See Also Send Feedback

Returns data from the SpeakProgress event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
System.ComponentModel..::..AsyncCompletedEventArgs
Microsoft.Speech.Synthesis..::..PromptEventArgs
Microsoft.Speech.Synthesis..::..SpeakProgressEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class SpeakProgressEventArgs _
    Inherits PromptEventArgs
Visual Basic (Usage)
Dim instance As SpeakProgressEventArgs
C#
public class SpeakProgressEventArgs : PromptEventArgs

Remarks

An instance of SpeakProgressEventArgs is created when the SpeechSynthesizer object raises the SpeakProgress event. The SpeechSynthesizer raises this event for each new word that it speaks in a prompt using any of the Speak()()()(), SpeakAsync()()()(), SpeakSsml(String), or SpeakSsmlAsync(String) methods.

The returned data is based on the Speech Synthesis Markup Language (SSML) that the code generates. The values returned for CharacterCount include spaces and the characters and contents of the SSML tags generated by the code.

Examples

The following example demonstrates the information that is available from SpeakProgressEventArgs. Note how the StartParagraph()()()(), EndParagraph()()()(), StartSentence()()()(), and EndSentence()()()() methods affect the CharacterCount by their addition of <p>, </p>, <s>, and </s> tags to the generated SSML. Also, there are two entries in the output for "30%", one for each word to speak this number string (thirty percent). The CharacterCount and CharacterPosition are the same for each entry and represent the characters "30%. However, the AudioPosition changes to reflect the speaking of the words "thirty" and "percent" by the SpeechSynthesizer.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\test\weather.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\test\weather.wav");

        // Build a prompt containing a paragraph and two sentences.
        PromptBuilder builder = new PromptBuilder(
          new System.Globalization.CultureInfo("en-US"));
        builder.StartParagraph();
        builder.StartSentence();
        builder.AppendText(
          "The weather forecast for today is partly cloudy with some sun breaks.");
        builder.EndSentence();
        builder.StartSentence();
        builder.AppendText(
          "Tonight's weather will be cloudy with a 30% chance of showers.");
        builder.EndSentence();
        builder.EndParagraph();

        // Add a handler for the SpeakProgress event.
        synth.SpeakProgress +=
          new EventHandler<SpeakProgressEventArgs>(synth_SpeakProgress);

        // Speak the prompt and play back the output file.
        synth.Speak(builder);
        m_SoundPlayer.Play();
      }

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

    // Write each word and its character postion to the console.
    static void synth_SpeakProgress(object sender, SpeakProgressEventArgs e)
    {
      Console.WriteLine("CharPos: {0}   CharCount: {1}   AudioPos: {2}    \"{3}\"",
        e.CharacterPosition, e.CharacterCount, e.AudioPosition, e.Text);
    }
  }
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SpeakProgressEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakProgressEventArgs Members

[image] [image]

SpeakProgressEventArgs Members
SpeakProgressEventArgs Class Methods Properties See Also Send Feedback

Returns data from the SpeakProgress event.

The SpeakProgressEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioPosition | Gets the audio position of the event.
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | CharacterCount | Gets the number of characters in the word that was spoken just before the event was raised.
Public property | CharacterPosition | Gets the number of characters and spaces from the beginning of the prompt to the position before the first letter of the word that was just spoken.
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Prompt | Gets the prompt associated with the event. (Inherited from PromptEventArgs.)
Public property | Text | The text that was just spoken when the event was raised.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeakProgressEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakProgressEventArgs Methods

[image] [image]

SpeakProgressEventArgs Methods
SpeakProgressEventArgs Class See Also Send Feedback

The SpeakProgressEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeakProgressEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakProgressEventArgs Properties

[image] [image]

SpeakProgressEventArgs Properties
SpeakProgressEventArgs Class See Also Send Feedback

The SpeakProgressEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | AudioPosition | Gets the audio position of the event.
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | CharacterCount | Gets the number of characters in the word that was spoken just before the event was raised.
Public property | CharacterPosition | Gets the number of characters and spaces from the beginning of the prompt to the position before the first letter of the word that was just spoken.
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Prompt | Gets the prompt associated with the event. (Inherited from PromptEventArgs.)
Public property | Text | The text that was just spoken when the event was raised.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

See Also

Reference

SpeakProgressEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AudioPosition Property

[image]

SpeakProgressEventArgs..::..AudioPosition Property
SpeakProgressEventArgs Class See Also Send Feedback

Gets the audio position of the event.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AudioPosition As TimeSpan
    Get
Visual Basic (Usage)
Dim instance As SpeakProgressEventArgs
Dim value As TimeSpan

value = instance.AudioPosition
C#
public TimeSpan AudioPosition { get; }

Property Value

Type: System..::..TimeSpan

Returns the position of the event in the audio output stream.

Remarks

The SpeechSynthesizer normalizes numbers to the words that correspond to how the number will be spoken. For example, the synthesizer speaks the number "4003" as "four thousand three". It raises a SpeakProgress event for each of the spoken words, and returns the AudioPosition for each word.

See Also

Reference

SpeakProgressEventArgs Class
SpeakProgressEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


CharacterCount Property

[image]

SpeakProgressEventArgs..::..CharacterCount Property
SpeakProgressEventArgs Class See Also Send Feedback

Gets the number of characters in the word that was spoken just before the event was raised.

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

Syntax

Visual Basic (Declaration)
Public Property CharacterCount As Integer
    Get
    Friend Set
Visual Basic (Usage)
Dim instance As SpeakProgressEventArgs
Dim value As Integer

value = instance.CharacterCount
C#
public int CharacterCount { get; internal set; }

Property Value

Type: System..::..Int32

Returns the number of characters in the word that was spoken just before the event was raised.

Remarks

The SpeechSynthesizer normalizes numbers to the words that correspond to how the number will be spoken. For example, the synthesizer speaks the number "4003" as "four thousand three". It raises a SpeakProgress event for each of the spoken words. However, the CharacterCount property for each of the three words is the same. It is the count of the characters in the number "4003" in the text of the prompt, in this case, four.

See Also

Reference

SpeakProgressEventArgs Class
SpeakProgressEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


CharacterPosition Property

[image]

SpeakProgressEventArgs..::..CharacterPosition Property
SpeakProgressEventArgs Class Example See Also Send Feedback

Gets the number of characters and spaces from the beginning of the prompt to the position before the first letter of the word that was just spoken.

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

Syntax

Visual Basic (Declaration)
Public Property CharacterPosition As Integer
    Get
    Friend Set
Visual Basic (Usage)
Dim instance As SpeakProgressEventArgs
Dim value As Integer

value = instance.CharacterPosition
C#
public int CharacterPosition { get; internal set; }

Property Value

Type: System..::..Int32

Returns the number of characters and spaces from the beginning of the prompt to the position before the first letter of the word that was just spoken.

Remarks

The CharacterPosition includes the count for characters in XML tags, including their enclosing brackets. When using any of the AppendText()()()(), AppendTextWithAlias(String, String), AppendTextWithHint()()()(), AppendSsmlMarkup(String), or AppendTextWithPronunciation(String, String) methods, the contents are added to an SSML prompt that includes the opening and closing speak elements. The opening speak element adds an offset of 82 characters and spaces to the CharacterPosition of the all the words and letters in the prompt. For example, in the following snippet, the CharacterPosition of the first word, "this", is 82.

C# Copy image Copy Code
builder.AppendText("This is a test");
Synthesizer.Speak(builder);

In the above example the CharacterPosition of the word "test" is 92. In the following snippet the CharacterPosition of the word "test" is ten characters higher (102) because the opening <emphasis> tag that precedes it contains ten characters.

C# Copy image Copy Code
builder.AppendSsmlMarkup("This is a <emphasis>test</emphasis>");
Synthesizer.Speak(builder);

When you use the AppendSsml(XmlReader) method to add content to a prompt by specifying a file, the opening xml declaration and speak elements in the file are not used or counted. The first character in the file after the opening speak tag will be at position 82 if it is the first content in the prompt.

By contrast, the string parameter of a Speak(String) method does not get added to an SSML prompt before being spoken. Therefore, the CharacterPosition of the first word, "this", in the following snippet is zero.

C# Copy image Copy Code
Synthesizer.Speak("This is a test.");

The SpeechSynthesizer normalizes numbers to the words that correspond to how the number will be spoken. For example, the synthesizer speaks the number "4003" as "four thousand three". It raises a SpeakProgress event for each of the three spoken words. However, the CharacterPosition property for each of the three words is the same. It is the position before the first character of the number "4003" in the text of the prompt.

Examples

The following example creates a PromptBuilder and appends the SSML contents of an XML file using XmlReader. The example outputs speech to a WAV file for playback. The contents of the XML file containing the SSML appear below the code example.

C# Copy image Copy Code
using System;
using System.Xml;
using System.IO;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\test\weather.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\test\weather.wav");

        // Create a path to the file that contains SSML.
        string weatherFile = Path.GetFullPath("c:\\test\\Weather.xml");

        // Create an XML Reader from the file, create a PromptBuilder and
        // append the XmlReader.
        PromptBuilder builder = null;

        if (File.Exists(weatherFile))
        {
          XmlReader reader = XmlReader.Create(weatherFile);
          builder = new PromptBuilder();
          builder.AppendSsml(reader);
          reader.Close();
        }

        // Add a handler for the SpeakProgress event.
        synth.SpeakProgress +=
          new EventHandler<SpeakProgressEventArgs>(synth_SpeakProgress);

        // Speak the prompt and play back the output file.
        synth.Speak(builder);
        m_SoundPlayer.Play();
      }

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

    // Write each word and its character postion to the console.
    static void synth_SpeakProgress(object sender, SpeakProgressEventArgs e)
    {
      Console.WriteLine("Speak progress: {0} {1}",
        e.CharacterPosition, e.Text);
    }
  }
}
XML Copy image Copy Code
<!-- The following are the contents of the file Weather.xml.
Note that because of the <p> tag and the space that follows it,
that the character position of the first word "The" will be 86. -->

<?xml version="1.0" encoding="ISO-8859-1"?>
<speak version="1.0"
 xmlns="http://www.w3.org/2001/10/synthesis"
 xml:lang="en-US">

  <p> The weather forecast for today is partly cloudy with
some sun breaks. </p>

  <break strength="medium" />

  <p> Tonight's weather will be cloudy with a 30% chance of
showers. </p>

</speak>

See Also

Reference

SpeakProgressEventArgs Class
SpeakProgressEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Text Property

[image]

SpeakProgressEventArgs..::..Text Property
SpeakProgressEventArgs Class See Also Send Feedback

The text that was just spoken when the event was raised.

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

Syntax

Visual Basic (Declaration)
Public Property Text As String
    Get
    Friend Set
Visual Basic (Usage)
Dim instance As SpeakProgressEventArgs
Dim value As String

value = instance.Text
C#
public string Text { get; internal set; }

Property Value

Type: System..::..String

Returns the text that was just spoken when the event was raised.

Remarks

The SpeechSynthesizer normalizes numbers to the words that correspond to how the number will be spoken. For example, the synthesizer speaks the number "4003" as "four thousand three". It raises a SpeakProgress event for each of the spoken words. However, the Text property for each of the three words is the same. It is the text "4003" from the prompt.

See Also

Reference

SpeakProgressEventArgs Class
SpeakProgressEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakStartedEventArgs Class

[image]

SpeakStartedEventArgs Class
Members See Also Send Feedback

Returns notification from the SpeakStarted event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
System.ComponentModel..::..AsyncCompletedEventArgs
Microsoft.Speech.Synthesis..::..PromptEventArgs
Microsoft.Speech.Synthesis..::..SpeakStartedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class SpeakStartedEventArgs _
    Inherits PromptEventArgs
Visual Basic (Usage)
Dim instance As SpeakStartedEventArgs
C#
public class SpeakStartedEventArgs : PromptEventArgs

Remarks

An instance of SpeakStartedEventArgs is created when the SpeechSynthesizer object raises the SpeakStarted event. The SpeechSynthesizer raises the SpeakStarted event when it begins speaking a prompt using any of the Speak()()()(), SpeakAsync()()()(), SpeakSsml(String), or SpeakSsmlAsync(String) methods.

The SpeakStartedEventArgs class has no properties, and does not return data from the SpeakStarted event. It is provided to enable application authors to write event handlers for the SpeakStarted event.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SpeakStartedEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakStartedEventArgs Members

[image] [image]

SpeakStartedEventArgs Members
SpeakStartedEventArgs Class Methods Properties See Also Send Feedback

Returns notification from the SpeakStarted event.

The SpeakStartedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Prompt | Gets the prompt associated with the event. (Inherited from PromptEventArgs.)
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeakStartedEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakStartedEventArgs Methods

[image] [image]

SpeakStartedEventArgs Methods
SpeakStartedEventArgs Class See Also Send Feedback

The SpeakStartedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeakStartedEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakStartedEventArgs Properties

[image] [image]

SpeakStartedEventArgs Properties
SpeakStartedEventArgs Class See Also Send Feedback

The SpeakStartedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Prompt | Gets the prompt associated with the event. (Inherited from PromptEventArgs.)
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Top

See Also

Reference

SpeakStartedEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechSynthesizer Class

[image]

SpeechSynthesizer Class
Members See Also Send Feedback

Provides access to the functionality of an installed a speech synthesis engine.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Synthesis..::..SpeechSynthesizer

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

Syntax

Visual Basic (Declaration)
Public NotInheritable Class SpeechSynthesizer _
    Implements IDisposable
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
C#
public sealed class SpeechSynthesizer : IDisposable

Remarks

When you create a new SpeechSynthesizer object, it uses the default system voice. To configure the SpeechSynthesizer to use one of the installed speech synthesis (text-to-speech) voices, use the SelectVoice or SelectVoiceByHints method. To get information about which voices are installed, use the GetInstalledVoices method and the VoiceInfo class.

The SpeechSynthesizer can use one or more lexicons to guide its pronunciation of words. To add or remove lexicons, use the AddLexicon and RemoveLexicon methods.

This class also provides control over the following aspects of speech synthesis:

  • To configure the output for the SpeechSynthesizer object, use the SetOutputToAudioStream, SetOutputToDefaultAudioDevice, SetOutputToNull, and SetOutputToWaveFile methods.

  • To generate speech, use the Speak, SpeakAsync, SpeakSsml, or SpeakSsmlAsync method. The SpeechSynthesizer can produce speech from text, a Prompt or PromptBuilder object, or from Speech Synthesis Markup Language (SSML) Version 1.0.

  • To pause and resume speech synthesis, use the Pause and Resume methods.

  • To add or remove lexicons, use the AddLexicon and RemoveLexicon methods. The SpeechSynthesizer can use one or more lexicons to guide its pronunciation of words.

  • To modify the delivery of speech output, use the Rate and Volume properties.

The SpeechSynthesizer raises events when it encounters certain features in prompts: (BookmarkReached and SpeakProgress). It also raises events that report on the start (SpeakStarted) and end (SpeakCompleted) of speak operations and on the change of the speaking voice (VoiceChange).

Note Note

Always call Dispose()()()() before you release your last reference to the SpeechSynthesizer. Otherwise, the resources it is using will not be freed until the garbage collector calls the SpeechSynthesizer object's Finalize()()()() method.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechSynthesizer Members

[image] [image]

SpeechSynthesizer Members
SpeechSynthesizer Class Constructors Methods Properties Events See Also Send Feedback

Provides access to the functionality of an installed a speech synthesis engine.

The SpeechSynthesizer type exposes the following members.

Constructors

 | Name | Description
Public method | SpeechSynthesizer | Initializes a new instance of the SpeechSynthesizer class.
Top

Properties

 | Name | Description
Public property | Rate | Gets or sets the speaking rate of the SpeechSynthesizer object.
Public property | State | Gets the speaking state of the SpeechSynthesizer object.
Public property | TtsVolume | Gets or sets the volume (loudness) of the synthesized speech in the SpeechSynthesizer's audio output.
Public property | Voice | Gets information about the current voice of the SpeechSynthesizer object.
Public property | Volume | Get or sets the output volume of the SpeechSynthesizer object.
Top

Methods

 | Name | Description
Public method | AddLexicon | Adds a lexicon to the SpeechSynthesizer object.
Public method | Dispose | Disposes the SpeechSynthesizer object and releases resources used during the session.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | Acts as a safeguard to clean up resources in the event that the Dispose()()()() method is not called. (Overrides Object..::..Finalize()()()().)
Public method | GetCurrentlySpokenPrompt | Gets the contents of the prompt that the SpeechSynthesizer is speaking.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetInstalledVoices()()()() | Returns all of the installed speech synthesis (text-to-speech) voices.
Public method | GetInstalledVoices(CultureInfo) | Returns all of the installed speech synthesis (text-to-speech) voices that support a specific locale.
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | Pause | Pauses the speaking of a prompt by a SpeechSynthesizer object.
Public method | RemoveLexicon | Removes a lexicon from the SpeechSynthesizer object.
Public method | Resume | Resumes the speaking of a prompt by the SpeechSynthesizer object after it has been paused.
Public method | SelectVoice | Selects a specific voice by name.
Public method | SelectVoiceByHints(VoiceGender) | Selects a voice with a specific gender.
Public method | SelectVoiceByHints(VoiceGender, VoiceAge) | Selects a voice with a specific gender and age.
Public method | SelectVoiceByHints(VoiceGender, VoiceAge, Int32) | Selects a voice with a specific gender and age, based on the position in which the voices are ordered.
Public method | SelectVoiceByHints(VoiceGender, VoiceAge, Int32, CultureInfo) | Selects a voice with a specific gender, age, and locale, based on the position in which the voices are ordered.
Public method | SetOutputToAudioStream | Configures the SpeechSynthesizer object to append output to a stream that contains Waveform format audio.
Public method | SetOutputToDefaultAudioDevice | Configures the SpeechSynthesizer object to send output to the default audio device for the system.
Public method | SetOutputToNull | Configures the SpeechSynthesizer object to not send output from synthesis operations to a device, file, or stream.
Public method | SetOutputToWaveFile(String) | Configures the SpeechSynthesizer object to append output to a file that contains Waveform format audio.
Public method | SetOutputToWaveFile(String, SpeechAudioFormatInfo) | Configures the SpeechSynthesizer object to append output to a Waveform audio format file in a specified format.
Public method | SetOutputToWaveStream | Configures the SpeechSynthesizer object to append output to a stream that contains Waveform format audio.
Public method | Skip | Skips the specified amount of time in a prompt.
Public method | Speak(String) | Synchronously speaks the contents of a string.
Public method | Speak(Prompt) | Synchronously speaks the contents of a Prompt object.
Public method | Speak(PromptBuilder) | Synchronously speaks the contents of a PromptBuilder object.
Public method | SpeakAsync(String) | Asynchronously speaks the contents of a string.
Public method | SpeakAsync(Prompt) | Asynchronously speaks the contents of a Prompt object.
Public method | SpeakAsync(PromptBuilder) | Asynchronously speaks the contents of a PromptBuilder object.
Public method | SpeakAsyncCancel | Cancels the asynchronous synthesis operation for a queued prompt.
Public method | SpeakAsyncCancelAll | Cancels all queued, asynchronous, speech synthesis operations.
Public method | SpeakSsml | Asynchronously speaks a String that contains SSML markup.
Public method | SpeakSsmlAsync | Asynchronously speaks a String that contains SSML markup.
Public method | ToString | (Inherited from Object.)
Top

Events

 | Name | Description
Public event | BookmarkReached | Raised when the SpeechSynthesizer encounters a bookmark in a prompt.
Public event | ProprietaryEngineEvent | This event is for use by developers of custom speech synthesis engines.
Public event | SpeakCompleted | Raised when the SpeechSynthesizer completes the speaking of a prompt.
Public event | SpeakProgress | Raised after the SpeechSynthesizer speaks each individual word of a prompt.
Public event | SpeakStarted | Raised when the SpeechSynthesizer begins the speaking of a prompt.
Public event | StateChanged | Raised when the state of the SpeechSynthesizer changes.
Public event | VoiceChange | Raised when the voice of the SpeechSynthesizer changes.
Top

See Also

Reference

SpeechSynthesizer Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechSynthesizer Constructor

[image]

SpeechSynthesizer Constructor
SpeechSynthesizer Class See Also Send Feedback

Initializes a new instance of the SpeechSynthesizer class.

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

Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New SpeechSynthesizer()
C#
public SpeechSynthesizer()

Remarks

When you initialize a new SpeechSynthesizer instance, it uses the default system voice. To configure the SpeechSynthesizer to use one of the installed speech synthesis (text-to-speech) voices, use the SelectVoice or SelectVoiceByHints method. To get information about which voices are installed, use the GetInstalledVoices method and the VoiceInfo class.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
InstalledVoice
SelectVoice(String)
SelectVoiceByHints
GetInstalledVoices
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechSynthesizer Methods

[image] [image]

SpeechSynthesizer Methods
SpeechSynthesizer Class See Also Send Feedback

The SpeechSynthesizer type exposes the following members.

Methods

 | Name | Description
Public method | AddLexicon | Adds a lexicon to the SpeechSynthesizer object.
Public method | Dispose | Disposes the SpeechSynthesizer object and releases resources used during the session.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | Acts as a safeguard to clean up resources in the event that the Dispose()()()() method is not called. (Overrides Object..::..Finalize()()()().)
Public method | GetCurrentlySpokenPrompt | Gets the contents of the prompt that the SpeechSynthesizer is speaking.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetInstalledVoices()()()() | Returns all of the installed speech synthesis (text-to-speech) voices.
Public method | GetInstalledVoices(CultureInfo) | Returns all of the installed speech synthesis (text-to-speech) voices that support a specific locale.
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | Pause | Pauses the speaking of a prompt by a SpeechSynthesizer object.
Public method | RemoveLexicon | Removes a lexicon from the SpeechSynthesizer object.
Public method | Resume | Resumes the speaking of a prompt by the SpeechSynthesizer object after it has been paused.
Public method | SelectVoice | Selects a specific voice by name.
Public method | SelectVoiceByHints(VoiceGender) | Selects a voice with a specific gender.
Public method | SelectVoiceByHints(VoiceGender, VoiceAge) | Selects a voice with a specific gender and age.
Public method | SelectVoiceByHints(VoiceGender, VoiceAge, Int32) | Selects a voice with a specific gender and age, based on the position in which the voices are ordered.
Public method | SelectVoiceByHints(VoiceGender, VoiceAge, Int32, CultureInfo) | Selects a voice with a specific gender, age, and locale, based on the position in which the voices are ordered.
Public method | SetOutputToAudioStream | Configures the SpeechSynthesizer object to append output to a stream that contains Waveform format audio.
Public method | SetOutputToDefaultAudioDevice | Configures the SpeechSynthesizer object to send output to the default audio device for the system.
Public method | SetOutputToNull | Configures the SpeechSynthesizer object to not send output from synthesis operations to a device, file, or stream.
Public method | SetOutputToWaveFile(String) | Configures the SpeechSynthesizer object to append output to a file that contains Waveform format audio.
Public method | SetOutputToWaveFile(String, SpeechAudioFormatInfo) | Configures the SpeechSynthesizer object to append output to a Waveform audio format file in a specified format.
Public method | SetOutputToWaveStream | Configures the SpeechSynthesizer object to append output to a stream that contains Waveform format audio.
Public method | Skip | Skips the specified amount of time in a prompt.
Public method | Speak(String) | Synchronously speaks the contents of a string.
Public method | Speak(Prompt) | Synchronously speaks the contents of a Prompt object.
Public method | Speak(PromptBuilder) | Synchronously speaks the contents of a PromptBuilder object.
Public method | SpeakAsync(String) | Asynchronously speaks the contents of a string.
Public method | SpeakAsync(Prompt) | Asynchronously speaks the contents of a Prompt object.
Public method | SpeakAsync(PromptBuilder) | Asynchronously speaks the contents of a PromptBuilder object.
Public method | SpeakAsyncCancel | Cancels the asynchronous synthesis operation for a queued prompt.
Public method | SpeakAsyncCancelAll | Cancels all queued, asynchronous, speech synthesis operations.
Public method | SpeakSsml | Asynchronously speaks a String that contains SSML markup.
Public method | SpeakSsmlAsync | Asynchronously speaks a String that contains SSML markup.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

SpeechSynthesizer Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AddLexicon Method

[image]

SpeechSynthesizer..::..AddLexicon Method
SpeechSynthesizer Class See Also Send Feedback

Adds a lexicon to the SpeechSynthesizer object.

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

Syntax

Visual Basic (Declaration)
Public Sub AddLexicon ( _
    uri As Uri, _
    mediaType As String _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim uri As Uri
Dim mediaType As String

instance.AddLexicon(uri, mediaType)
C#
public void AddLexicon(
    Uri uri,
    string mediaType
)

Parameters

uri
Type: System..::..Uri

The location of the lexicon information.

mediaType
Type: System..::..String

The media type of the lexicon. Media type values are not case sensitive.

Remarks

A pronunciation lexicon is a collection of words or phrases together with their pronunciations, which consist of letters and characters from a supported phonetic alphabet. You can add multiple lexicons to a SpeechSynthesizer.

Two values are currently supported for mediaType:

  • The value application/vdn.ms-sapi-lex indicates that the lexicon format is Uncompressed Lexicon, which is specific to the Microsoft Speech API.

  • The value application/pls+xml indicates that the lexicon conforms to the Pronunciation Lexicon Specification (PLS) Version 1.0.

    Pronunciations specified in an external lexicon file take precedence over the pronunciations of the speech synthesizer's internal lexicon or dictionary. However, pronunciations specified inline in prompts created with any of the AppendTextWithPronunciation(String, String), AppendSsmlMarkup(String), or AppendSsml(XmlReader) methods take precedence over pronunciations specified in any lexicon. Inline pronunciations apply only to a single occurrence of a word. For more information, see Lexicons and Phonetic Alphabets (Microsoft.Speech).

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Dispose Method

[image]

SpeechSynthesizer..::..Dispose Method
SpeechSynthesizer Class See Also Send Feedback

Disposes the SpeechSynthesizer object and releases resources used during the session.

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

Syntax

Visual Basic (Declaration)
Public Sub Dispose
Visual Basic (Usage)
Dim instance As SpeechSynthesizer

instance.Dispose()
C#
public void Dispose()

Implements

IDisposable..::..Dispose()()()()

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Finalize Method

[image]

SpeechSynthesizer..::..Finalize Method
SpeechSynthesizer Class See Also Send Feedback

Acts as a safeguard to clean up resources in the event that the Dispose()()()() method is not called.

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

Syntax

Visual Basic (Declaration)
Protected Overrides Sub Finalize
Visual Basic (Usage)
Me.Finalize()
C#
protected override void Finalize()

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetCurrentlySpokenPrompt Method

[image]

SpeechSynthesizer..::..GetCurrentlySpokenPrompt Method
SpeechSynthesizer Class See Also Send Feedback

Gets the contents of the prompt that the SpeechSynthesizer is speaking.

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

Syntax

Visual Basic (Declaration)
Public Function GetCurrentlySpokenPrompt As Prompt
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim returnValue As Prompt

returnValue = instance.GetCurrentlySpokenPrompt()
C#
public Prompt GetCurrentlySpokenPrompt()

Return Value

Type: Microsoft.Speech.Synthesis..::..Prompt

Returns the prompt object that is currently being spoken.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetInstalledVoices Method

[image] [image]

SpeechSynthesizer..::..GetInstalledVoices Method
SpeechSynthesizer Class See Also Send Feedback

Returns the collection of speech synthesis (text-to-speech) voices that are currently installed on the system.

Overload List

 | Name | Description
Public method | GetInstalledVoices()()()() | Returns all of the installed speech synthesis (text-to-speech) voices.
Public method | GetInstalledVoices(CultureInfo) | Returns all of the installed speech synthesis (text-to-speech) voices that support a specific locale.
Top

Remarks

The Microsoft Speech Platform Runtime 11 and Microsoft Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech.

The language packs are different for each version of the Speech Platform Runtime. You must download the language pack version that matches the version of the Speech Platform Runtime that you have installed. The language packs for the Speech Platform SDK 11 are for server-based applications and are different than the languages that ship with Windows Vista or Windows 7. Use the following links to download the version of the server language packs that match your Speech Platform Runtime version:

  • Server Language Packs v11.0

  • Server Language Packs v10.2

  • Server Language Packs v10.1

  • Server Language Packs v10.0

Note Note

Speech synthesis is often referred to as text-to-speech or TTS. An installed TTS engine is also referred to as a voice. A language pack for speech synthesis contains a TTS engine, or voice.

When an application calls GetInstalledVoices()()()(), the method verifies that each of the voices (engines for text-to-speech) it finds in the registry meets certain minimum criteria. For any voice that fails verification, GetInstalledVoices()()()() sets its Enabled property to False. An application cannot select a voice whose Enabled property is False. Typically, applications will not set a voice's Enabled property.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetInstalledVoices Method

[image]

SpeechSynthesizer..::..GetInstalledVoices Method
SpeechSynthesizer Class Example See Also Send Feedback

Returns all of the installed speech synthesis (text-to-speech) voices.

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

Syntax

Visual Basic (Declaration)
Public Function GetInstalledVoices As ReadOnlyCollection(Of InstalledVoice)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim returnValue As ReadOnlyCollection(Of InstalledVoice)

returnValue = instance.GetInstalledVoices()
C#
public ReadOnlyCollection<InstalledVoice> GetInstalledVoices()

Return Value

Type: System.Collections.ObjectModel..::..ReadOnlyCollection <(Of <(<' InstalledVoice >)>)>

Returns a read-only collection of the voices currently installed on the system.

Remarks

A voice is an engine for speech synthesis (text-to-speech or TTS) that is installed on the system.

Examples

The following example is part of a console application that initializes a SpeechSynthesizer object and outputs to the console a list of the installed voices (engines for speech synthesis) and demonstrates the information that is available for each voice.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;
using Microsoft.Speech.AudioFormat;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Output information about all of the installed voices.
        Console.WriteLine("Installed voices -");
        foreach (InstalledVoice voice in synth.GetInstalledVoices())
        {
          VoiceInfo info = voice.VoiceInfo;
          string AudioFormats = "";
          foreach (SpeechAudioFormatInfo fmt in info.SupportedAudioFormats)
          {
            AudioFormats += String.Format("{0}\n",
            fmt.EncodingFormat.ToString());
          }

          Console.WriteLine(" Name:          " + info.Name);
          Console.WriteLine(" Culture:       " + info.Culture);
          Console.WriteLine(" Age:           " + info.Age);
          Console.WriteLine(" Gender:        " + info.Gender);
          Console.WriteLine(" Description:   " + info.Description);
          Console.WriteLine(" ID:            " + info.Id);
          Console.WriteLine(" Enabled:       " + voice.Enabled);
          if (info.SupportedAudioFormats.Count != 0)
          {
            Console.WriteLine( " Audio formats: " + AudioFormats);
          }
          else
          {
            Console.WriteLine(" No supported audio formats found");
          }

          string AdditionalInfo = "";
          foreach (string key in info.AdditionalInfo.Keys)
          {
            AdditionalInfo += String.Format("  {0}: {1}\n", key, info.AdditionalInfo[key]);
          }

          Console.WriteLine(" Additional Info - " + AdditionalInfo);
          Console.WriteLine();
        }
      }
      Console.WriteLine("Press any key to exit...");
      Console.ReadKey();
    }
  }
}

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
GetInstalledVoices Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetInstalledVoices Method (CultureInfo)

[image]

SpeechSynthesizer..::..GetInstalledVoices Method (CultureInfo)
SpeechSynthesizer Class See Also Send Feedback

Returns all of the installed speech synthesis (text-to-speech) voices that support a specific locale.

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

Syntax

Visual Basic (Declaration)
Public Function GetInstalledVoices ( _
    culture As CultureInfo _
) As ReadOnlyCollection(Of InstalledVoice)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim culture As CultureInfo
Dim returnValue As ReadOnlyCollection(Of InstalledVoice)

returnValue = instance.GetInstalledVoices(culture)
C#
public ReadOnlyCollection<InstalledVoice> GetInstalledVoices(
    CultureInfo culture
)

Parameters

culture
Type: System.Globalization..::..CultureInfo

The locale that the voice must support.

Return Value

Type: System.Collections.ObjectModel..::..ReadOnlyCollection <(Of <(<' InstalledVoice >)>)>

Returns a read-only collection of the voices currently installed on the system that support the specified locale.

Remarks

If none of the installed voices support the specified locale, this method returns an empty collection.

The Microsoft Speech Platform SDK 11 accepts all valid language-country codes as values for culture. For a given language code specified in the culture parameter, a speech synthesis engine that supports that language code must be installed to correctly pronounce words in the specified language.

If the culture parameter specifies only a language code, (such as "en" for English or "es" for Spanish), and not a country/region code, then any installed speech synthesis voice that expresses support for that generic, region-independent language may produce acceptable pronunciations for words in the specified language. See Language Identifier Constants and Strings for a comprehensive list of language codes.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
GetInstalledVoices Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Pause Method

[image]

SpeechSynthesizer..::..Pause Method
SpeechSynthesizer Class See Also Send Feedback

Pauses the speaking of a prompt by a SpeechSynthesizer object.

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

Syntax

Visual Basic (Declaration)
Public Sub Pause
Visual Basic (Usage)
Dim instance As SpeechSynthesizer

instance.Pause()
C#
public void Pause()

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
Resume
State
StateChanged
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


RemoveLexicon Method

[image]

SpeechSynthesizer..::..RemoveLexicon Method
SpeechSynthesizer Class See Also Send Feedback

Removes a lexicon from the SpeechSynthesizer object.

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

Syntax

Visual Basic (Declaration)
Public Sub RemoveLexicon ( _
    uri As Uri _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim uri As Uri

instance.RemoveLexicon(uri)
C#
public void RemoveLexicon(
    Uri uri
)

Parameters

uri
Type: System..::..Uri

The location of the lexicon document.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
AddLexicon(Uri, String)

Other Resources

Lexicons and Phonetic Alphabets (Microsoft.Speech)
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Resume Method

[image]

SpeechSynthesizer..::..Resume Method
SpeechSynthesizer Class See Also Send Feedback

Resumes the speaking of a prompt by the SpeechSynthesizer object after it has been paused.

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

Syntax

Visual Basic (Declaration)
Public Sub Resume
Visual Basic (Usage)
Dim instance As SpeechSynthesizer

instance.Resume()
C#
public void Resume()

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
Pause
State
StateChanged
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SelectVoice Method

[image]

SpeechSynthesizer..::..SelectVoice Method
SpeechSynthesizer Class Example See Also Send Feedback

Selects a specific voice by name.

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

Syntax

Visual Basic (Declaration)
Public Sub SelectVoice ( _
    name As String _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim name As String

instance.SelectVoice(name)
C#
public void SelectVoice(
    string name
)

Parameters

name
Type: System..::..String

The name of the voice to select.

Remarks

Use the GetInstalledVoices method and VoiceInfo class to obtain the names of installed text-to-speech (TTS) voices that you can select. To select a voice, pass the entire contents of the Name property as the argument for the SelectVoice(String) method. The SpeechSynthesizer object selects the first installed voice that contains name in the voice's VoiceInfo..::..Name property. The SpeechSynthesizer performs a case-sensitive, substring comparison to determine if the voice matches the name.

Typically, you will select a voice whose Culture property matches the culture parameter that is specified in the content to speak. You can specify a culture parameter for content to be spoken using the PromptBuilder(CultureInfo) constructor or the StartParagraph(CultureInfo) or StartSentence(CultureInfo) method. If authoring in Speech Synthesis Markup Language (SSML), you specify the culture using the xml:lang attribute.

When an application calls GetInstalledVoices()()()(), the method verifies that each of the voices it finds in the registry meets certain minimum criteria. For any voice that fails verification, GetInstalledVoices()()()() sets its Enabled property to False. An application cannot select a voice whose Enabled property is False. Typically, applications will not set a voice's Enabled property.

To select a voice by gender, age, or locale, use one of the SelectVoiceByHints methods.

Examples

The following example uses the GetInstalledVoices()()()() method and the VoiceInfo class to obtain the names of the installed text-to-speech voices.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Output information about all of the installed voices.
        Console.WriteLine("Installed voices -");
        foreach (InstalledVoice voice in synth.GetInstalledVoices())
        {
          VoiceInfo info = voice.VoiceInfo;
          Console.WriteLine(" Voice Name: " + info.Name);
        }
      }

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

You can use one of the voice names discovered with the above example as an argument to the SelectVoice(String) method to select a voice to use. The following example selects the US English voice.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\temp\test.wav");

        // Select the US English voice.
        synth.SelectVoice("Microsoft Server Speech Text to Speech Voice (en-US, Helen)");

        // Build a prompt.
        PromptBuilder builder = new PromptBuilder();
        builder.AppendText("That is a big pizza!");

        // Speak the prompt.
        synth.Speak(builder);
      }
    }
  }
}

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SelectVoiceByHints Method

[image] [image]

SpeechSynthesizer..::..SelectVoiceByHints Method
SpeechSynthesizer Class See Also Send Feedback

Selects a voice with specific characteristics.

Overload List

 | Name | Description
Public method | SelectVoiceByHints(VoiceGender) | Selects a voice with a specific gender.
Public method | SelectVoiceByHints(VoiceGender, VoiceAge) | Selects a voice with a specific gender and age.
Public method | SelectVoiceByHints(VoiceGender, VoiceAge, Int32) | Selects a voice with a specific gender and age, based on the position in which the voices are ordered.
Public method | SelectVoiceByHints(VoiceGender, VoiceAge, Int32, CultureInfo) | Selects a voice with a specific gender, age, and locale, based on the position in which the voices are ordered.
Top

Remarks

Use the GetInstalledVoices method and VoiceInfo class to obtain the names of installed text-to-speech (TTS) voices that you can select. The SpeechSynthesizer object selects the first installed voice that matches the specified characteristics.

When an application calls GetInstalledVoices()()()(), the method verifies that each of the voices it finds in the registry meets certain minimum criteria. For any voice that fails verification, GetInstalledVoices()()()() sets its Enabled property to False. An application cannot select a voice whose Enabled property is False. Typically, applications will not set a voice's Enabled property.

To select a voice by name, use the SelectVoice(String) method

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SelectVoiceByHints Method (VoiceGender)

[image]

SpeechSynthesizer..::..SelectVoiceByHints Method (VoiceGender)
SpeechSynthesizer Class See Also Send Feedback

Selects a voice with a specific gender.

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

Syntax

Visual Basic (Declaration)
Public Sub SelectVoiceByHints ( _
    gender As VoiceGender _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim gender As VoiceGender

instance.SelectVoiceByHints(gender)
C#
public void SelectVoiceByHints(
    VoiceGender gender
)

Parameters

gender
Type: Microsoft.Speech.Synthesis..::..VoiceGender

The gender of the voice to select.

Remarks

Use the GetInstalledVoices method and VoiceInfo class to obtain the names of installed text-to-speech (TTS) voices that you can select. The SpeechSynthesizer object selects the first installed voice whose Gender property matches the gender parameter.

When an application calls GetInstalledVoices()()()(), the method verifies that each of the voices it finds in the registry meets certain minimum criteria. For any voice that fails verification, GetInstalledVoices()()()() sets its Enabled property to False. An application cannot select a voice whose Enabled property is False. Typically, applications will not set a voice's Enabled property.

To select a voice based on other characteristics, see the other SelectVoiceByHints methods.

To select a voice by name, use the SelectVoice(String) method.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
SelectVoiceByHints Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SelectVoiceByHints Method (VoiceGender, VoiceAge)

[image]

SpeechSynthesizer..::..SelectVoiceByHints Method (VoiceGender, VoiceAge)
SpeechSynthesizer Class See Also Send Feedback

Selects a voice with a specific gender and age.

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

Syntax

Visual Basic (Declaration)
Public Sub SelectVoiceByHints ( _
    gender As VoiceGender, _
    age As VoiceAge _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim gender As VoiceGender
Dim age As VoiceAge

instance.SelectVoiceByHints(gender, age)
C#
public void SelectVoiceByHints(
    VoiceGender gender,
    VoiceAge age
)

Parameters

gender
Type: Microsoft.Speech.Synthesis..::..VoiceGender

The gender of the voice to select.

age
Type: Microsoft.Speech.Synthesis..::..VoiceAge

The age of the voice to select.

Remarks

Use the GetInstalledVoices method and VoiceInfo class to obtain the names of installed text-to-speech (TTS) voices that you can select. The SpeechSynthesizer object selects the first installed voice whose Gender and Age properties match the gender and age parameters.

When an application calls GetInstalledVoices()()()(), the method verifies that each of the voices it finds in the registry meets certain minimum criteria. For any voice that fails verification, GetInstalledVoices()()()() sets its Enabled property to False. An application cannot select a voice whose Enabled()()()() property is False. Typically, applications will not set a voice's Enabled()()()() property.

To select a voice based on other characteristics, see the other SelectVoiceByHints methods.

To select a voice by name, use the SelectVoice(String) method.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
SelectVoiceByHints Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SelectVoiceByHints Method (VoiceGender, VoiceAge, Int32)

[image]

SpeechSynthesizer..::..SelectVoiceByHints Method (VoiceGender, VoiceAge, Int32)
SpeechSynthesizer Class See Also Send Feedback

Selects a voice with a specific gender and age, based on the position in which the voices are ordered.

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

Syntax

Visual Basic (Declaration)
Public Sub SelectVoiceByHints ( _
    gender As VoiceGender, _
    age As VoiceAge, _
    voiceAlternate As Integer _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim gender As VoiceGender
Dim age As VoiceAge
Dim voiceAlternate As Integer

instance.SelectVoiceByHints(gender, age, _
    voiceAlternate)
C#
public void SelectVoiceByHints(
    VoiceGender gender,
    VoiceAge age,
    int voiceAlternate
)

Parameters

gender
Type: Microsoft.Speech.Synthesis..::..VoiceGender

The gender of the voice to select.

age
Type: Microsoft.Speech.Synthesis..::..VoiceAge

The age of the voice to select.

voiceAlternate
Type: System..::..Int32

The position of the voice to select.

Remarks

Use the GetInstalledVoices method and VoiceInfo class to obtain the names of installed text-to-speech (TTS) voices that you can select. The SpeechSynthesizer object finds installed voices whose Gender and Age properties match the gender and age parameters. The SpeechSynthesizer counts the matches it finds, and returns the voice when the count equals the voiceAlternate parameter.

When an application calls GetInstalledVoices()()()(), the method verifies that each of the voices it finds in the registry meets certain minimum criteria. For any voice that fails verification, GetInstalledVoices()()()() sets its Enabled property to False. An application cannot select a voice whose Enabled property is False. Typically, applications will not set a voice's Enabled property.

To select a voice based on other characteristics, see the other SelectVoiceByHints overloads.

To select a voice by name, use the SelectVoice(String) method.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
SelectVoiceByHints Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SelectVoiceByHints Method (VoiceGender, VoiceAge, Int32, CultureInfo)

[image]

SpeechSynthesizer..::..SelectVoiceByHints Method (VoiceGender, VoiceAge, Int32, CultureInfo)
SpeechSynthesizer Class See Also Send Feedback

Selects a voice with a specific gender, age, and locale, based on the position in which the voices are ordered.

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

Syntax

Visual Basic (Declaration)
Public Sub SelectVoiceByHints ( _
    gender As VoiceGender, _
    age As VoiceAge, _
    voiceAlternate As Integer, _
    culture As CultureInfo _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim gender As VoiceGender
Dim age As VoiceAge
Dim voiceAlternate As Integer
Dim culture As CultureInfo

instance.SelectVoiceByHints(gender, age, _
    voiceAlternate, culture)
C#
public void SelectVoiceByHints(
    VoiceGender gender,
    VoiceAge age,
    int voiceAlternate,
    CultureInfo culture
)

Parameters

gender
Type: Microsoft.Speech.Synthesis..::..VoiceGender

The gender of the voice to select.

age
Type: Microsoft.Speech.Synthesis..::..VoiceAge

The age of the voice to select.

voiceAlternate
Type: System..::..Int32

The position of the voice to select.

culture
Type: System.Globalization..::..CultureInfo

The locale of the voice to select.

Remarks

The SpeechSynthesizer object finds voices whose Gender, Age, and Culture properties match the gender, age, and culture parameters. The SpeechSynthesizer counts the matches it finds, and returns the voice when the count equals the voiceAlternate parameter.

For a given language code specified in the culture parameter, a speech synthesis engine that supports that language code must be installed to correctly pronounce words in the specified language.

The Microsoft Speech Platform SDK 11 and Microsoft Speech Platform SDK 11 do not include any engines for speech synthesis in a specific language. You must download a language pack (an engine for speech synthesis in a specific language) for each language in which you want to generate synthesized speech. See InstalledVoice for more information.

The Speech Platform SDK 11 accepts all valid language-country codes as values for culture. See Language Identifier Constants and Strings for a comprehensive list of language codes.

When an application calls GetInstalledVoices()()()(), the method verifies that each of the voices it finds in the registry meets certain minimum criteria. For any voice that fails verification, GetInstalledVoices()()()() sets its Enabled property to False. An application cannot select a voice whose Enabled property is False. Typically, applications will not set a voice's Enabled property.

To select a voice based on other characteristics, see the other SelectVoiceByHints overloads.

To select a voice by name, use the SelectVoice(String) method.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
SelectVoiceByHints Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetOutputToAudioStream Method

[image]

SpeechSynthesizer..::..SetOutputToAudioStream Method
SpeechSynthesizer Class See Also Send Feedback

Configures the SpeechSynthesizer object to append output to a stream that contains Waveform format audio.

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

Syntax

Visual Basic (Declaration)
Public Sub SetOutputToAudioStream ( _
    audioDestination As Stream, _
    formatInfo As SpeechAudioFormatInfo _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim audioDestination As Stream
Dim formatInfo As SpeechAudioFormatInfo

instance.SetOutputToAudioStream(audioDestination, _
    formatInfo)
C#
public void SetOutputToAudioStream(
    Stream audioDestination,
    SpeechAudioFormatInfo formatInfo
)

Parameters

audioDestination
Type: System.IO..::..Stream

The stream to which to append synthesis output.

formatInfo
Type: Microsoft.Speech.AudioFormat..::..SpeechAudioFormatInfo

The format to use for the synthesis output.

Remarks

Call SetOutputToNull to release the SpeechSynthesizer's reference to the stream.

For other output configuration options, see the SetOutputToDefaultAudioDevice, SetOutputToNull, SetOutputToWaveFile, and SetOutputToWaveStream methods.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetOutputToDefaultAudioDevice Method

[image]

SpeechSynthesizer..::..SetOutputToDefaultAudioDevice Method
SpeechSynthesizer Class See Also Send Feedback

Configures the SpeechSynthesizer object to send output to the default audio device for the system.

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

Syntax

Visual Basic (Declaration)
Public Sub SetOutputToDefaultAudioDevice
Visual Basic (Usage)
Dim instance As SpeechSynthesizer

instance.SetOutputToDefaultAudioDevice()
C#
public void SetOutputToDefaultAudioDevice()

Remarks

For other output configuration options, see the SetOutputToAudioStream, SetOutputToNull, SetOutputToWaveFile, and SetOutputToWaveStream methods.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetOutputToNull Method

[image]

SpeechSynthesizer..::..SetOutputToNull Method
SpeechSynthesizer Class See Also Send Feedback

Configures the SpeechSynthesizer object to not send output from synthesis operations to a device, file, or stream.

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

Syntax

Visual Basic (Declaration)
Public Sub SetOutputToNull
Visual Basic (Usage)
Dim instance As SpeechSynthesizer

instance.SetOutputToNull()
C#
public void SetOutputToNull()

Remarks

Use this method to release the SpeechSynthesizer 's reference to a file or stream.

For other output configuration options, see the SetOutputToAudioStream, SetOutputToDefaultAudioDevice, SetOutputToWaveFile, and SetOutputToWaveStream methods.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetOutputToWaveFile Method

[image] [image]

SpeechSynthesizer..::..SetOutputToWaveFile Method
SpeechSynthesizer Class See Also Send Feedback

Configures the SpeechSynthesizer object to append output to a Waveform audio format file.

Overload List

 | Name | Description
Public method | SetOutputToWaveFile(String) | Configures the SpeechSynthesizer object to append output to a file that contains Waveform format audio.
Public method | SetOutputToWaveFile(String, SpeechAudioFormatInfo) | Configures the SpeechSynthesizer object to append output to a Waveform audio format file in a specified format.
Top

Remarks

To release the SpeechSynthesizer's reference to the file, reconfigure the SpeechSynthesizer's output, for example, by calling SetOutputToNull.

For other output configuration options, see the SetOutputToAudioStream, SetOutputToDefaultAudioDevice, SetOutputToNull, and SetOutputToWaveStream methods.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetOutputToWaveFile Method (String)

[image]

SpeechSynthesizer..::..SetOutputToWaveFile Method (String)
SpeechSynthesizer Class Example See Also Send Feedback

Configures the SpeechSynthesizer object to append output to a file that contains Waveform format audio.

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

Syntax

Visual Basic (Declaration)
Public Sub SetOutputToWaveFile ( _
    path As String _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim path As String

instance.SetOutputToWaveFile(path)
C#
public void SetOutputToWaveFile(
    string path
)

Parameters

path
Type: System..::..String

The path to the file.

Remarks

To configure the output and specify the audio format, use the SetOutputToWaveFile(String, SpeechAudioFormatInfo) method.

Examples

The following example uses an instance of SoundPlayer to play a prompt that has been output to a .wav file.

Copy image Copy Code
using System;
using System.IO;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\temp\test.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\temp\test.wav");

        // Build a prompt.
        PromptBuilder builder = new PromptBuilder();
        builder.AppendText("This is sample output to a WAVE file.");

        // Speak the prompt.
        synth.Speak(builder);
        m_SoundPlayer.Play();
      }

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

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
SetOutputToWaveFile Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetOutputToWaveFile Method (String, SpeechAudioFormatInfo)

[image]

SpeechSynthesizer..::..SetOutputToWaveFile Method (String, SpeechAudioFormatInfo)
SpeechSynthesizer Class Example See Also Send Feedback

Configures the SpeechSynthesizer object to append output to a Waveform audio format file in a specified format.

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

Syntax

Visual Basic (Declaration)
Public Sub SetOutputToWaveFile ( _
    path As String, _
    formatInfo As SpeechAudioFormatInfo _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim path As String
Dim formatInfo As SpeechAudioFormatInfo

instance.SetOutputToWaveFile(path, formatInfo)
C#
public void SetOutputToWaveFile(
    string path,
    SpeechAudioFormatInfo formatInfo
)

Parameters

path
Type: System..::..String

The path to the file.

formatInfo
Type: Microsoft.Speech.AudioFormat..::..SpeechAudioFormatInfo

The audio format information.

Examples

The following example specifies the format of the output of speech synthesis and sends it to a WAV file.

Copy image Copy Code
using System;
using System.IO;
using Microsoft.Speech.Synthesis;
using Microsoft.Speech.AudioFormat;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\temp\test.wav",
          new SpeechAudioFormatInfo(8000, AudioBitsPerSample.Eight, AudioChannel.Mono));

        // Create a SoundPlayer instance to play output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\temp\test.wav");

        // Build a prompt.
        PromptBuilder builder = new PromptBuilder();
        builder.AppendText("This is sample output to a WAVE file.");

        // Speak the prompt.
        synth.Speak(builder);
        m_SoundPlayer.Play();
      }

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

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
SetOutputToWaveFile Overload
Microsoft.Speech.Synthesis Namespace
SetOutputToAudioStream
SetOutputToDefaultAudioDevice
SetOutputToNull
SetOutputToWaveStream
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SetOutputToWaveStream Method

[image]

SpeechSynthesizer..::..SetOutputToWaveStream Method
SpeechSynthesizer Class Example See Also Send Feedback

Configures the SpeechSynthesizer object to append output to a stream that contains Waveform format audio.

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

Syntax

Visual Basic (Declaration)
Public Sub SetOutputToWaveStream ( _
    audioDestination As Stream _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim audioDestination As Stream

instance.SetOutputToWaveStream(audioDestination)
C#
public void SetOutputToWaveStream(
    Stream audioDestination
)

Parameters

audioDestination
Type: System.IO..::..Stream

The stream to which to append synthesis output.

Remarks

To release the SpeechSynthesizer's reference to the stream, reconfigure the synthesizer's output, for example, by calling SetOutputToNull.

For other output configuration options, see the SetOutputToAudioStream, SetOutputToDefaultAudioDevice, SetOutputToNull, and SetOutputToWaveFile methods.

Examples

The following example outputs a phrase to a WAV stream.

Copy image Copy Code
using System;
using System.IO;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the speech synthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      using (MemoryStream stream = new MemoryStream())
      {

        // Create a SoundPlayer instance to play the output audio file.
        MemoryStream streamAudio = new MemoryStream();
        System.Media.SoundPlayer m_SoundPlayer = new System.Media.SoundPlayer();

        // Configure the synthesizer to output to an audio stream.
        synth.SetOutputToWaveStream(streamAudio);

        // Speak a phrase.
        synth.Speak("Sample text-to-speech output.");
        streamAudio.Position = 0;
        m_SoundPlayer.Stream = streamAudio;
        m_SoundPlayer.Play();

        // Set the synthesizer output to null to release the stream.
        synth.SetOutputToNull();

        // Insert code to persist or process the stream contents here.
      }

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

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Skip Method

[image]

SpeechSynthesizer..::..Skip Method
SpeechSynthesizer Class See Also Send Feedback

Skips the specified amount of time in a prompt.

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

Syntax

Visual Basic (Declaration)
Public Sub Skip ( _
    timeToSkip As TimeSpan _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim timeToSkip As TimeSpan

instance.Skip(timeToSkip)
C#
public void Skip(
    TimeSpan timeToSkip
)

Parameters

timeToSkip
Type: System..::..TimeSpan

The amount of time to skip.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Speak Method

[image] [image]

SpeechSynthesizer..::..Speak Method
SpeechSynthesizer Class See Also Send Feedback

Generates speech output synchronously from a string, a Prompt object, or a PromptBuilder object.

Overload List

 | Name | Description
Public method | Speak(String) | Synchronously speaks the contents of a string.
Public method | Speak(Prompt) | Synchronously speaks the contents of a Prompt object.
Public method | Speak(PromptBuilder) | Synchronously speaks the contents of a PromptBuilder object.
Top

Remarks

The Speak()()()() methods generate speech synchronously. The methods do not return until the content of the Speak()()()() instance has been completely spoken. This is the simplest way to generate speech. However, if your application needs to perform tasks while speaking, for example highlight text, paint animation, monitor controls, or other tasks, use the SpeakAsync()()()() methods or the SpeakSsmlAsync(String) method to generate speech asynchronously.

During a call to this method, the SpeechSynthesizer can raise the following events:

  • StateChanged. Raised when the speaking state of the synthesizer changes.

  • SpeakStarted. Raised when the synthesizer begins generating speech.

  • SpeakProgress. Raised each time the synthesizer completes speaking a word.

  • BookmarkReached. Raised when the synthesizer encounters a bookmark in a prompt.

  • VoiceChange. Raised when the speaking voice for the synthesizer changes.

The SpeechSynthesizer does not raise the SpeakCompleted event while processing any of the Speak()()()() methods.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Speak Method (String)

[image]

SpeechSynthesizer..::..Speak Method (String)
SpeechSynthesizer Class See Also Send Feedback

Synchronously speaks the contents of a string.

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

Syntax

Visual Basic (Declaration)
Public Sub Speak ( _
    textToSpeak As String _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim textToSpeak As String

instance.Speak(textToSpeak)
C#
public void Speak(
    string textToSpeak
)

Parameters

textToSpeak
Type: System..::..String

The text to speak.

Remarks

To synchronously speak a string that contains SSML markup, use the SpeakSsml(String) method. To asynchronously speak the contents of a string, use the SpeakAsync(String) method.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Speak Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Speak Method (Prompt)

[image]

SpeechSynthesizer..::..Speak Method (Prompt)
SpeechSynthesizer Class See Also Send Feedback

Synchronously speaks the contents of a Prompt object.

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

Syntax

Visual Basic (Declaration)
Public Sub Speak ( _
    prompt As Prompt _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim prompt As Prompt

instance.Speak(prompt)
C#
public void Speak(
    Prompt prompt
)

Parameters

prompt
Type: Microsoft.Speech.Synthesis..::..Prompt

The content to speak.

Remarks

To asynchronously speak the contents of a Prompt object, use SpeakAsync(Prompt).

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Speak Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Speak Method (PromptBuilder)

[image]

SpeechSynthesizer..::..Speak Method (PromptBuilder)
SpeechSynthesizer Class See Also Send Feedback

Synchronously speaks the contents of a PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Sub Speak ( _
    promptBuilder As PromptBuilder _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim promptBuilder As PromptBuilder

instance.Speak(promptBuilder)
C#
public void Speak(
    PromptBuilder promptBuilder
)

Parameters

promptBuilder
Type: Microsoft.Speech.Synthesis..::..PromptBuilder

The content to speak.

Remarks

To asynchronously speak the contents of a PromptBuilder object, use SpeakAsync(PromptBuilder).

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Speak Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakAsync Method

[image] [image]

SpeechSynthesizer..::..SpeakAsync Method
SpeechSynthesizer Class See Also Send Feedback

Generates speech output asynchronously from a string, a Prompt object, or a PromptBuilder object.

Overload List

 | Name | Description
Public method | SpeakAsync(String) | Asynchronously speaks the contents of a string.
Public method | SpeakAsync(Prompt) | Asynchronously speaks the contents of a Prompt object.
Public method | SpeakAsync(PromptBuilder) | Asynchronously speaks the contents of a PromptBuilder object.
Top

Remarks

The SpeakAsync()()()() methods generate speech asynchronously. The methods return immediately without waiting for the content of the SpeakAsync()()()() object to finish speaking. Use SpeakAsync()()()() if your application needs to perform tasks while speaking, for example highlight text, paint animation, monitor controls, or other tasks.

During a call to this method, the SpeechSynthesizer can raise the following events:

  • StateChanged. Raised when the speaking state of the synthesizer changes.

  • SpeakStarted. Raised when the synthesizer begins generating speech.

  • SpeakProgress. Raised each time the synthesizer completes speaking a word.

  • BookmarkReached. Raised when the synthesizer encounters a bookmark in a prompt.

  • VoiceChange. Raised when the speaking voice for the synthesizer changes.

  • SpeakCompleted. Raised when the synthesizer finishes a SpeakAsync()()()() operation.

If your application does not need to perform tasks while speaking, you can use the Speak()()()() methods or the SpeakSsml(String) method to generate speech synchronously.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakAsync Method (String)

[image]

SpeechSynthesizer..::..SpeakAsync Method (String)
SpeechSynthesizer Class See Also Send Feedback

Asynchronously speaks the contents of a string.

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

Syntax

Visual Basic (Declaration)
Public Function SpeakAsync ( _
    textToSpeak As String _
) As Prompt
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim textToSpeak As String
Dim returnValue As Prompt

returnValue = instance.SpeakAsync(textToSpeak)
C#
public Prompt SpeakAsync(
    string textToSpeak
)

Parameters

textToSpeak
Type: System..::..String

The text to speak.

Return Value

Type: Microsoft.Speech.Synthesis..::..Prompt

Returns the object that contains the content to speak.

Remarks

To synchronously speak a string that contains SSML markup, use the SpeakSsml(String) method. To asynchronously speak the contents of a string, use the SpeakAsync(String) method.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
SpeakAsync Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakAsync Method (Prompt)

[image]

SpeechSynthesizer..::..SpeakAsync Method (Prompt)
SpeechSynthesizer Class See Also Send Feedback

Asynchronously speaks the contents of a Prompt object.

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

Syntax

Visual Basic (Declaration)
Public Sub SpeakAsync ( _
    prompt As Prompt _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim prompt As Prompt

instance.SpeakAsync(prompt)
C#
public void SpeakAsync(
    Prompt prompt
)

Parameters

prompt
Type: Microsoft.Speech.Synthesis..::..Prompt

The content to speak.

Remarks

You can cancel the asynchronous speaking of a prompt with the SpeakAsyncCancel(Prompt) or the SpeakAsyncCancelAll()()()() method.

To synchronously speak the contents of a Prompt object, use Speak(Prompt).

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
SpeakAsync Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakAsync Method (PromptBuilder)

[image]

SpeechSynthesizer..::..SpeakAsync Method (PromptBuilder)
SpeechSynthesizer Class See Also Send Feedback

Asynchronously speaks the contents of a PromptBuilder object.

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

Syntax

Visual Basic (Declaration)
Public Function SpeakAsync ( _
    promptBuilder As PromptBuilder _
) As Prompt
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim promptBuilder As PromptBuilder
Dim returnValue As Prompt

returnValue = instance.SpeakAsync(promptBuilder)
C#
public Prompt SpeakAsync(
    PromptBuilder promptBuilder
)

Parameters

promptBuilder
Type: Microsoft.Speech.Synthesis..::..PromptBuilder

The content to speak.

Return Value

Type: Microsoft.Speech.Synthesis..::..Prompt

Returns the object that contains the content to speak.

Remarks

To synchronously speak the contents of a PromptBuilder object, use Speak(PromptBuilder).

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
SpeakAsync Overload
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakAsyncCancel Method

[image]

SpeechSynthesizer..::..SpeakAsyncCancel Method
SpeechSynthesizer Class See Also Send Feedback

Cancels the asynchronous synthesis operation for a queued prompt.

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

Syntax

Visual Basic (Declaration)
Public Sub SpeakAsyncCancel ( _
    prompt As Prompt _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim prompt As Prompt

instance.SpeakAsyncCancel(prompt)
C#
public void SpeakAsyncCancel(
    Prompt prompt
)

Parameters

prompt
Type: Microsoft.Speech.Synthesis..::..Prompt

The content for which to cancel a speak operation.

Remarks

You can also use this method to cancel an asynchronous speak operation for the following:

  • The contents of a String specified by a SpeechSynthesizer..::..SpeakAsync(String) method.

  • The contents of a PromptBuilder specified by a SpeechSynthesizer..::..SpeakAsync(PromptBuilder) method.

  • The contents of a String containing SSML specified by a SpeakSsmlAsync(String) method.

When you call SpeechSynthesizer..::..SpeakAsync(String), SpeechSynthesizer..::..SpeakAsync(PromptBuilder), or SpeakSsmlAsync(String), the method creates a Prompt object and populates it with the contents of the method's parameter, and returns the Prompt object. If you retain a copy of the returned Prompt, you can pass it into SpeakAsyncCancel(Prompt) to cancel speaking content specified in a String or a PromptBuilder object.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakAsyncCancelAll Method

[image]

SpeechSynthesizer..::..SpeakAsyncCancelAll Method
SpeechSynthesizer Class See Also Send Feedback

Cancels all queued, asynchronous, speech synthesis operations.

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

Syntax

Visual Basic (Declaration)
Public Sub SpeakAsyncCancelAll
Visual Basic (Usage)
Dim instance As SpeechSynthesizer

instance.SpeakAsyncCancelAll()
C#
public void SpeakAsyncCancelAll()

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakSsml Method

[image]

SpeechSynthesizer..::..SpeakSsml Method
SpeechSynthesizer Class Example See Also Send Feedback

Asynchronously speaks a String that contains SSML markup.

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

Syntax

Visual Basic (Declaration)
Public Sub SpeakSsml ( _
    textToSpeak As String _
)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim textToSpeak As String

instance.SpeakSsml(textToSpeak)
C#
public void SpeakSsml(
    string textToSpeak
)

Parameters

textToSpeak
Type: System..::..String

The SMML markup to speak.

Remarks

The contents of the textToSpeak parameter must include a speak element and must conform to the Speech Synthesis Markup Language (SSML) Version 1.0. For more information, see Speech Synthesis Markup Language Reference (Microsoft.Speech).

To asynchronously speak a string that contains SSML markup, use the SpeakSsmlAsync(String) method. You can use Speak(String) to initiate the synchronous speaking of a string that does not contain SSML markup.

During a call to this method, the SpeechSynthesizer can raise the following events:

  • StateChanged. Raised when the speaking state of the synthesizer changes.

  • SpeakStarted. Raised when the synthesizer begins generating speech.

  • SpeakProgress. Raised each time the synthesizer completes speaking a word.

  • BookmarkReached. Raised when the synthesizer encounters a bookmark in a prompt.

  • VoiceChange. Raised when the speaking voice for the synthesizer changes.

The SpeechSynthesizer does not raise the SpeakCompleted event while processing the SpeakSsml(String) method.

Examples

The following example renders the date 1/29/2009 as a date, in month, day, year order.

C# Copy image Copy Code
SpeechSynthesizer synth = new SpeechSynthesizer();
string str = "<speak version=\"1.0\"";
str += " xmlns:ssml=\"http://www.w3.org/2001/10/synthesis\"";
str += " xml:lang=\"en-US\">";
str += "<say-as type=\"date:mdy\">1/29/2009</say-as>";
str += "</speak>";
synth.SpeakSsml(str);

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakSsmlAsync Method

[image]

SpeechSynthesizer..::..SpeakSsmlAsync Method
SpeechSynthesizer Class See Also Send Feedback

Asynchronously speaks a String that contains SSML markup.

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

Syntax

Visual Basic (Declaration)
Public Function SpeakSsmlAsync ( _
    textToSpeak As String _
) As Prompt
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim textToSpeak As String
Dim returnValue As Prompt

returnValue = instance.SpeakSsmlAsync(textToSpeak)
C#
public Prompt SpeakSsmlAsync(
    string textToSpeak
)

Parameters

textToSpeak
Type: System..::..String

The SMML markup to speak.

Return Value

Type: Microsoft.Speech.Synthesis..::..Prompt

Remarks

The contents of the textToSpeak parameter must include a speak element and must conform to the Speech Synthesis Markup Language (SSML) Version 1.0. For more information, see Speech Synthesis Markup Language Reference (Microsoft.Speech).

To synchronously speak a string that contains SSML markup, use the SpeakSsml(String) method. You can use SpeakAsync(String) to initiate the asynchronous speaking of a string that does not contain SSML markup.

During a call to this method, the SpeechSynthesizer can raise the following events:

  • StateChanged. Raised when the speaking state of the synthesizer changes.

  • SpeakStarted. Raised when the synthesizer begins generating speech.

  • SpeakProgress. Raised each time the synthesizer completes speaking a word.

  • BookmarkReached. Raised when the synthesizer encounters a bookmark in a prompt.

  • VoiceChange. Raised when the speaking voice for the synthesizer changes.

  • SpeakCompleted. Raised when the synthesizer finishes processing a SpeakSsmlAsync(String) operation.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechSynthesizer Properties

[image] [image]

SpeechSynthesizer Properties
SpeechSynthesizer Class See Also Send Feedback

The SpeechSynthesizer type exposes the following members.

Properties

 | Name | Description
Public property | Rate | Gets or sets the speaking rate of the SpeechSynthesizer object.
Public property | State | Gets the speaking state of the SpeechSynthesizer object.
Public property | TtsVolume | Gets or sets the volume (loudness) of the synthesized speech in the SpeechSynthesizer's audio output.
Public property | Voice | Gets information about the current voice of the SpeechSynthesizer object.
Public property | Volume | Get or sets the output volume of the SpeechSynthesizer object.
Top

See Also

Reference

SpeechSynthesizer Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Rate Property

[image]

SpeechSynthesizer..::..Rate Property
SpeechSynthesizer Class See Also Send Feedback

Gets or sets the speaking rate of the SpeechSynthesizer object.

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

Syntax

Visual Basic (Declaration)
Public Property Rate As Integer
    Get
    Set
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim value As Integer

value = instance.Rate

instance.Rate = value
C#
public int Rate { get; set; }

Property Value

Type: System..::..Int32

Returns the speaking rate of the SpeechSynthesizer object, from -10 through 10.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
PromptStyle
PromptRate
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


State Property

[image]

SpeechSynthesizer..::..State Property
SpeechSynthesizer Class See Also Send Feedback

Gets the speaking state of the SpeechSynthesizer object.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property State As SynthesizerState
    Get
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim value As SynthesizerState

value = instance.State
C#
public SynthesizerState State { get; }

Property Value

Type: Microsoft.Speech.Synthesis..::..SynthesizerState

Returns the speaking state of the SpeechSynthesizer object.

Remarks

To pause and resume speech synthesis, use the Pause and Resume methods.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


TtsVolume Property

[image]

SpeechSynthesizer..::..TtsVolume Property
SpeechSynthesizer Class Example See Also Send Feedback

Gets or sets the volume (loudness) of the synthesized speech in the SpeechSynthesizer's audio output.

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

Syntax

Visual Basic (Declaration)
Public Property TtsVolume As Integer
    Get
    Set
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim value As Integer

value = instance.TtsVolume

instance.TtsVolume = value
C#
public int TtsVolume { get; set; }

Property Value

Type: System..::..Int32

Returns the volume of the synthesized voice in the SpeechSynthesizer's audio output, from 0 through 100.

Remarks

You can use this property to balance the level of the TTS voice with the level of recorded audio in a prompt. By contrast, the Volume property sets the level of the combined audio output for both the synthesized voice and audio files in a prompt.

Examples

The following example sets the level of the TTS voice to be compatible with the level of the WAV file ContosoWeather.wav.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToDefaultAudioDevice();

        // Set the volume of the TTS voice.
        synth.TtsVolume = 50;

        // Build a prompt containing recorded audio and synthesized speech.
        PromptBuilder builder = new PromptBuilder(
          new System.Globalization.CultureInfo("en-US"));
        builder.AppendAudio("C:\\Test\\WelcomeToContosoRadio.wav");
        builder.AppendText(
          "The weather forecast for today is partly cloudy with some sun breaks.");

        // Speak the prompt.
        synth.Speak(builder);
      }

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

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Voice Property

[image]

SpeechSynthesizer..::..Voice Property
SpeechSynthesizer Class Example See Also Send Feedback

Gets information about the current voice of the SpeechSynthesizer object.

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

Syntax

Visual Basic (Declaration)
Public Property Voice As VoiceInfo
    Get
    Friend Set
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim value As VoiceInfo

value = instance.Voice
C#
public VoiceInfo Voice { get; internal set; }

Property Value

Type: Microsoft.Speech.Synthesis..::..VoiceInfo

Returns information about the current voice of the SpeechSynthesizer object.

Remarks

When you initialize a new SpeechSynthesizer, it uses the default system voice. To configure the SpeechSynthesizer object to use one of the installed speech synthesis voices, use the SelectVoice or SelectVoiceByHints method. To get information about which voices are installed, use the GetInstalledVoices method and the VoiceInfo class.

Examples

The following example initializes an instance of SpeechSynthesizer and gets information about the current voice.

Copy image Copy Code
using System;
using System.IO;
using Microsoft.Speech.Synthesis;
using Microsoft.Speech.AudioFormat;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Get information about supported audio formats.
        string AudioFormats = "";
        foreach (SpeechAudioFormatInfo fmt in synth.Voice.SupportedAudioFormats)
        {
          AudioFormats += String.Format("{0}\n",
          fmt.EncodingFormat.ToString());
        }

        // Write information about the voice to the console.
        Console.WriteLine(" Name:          " + synth.Voice.Name);
        Console.WriteLine(" Culture:       " + synth.Voice.Culture);
        Console.WriteLine(" Age:           " + synth.Voice.Age);
        Console.WriteLine(" Gender:        " + synth.Voice.Gender);
        Console.WriteLine(" Description:   " + synth.Voice.Description);
        Console.WriteLine(" ID:            " + synth.Voice.Id);
        if (synth.Voice.SupportedAudioFormats.Count != 0)
        {
          Console.WriteLine(" Audio formats: " + AudioFormats);
        }
        else
        {
          Console.WriteLine(" No supported audio formats found");
        }

        // Get additional information about the voice.
        string AdditionalInfo = "";
        foreach (string key in synth.Voice.AdditionalInfo.Keys)
        {
          AdditionalInfo += String.Format("  {0}: {1}\n",
            key, synth.Voice.AdditionalInfo[key]);
        }

        Console.WriteLine(" Additional Info - " + AdditionalInfo);
        Console.WriteLine();
      }

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

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Volume Property

[image]

SpeechSynthesizer..::..Volume Property
SpeechSynthesizer Class Example See Also Send Feedback

Get or sets the output volume of the SpeechSynthesizer object.

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

Syntax

Visual Basic (Declaration)
Public Property Volume As Integer
    Get
    Set
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim value As Integer

value = instance.Volume

instance.Volume = value
C#
public int Volume { get; set; }

Property Value

Type: System..::..Int32

Returns the volume of the SpeechSynthesizer, from 0 through 100.

Remarks

You can use this property to set the combined audio output for both the synthesized voice and the audio files in a prompt. By contrast, the TtsVolume property affects only the output volume of the synthesized voice in a prompt.

Examples

The following example sets the level of the TTS voice to be compatible with the level of the WAV file ContosoWeather.wav, and then sets the combined output volume for the synthesized voice and the recorded audio file.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToDefaultAudioDevice();

        // Set the volume of the TTS voice, and the combined output volume.
        synth.TtsVolume = 50;
        synth.Volume = 60;

        // Build a prompt containing recorded audio and synthesized speech.
        PromptBuilder builder = new PromptBuilder(
          new System.Globalization.CultureInfo("en-US"));
        builder.AppendAudio("C:\\Test\\WelcomeToContosoRadio.wav");
        builder.AppendText(
          "The weather forecast for today is partly cloudy with some sun breaks.");

        // Speak the prompt.
        synth.Speak(builder);
      }

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

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeechSynthesizer Events

[image] [image]

SpeechSynthesizer Events
SpeechSynthesizer Class See Also Send Feedback

The SpeechSynthesizer type exposes the following members.

Events

 | Name | Description
Public event | BookmarkReached | Raised when the SpeechSynthesizer encounters a bookmark in a prompt.
Public event | ProprietaryEngineEvent | This event is for use by developers of custom speech synthesis engines.
Public event | SpeakCompleted | Raised when the SpeechSynthesizer completes the speaking of a prompt.
Public event | SpeakProgress | Raised after the SpeechSynthesizer speaks each individual word of a prompt.
Public event | SpeakStarted | Raised when the SpeechSynthesizer begins the speaking of a prompt.
Public event | StateChanged | Raised when the state of the SpeechSynthesizer changes.
Public event | VoiceChange | Raised when the voice of the SpeechSynthesizer changes.
Top

See Also

Reference

SpeechSynthesizer Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


BookmarkReached Event

[image]

SpeechSynthesizer..::..BookmarkReached Event
SpeechSynthesizer Class Example See Also Send Feedback

Raised when the SpeechSynthesizer encounters a bookmark in a prompt.

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

Syntax

Visual Basic (Declaration)
Public Event BookmarkReached As EventHandler(Of BookmarkReachedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim handler As EventHandler(Of BookmarkReachedEventArgs)

AddHandler instance.BookmarkReached, handler
C#
public event EventHandler<BookmarkReachedEventArgs> BookmarkReached

Remarks

The SpeechSynthesizer raises this event while processing any of the Speak()()()(), SpeakAsync()()()(), SpeakSsml(String), or SpeakSsmlAsync(String) methods. For information about data associated with the event, see BookmarkReachedEventArgs.

You can add bookmarks using the AppendBookmark(String) method.

Examples

The following example creates a prompt that includes two bookmarks and sends the output to a WAV file for playback. The handler for the BookmarkReached event writes the name of the bookmark and its position in the audio stream when the event was raised to the console.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Configure the audio output.
        synth.SetOutputToWaveFile(@"C:\test\weather.wav");

        // Create a SoundPlayer instance to play the output audio file.
        System.Media.SoundPlayer m_SoundPlayer =
          new System.Media.SoundPlayer(@"C:\test\weather.wav");

        // Build a prompt and append bookmarks.
        PromptBuilder builder = new PromptBuilder(
          new System.Globalization.CultureInfo("en-US"));
        builder.AppendText(
          "The weather forecast for today is partly cloudy with some sun breaks.");
        builder.AppendBookmark("Daytime forecast");
        builder.AppendText(
          "Tonight's weather will be cloudy with a 30% chance of showers.");
        builder.AppendBookmark("Nightime forecast");

        // Add a handler for the BookmarkReached event.
        synth.BookmarkReached +=
          new EventHandler<BookmarkReachedEventArgs>(synth_BookmarkReached);

        // Speak the prompt and play back the output file.
        synth.Speak(builder);
        m_SoundPlayer.Play();
      }

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

    // Write the name and position of the bookmark to the console.
    static void synth_BookmarkReached(object sender, BookmarkReachedEventArgs e)
    {
      Console.WriteLine("Bookmark ({0}) reached at: {1} ",
        e.Bookmark, e.AudioPosition);
    }
  }
}

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


ProprietaryEngineEvent Event

[image]

SpeechSynthesizer..::..ProprietaryEngineEvent Event
SpeechSynthesizer Class See Also Send Feedback

This event is for use by developers of custom speech synthesis engines.

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

Syntax

Visual Basic (Declaration)
Public Event ProprietaryEngineEvent As EventHandler(Of ProprietaryEngineEventArgs)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim handler As EventHandler(Of ProprietaryEngineEventArgs)

AddHandler instance.ProprietaryEngineEvent, handler
C#
public event EventHandler<ProprietaryEngineEventArgs> ProprietaryEngineEvent

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakCompleted Event

[image]

SpeechSynthesizer..::..SpeakCompleted Event
SpeechSynthesizer Class See Also Send Feedback

Raised when the SpeechSynthesizer completes the speaking of a prompt.

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

Syntax

Visual Basic (Declaration)
Public Event SpeakCompleted As EventHandler(Of SpeakCompletedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim handler As EventHandler(Of SpeakCompletedEventArgs)

AddHandler instance.SpeakCompleted, handler
C#
public event EventHandler<SpeakCompletedEventArgs> SpeakCompleted

Remarks

The SpeechSynthesizer raises the SpeakCompleted event at the completion of any of the SpeakAsync()()()() or SpeakSsmlAsync(String) methods. You can write handlers for the SpeakCompleted event using SpeakCompletedEventArgs.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
SpeakCompletedEventArgs
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakProgress Event

[image]

SpeechSynthesizer..::..SpeakProgress Event
SpeechSynthesizer Class See Also Send Feedback

Raised after the SpeechSynthesizer speaks each individual word of a prompt.

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

Syntax

Visual Basic (Declaration)
Public Event SpeakProgress As EventHandler(Of SpeakProgressEventArgs)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim handler As EventHandler(Of SpeakProgressEventArgs)

AddHandler instance.SpeakProgress, handler
C#
public event EventHandler<SpeakProgressEventArgs> SpeakProgress

Remarks

The SpeechSynthesizer raises this event for each new word that it speaks in a prompt using any of the Speak()()()(), SpeakAsync()()()(), SpeakSsml(String), or SpeakSsmlAsync(String) methods. For information about data associated with the event, see SpeakProgressEventArgs.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SpeakStarted Event

[image]

SpeechSynthesizer..::..SpeakStarted Event
SpeechSynthesizer Class See Also Send Feedback

Raised when the SpeechSynthesizer begins the speaking of a prompt.

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

Syntax

Visual Basic (Declaration)
Public Event SpeakStarted As EventHandler(Of SpeakStartedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim handler As EventHandler(Of SpeakStartedEventArgs)

AddHandler instance.SpeakStarted, handler
C#
public event EventHandler<SpeakStartedEventArgs> SpeakStarted

Remarks

The SpeechSynthesizer raises this event when it begins processing a prompt using any of the Speak()()()(), SpeakAsync()()()(), SpeakSsml(String), or SpeakSsmlAsync(String) methods. For information about data associated with the event, see SpeakStartedEventArgs.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StateChanged Event

[image]

SpeechSynthesizer..::..StateChanged Event
SpeechSynthesizer Class See Also Send Feedback

Raised when the state of the SpeechSynthesizer changes.

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

Syntax

Visual Basic (Declaration)
Public Event StateChanged As EventHandler(Of StateChangedEventArgs)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim handler As EventHandler(Of StateChangedEventArgs)

AddHandler instance.StateChanged, handler
C#
public event EventHandler<StateChangedEventArgs> StateChanged

Remarks

The SpeechSynthesizer raises this event when its speaking State changes. For information about data associated with the event, see StateChangedEventArgs.

To pause and resume speech synthesis, use the Pause and Resume methods.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceChange Event

[image]

SpeechSynthesizer..::..VoiceChange Event
SpeechSynthesizer Class See Also Send Feedback

Raised when the voice of the SpeechSynthesizer changes.

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

Syntax

Visual Basic (Declaration)
Public Event VoiceChange As EventHandler(Of VoiceChangeEventArgs)
Visual Basic (Usage)
Dim instance As SpeechSynthesizer
Dim handler As EventHandler(Of VoiceChangeEventArgs)

AddHandler instance.VoiceChange, handler
C#
public event EventHandler<VoiceChangeEventArgs> VoiceChange

Remarks

For information about data associated with the event, see VoiceChangeEventArgs.

You can change the voice in use by the SpeechSynthesizer with any of the PromptBuilder's StartVoice()()()() methods or the SpeechSynthesizer's SelectVoice(String) or SelectVoiceByHints()()()() methods.

See Also

Reference

SpeechSynthesizer Class
SpeechSynthesizer Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StateChangedEventArgs Class

[image]

StateChangedEventArgs Class
Members See Also Send Feedback

Returns data from the StateChanged event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.Synthesis..::..StateChangedEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class StateChangedEventArgs _
    Inherits EventArgs
Visual Basic (Usage)
Dim instance As StateChangedEventArgs
C#
public class StateChangedEventArgs : EventArgs

Remarks

An instance of StateChangedEventArgs is created when the SpeechSynthesizer object raises the StateChanged event. To obtain the values for the new and the previous SynthesizerState, access the State and PreviousState properties in the handler for the event.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

StateChangedEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StateChangedEventArgs Members

[image] [image]

StateChangedEventArgs Members
StateChangedEventArgs Class Methods Properties See Also Send Feedback

Returns data from the StateChanged event.

The StateChangedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | PreviousState | Gets the state of the SpeechSynthesizer before the StateChanged event.
Public property | State | Gets the state of the SpeechSynthesizer after the StateChanged event.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

StateChangedEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StateChangedEventArgs Methods

[image] [image]

StateChangedEventArgs Methods
StateChangedEventArgs Class See Also Send Feedback

The StateChangedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

StateChangedEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


StateChangedEventArgs Properties

[image] [image]

StateChangedEventArgs Properties
StateChangedEventArgs Class See Also Send Feedback

The StateChangedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | PreviousState | Gets the state of the SpeechSynthesizer before the StateChanged event.
Public property | State | Gets the state of the SpeechSynthesizer after the StateChanged event.
Top

See Also

Reference

StateChangedEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


PreviousState Property

[image]

StateChangedEventArgs..::..PreviousState Property
StateChangedEventArgs Class See Also Send Feedback

Gets the state of the SpeechSynthesizer before the StateChanged event.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property PreviousState As SynthesizerState
    Get
Visual Basic (Usage)
Dim instance As StateChangedEventArgs
Dim value As SynthesizerState

value = instance.PreviousState
C#
public SynthesizerState PreviousState { get; }

Property Value

Type: Microsoft.Speech.Synthesis..::..SynthesizerState

The state of the synthesizer before the state changed.

Remarks

The PreviousState property represents the synthesizer state with a member of the SynthesizerState enumeration.

See Also

Reference

StateChangedEventArgs Class
StateChangedEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


State Property

[image]

StateChangedEventArgs..::..State Property
StateChangedEventArgs Class See Also Send Feedback

Gets the state of the SpeechSynthesizer after the StateChanged event.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property State As SynthesizerState
    Get
Visual Basic (Usage)
Dim instance As StateChangedEventArgs
Dim value As SynthesizerState

value = instance.State
C#
public SynthesizerState State { get; }

Property Value

Type: Microsoft.Speech.Synthesis..::..SynthesizerState

The state of the synthesizer after the state changed.

Remarks

The State property represents the synthesizer state with a member of the SynthesizerState enumeration.

See Also

Reference

StateChangedEventArgs Class
StateChangedEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SynthesisMediaType Enumeration

[image]

SynthesisMediaType Enumeration
See Also Send Feedback

Enumerates the types of media files.

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

Syntax

Visual Basic (Declaration)
Public Enumeration SynthesisMediaType
Visual Basic (Usage)
Dim instance As SynthesisMediaType
C#
public enum SynthesisMediaType

Members

Member name | Description
Text | Indicates that the media type is Text.
Ssml | Indicates that the media type is SSML.
WaveAudio | Indicates that the media type is WaveAudio.

Remarks

The constructors of the FilePrompt class use SynthesisMediaType to indicate the media type of the file from which the prompt will be constructed.

See Also

Reference

Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SynthesisTextFormat Enumeration

[image]

SynthesisTextFormat Enumeration
See Also Send Feedback

Enumerates the types of text formats that may be used to construct a Prompt object.

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

Syntax

Visual Basic (Declaration)
Public Enumeration SynthesisTextFormat
Visual Basic (Usage)
Dim instance As SynthesisTextFormat
C#
public enum SynthesisTextFormat

Members

Member name | Description
Text | Indicates that text format is Text.
Ssml | Indicates that text format is SSML.

Remarks

The Prompt(String, SynthesisTextFormat) constructor uses SynthesisTextFormat to indicate the format of the text that its textToSpeak parameter contains.

See Also

Reference

Microsoft.Speech.Synthesis Namespace
Prompt
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SynthesizerState Enumeration

[image]

SynthesizerState Enumeration
See Also Send Feedback

Enumerates values for the state of the SpeechSynthesizer.

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

Syntax

Visual Basic (Declaration)
Public Enumeration SynthesizerState
Visual Basic (Usage)
Dim instance As SynthesizerState
C#
public enum SynthesizerState

Members

Member name | Description
Ready | Indicates that the SpeechSynthesizer is ready to generate speech from a prompt.
Speaking | Indicates that the SpeechSynthesizer is speaking.
Paused | Indicates that the SpeechSynthesizer is paused.

Remarks

The State property uses SynthesizerState to indicate the current state of the SpeechSynthesizer. The PreviousState and State properties use SynthesizerState to indicate state of the SpeechSynthesizer when the StateChanged event is raised.

See Also

Reference

Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceAge Enumeration

[image]

VoiceAge Enumeration
See Also Send Feedback

Defines the values for the age of a synthesized voice.

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

Syntax

Visual Basic (Declaration)
Public Enumeration VoiceAge
Visual Basic (Usage)
Dim instance As VoiceAge
C#
public enum VoiceAge

Members

Member name | Description
NotSet | Indicates that no voice age is specified.
Child | Indicates a child voice (age 10).
Teen | Indicates a teenage voice (age 15).
Adult | Indicates an adult voice (age 30).
Senior | Indicates a senior voice (age 65).

Remarks

VoiceAge can indicate the age of an existing voice or an age preference when selecting a voice. Three of the SelectVoiceByHints()()()() methods and two of the StartVoice()()()() methods use VoiceAge to specify the age when selecting a voice. The Age property obtains the age of an existing voice using a VoiceAge member.

See Also

Reference

Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceChangeEventArgs Class

[image]

VoiceChangeEventArgs Class
Members See Also Send Feedback

Returns data from the VoiceChange event.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
System.ComponentModel..::..AsyncCompletedEventArgs
Microsoft.Speech.Synthesis..::..PromptEventArgs
Microsoft.Speech.Synthesis..::..VoiceChangeEventArgs

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

Syntax

Visual Basic (Declaration)
Public Class VoiceChangeEventArgs _
    Inherits PromptEventArgs
Visual Basic (Usage)
Dim instance As VoiceChangeEventArgs
C#
public class VoiceChangeEventArgs : PromptEventArgs

Remarks

An instance of VoiceChangeEventArgs is created when the SpeechSynthesizer object raises the VoiceChange event. To obtain the identity of the new Voice, access the Voice property in the handler for the event.

You can change the voice in use by the SpeechSynthesizer with any of the PromptBuilder's StartVoice()()()() methods or the SpeechSynthesizer's SelectVoice()()()() or SelectVoiceByHints()()()() methods.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

VoiceChangeEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceChangeEventArgs Members

[image] [image]

VoiceChangeEventArgs Members
VoiceChangeEventArgs Class Methods Properties See Also Send Feedback

Returns data from the VoiceChange event.

The VoiceChangeEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Prompt | Gets the prompt associated with the event. (Inherited from PromptEventArgs.)
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Public property | Voice | Gets the VoiceInfo object of the new voice.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

VoiceChangeEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceChangeEventArgs Methods

[image] [image]

VoiceChangeEventArgs Methods
VoiceChangeEventArgs Class See Also Send Feedback

The VoiceChangeEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

VoiceChangeEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceChangeEventArgs Properties

[image] [image]

VoiceChangeEventArgs Properties
VoiceChangeEventArgs Class See Also Send Feedback

The VoiceChangeEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Prompt | Gets the prompt associated with the event. (Inherited from PromptEventArgs.)
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)
Public property | Voice | Gets the VoiceInfo object of the new voice.
Top

See Also

Reference

VoiceChangeEventArgs Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Voice Property

[image]

VoiceChangeEventArgs..::..Voice Property
VoiceChangeEventArgs Class See Also Send Feedback

Gets the VoiceInfo object of the new voice.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Voice As VoiceInfo
    Get
Visual Basic (Usage)
Dim instance As VoiceChangeEventArgs
Dim value As VoiceInfo

value = instance.Voice
C#
public VoiceInfo Voice { get; }

Property Value

Type: Microsoft.Speech.Synthesis..::..VoiceInfo

Returns information that describes and identifies the new voice.

Remarks

The Voice property gets the VoiceInfo object when a VoiceChange event is raised.

See Also

Reference

VoiceChangeEventArgs Class
VoiceChangeEventArgs Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceGender Enumeration

[image]

VoiceGender Enumeration
See Also Send Feedback

Defines the values for the gender of synthesized voices.

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

Syntax

Visual Basic (Declaration)
Public Enumeration VoiceGender
Visual Basic (Usage)
Dim instance As VoiceGender
C#
public enum VoiceGender

Members

Member name | Description
NotSet | Indicates no voice gender specification.
Male | Indicates a male voice.
Female | Indicates a female voice.
Neutral | Indicates a gender-neutral voice.

Remarks

VoiceGender can indicate the gender of an existing voice or a gender preference when selecting a voice. All of the SelectVoiceByHints()()()() methods and three of the StartVoice()()()() methods use VoiceGender to specify the gender when selecting a voice. The Gender property obtains the gender of an existing voice using a VoiceGender member.

See Also

Reference

Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceInfo Class

[image]

VoiceInfo Class
Members Example See Also Send Feedback

Represents an installed speech synthesis engine.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Synthesis..::..VoiceInfo

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

Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class VoiceInfo
Visual Basic (Usage)
Dim instance As VoiceInfo
C#
[SerializableAttribute]
public sealed class VoiceInfo

Remarks

A voice is an installed speech synthesis engine, which is also referred to as a text-to-speech engine or a TTS engine. The SpeechSynthesizer object uses a voice to generate speech from text. The properties of the VoiceInfo object identify a voice and describe its characteristics. The most defining characteristic of a voice is its Culture, which defines the single language that a voice can speak.

The Voice property returns a VoiceInfo object that contains information about the current voice in use by the SpeechSynthesizer. You can also use a VoiceInfo object to get information about any of the voices that are installed on the system, as returned by the GetInstalledVoices()()()() method. See InstalledVoice for more information.

Examples

The following example is part of a console application that initializes a SpeechSynthesizer object and outputs to the console a list of the installed voices (engines for speech synthesis) and demonstrates the information that is available for each voice.

Copy image Copy Code
using System;
using Microsoft.Speech.Synthesis;
using Microsoft.Speech.AudioFormat;

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

      // Initialize a new instance of the SpeechSynthesizer.
      using (SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Output information about all of the installed voices.
        Console.WriteLine("Installed voices -");
        foreach (InstalledVoice voice in synth.GetInstalledVoices())
        {
          VoiceInfo info = voice.VoiceInfo;
          string AudioFormats = "";
          foreach (SpeechAudioFormatInfo fmt in info.SupportedAudioFormats)
          {
            AudioFormats += String.Format("{0}\n",
            fmt.EncodingFormat.ToString());
          }

          Console.WriteLine(" Name:          " + info.Name);
          Console.WriteLine(" Culture:       " + info.Culture);
          Console.WriteLine(" Age:           " + info.Age);
          Console.WriteLine(" Gender:        " + info.Gender);
          Console.WriteLine(" Description:   " + info.Description);
          Console.WriteLine(" ID:            " + info.Id);
          Console.WriteLine(" Enabled:       " + voice.Enabled);
          if (info.SupportedAudioFormats.Count != 0)
          {
            Console.WriteLine( " Audio formats: " + AudioFormats);
          }
          else
          {
            Console.WriteLine(" No supported audio formats found");
          }

          string AdditionalInfo = "";
          foreach (string key in info.AdditionalInfo.Keys)
          {
            AdditionalInfo += String.Format("  {0}: {1}\n", key, info.AdditionalInfo[key]);
          }

          Console.WriteLine(" Additional Info - " + AdditionalInfo);
          Console.WriteLine();
        }
      }
      Console.WriteLine("Press any key to exit...");
      Console.ReadKey();
    }
  }
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

VoiceInfo Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceInfo Members

[image] [image]

VoiceInfo Members
VoiceInfo Class Methods Properties See Also Send Feedback

Represents an installed speech synthesis engine.

The VoiceInfo type exposes the following members.

Properties

 | Name | Description
Public property | AdditionalInfo | Gets additional information about the voice.
Public property | Age | Gets the age of the voice.
Public property | Culture | Gets the culture of the voice.
Public property | Description | Gets the description of the voice.
Public property | Gender | Gets the gender of the voice.
Public property | Id | Gets the ID of the voice.
Public property | Name | Gets the name of the voice.
Public property | SupportedAudioFormats | Gets the collection of audio formats that the voice supports.
Top

Methods

 | Name | Description
Public method | Equals | Compares the fields of the voice with the specified VoiceInfo object to determine whether they contain the same values. (Overrides Object..::..Equals(Object).)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Overrides Object..::..GetHashCode()()()().)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

VoiceInfo Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceInfo Methods

[image] [image]

VoiceInfo Methods
VoiceInfo Class See Also Send Feedback

The VoiceInfo type exposes the following members.

Methods

 | Name | Description
Public method | Equals | Compares the fields of the voice with the specified VoiceInfo object to determine whether they contain the same values. (Overrides Object..::..Equals(Object).)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Overrides Object..::..GetHashCode()()()().)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

VoiceInfo Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Equals Method

[image]

VoiceInfo..::..Equals Method
VoiceInfo Class See Also Send Feedback

Compares the fields of the voice with the specified VoiceInfo object to determine whether they contain the same values.

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

Syntax

Visual Basic (Declaration)
Public Overrides Function Equals ( _
    obj As Object _
) As Boolean
Visual Basic (Usage)
Dim instance As VoiceInfo
Dim obj As Object
Dim returnValue As Boolean

returnValue = instance.Equals(obj)
C#
public override bool Equals(
    Object obj
)

Parameters

obj
Type: System..::..Object

The specified VoiceInfo object.

Return Value

Type: System..::..Boolean

Returns True if the fields of the two VoiceInfo objects are equal; otherwise returns False.

Remarks

The Equals(Object) method takes a Object type as its parameter. If that object is not of the VoiceInfo type, the method returns False.

See Also

Reference

VoiceInfo Class
VoiceInfo Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetHashCode Method

[image]

VoiceInfo..::..GetHashCode Method
VoiceInfo Class See Also Send Feedback

This member overrides Object..::..GetHashCode()()()().

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

Syntax

Visual Basic (Declaration)
Public Overrides Function GetHashCode As Integer
Visual Basic (Usage)
Dim instance As VoiceInfo
Dim returnValue As Integer

returnValue = instance.GetHashCode()
C#
public override int GetHashCode()

Return Value

Type: System..::..Int32

See Also

Reference

VoiceInfo Class
VoiceInfo Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


VoiceInfo Properties

[image] [image]

VoiceInfo Properties
VoiceInfo Class See Also Send Feedback

The VoiceInfo type exposes the following members.

Properties

 | Name | Description
Public property | AdditionalInfo | Gets additional information about the voice.
Public property | Age | Gets the age of the voice.
Public property | Culture | Gets the culture of the voice.
Public property | Description | Gets the description of the voice.
Public property | Gender | Gets the gender of the voice.
Public property | Id | Gets the ID of the voice.
Public property | Name | Gets the name of the voice.
Public property | SupportedAudioFormats | Gets the collection of audio formats that the voice supports.
Top

See Also

Reference

VoiceInfo Class
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


AdditionalInfo Property

[image]

VoiceInfo..::..AdditionalInfo Property
VoiceInfo Class See Also Send Feedback

Gets additional information about the voice.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property AdditionalInfo As IDictionary(Of String, String)
    Get
Visual Basic (Usage)
Dim instance As VoiceInfo
Dim value As IDictionary(Of String, String)

value = instance.AdditionalInfo
C#
public IDictionary<string, string> AdditionalInfo { get; }

Property Value

Type: System.Collections.Generic..::..IDictionary <(Of <(<' String, String >)>)>

Returns a collection of name/value pairs that describe and identify the voice.

See Also

Reference

VoiceInfo Class
VoiceInfo Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Age Property

[image]

VoiceInfo..::..Age Property
VoiceInfo Class See Also Send Feedback

Gets the age of the voice.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Age As VoiceAge
    Get
Visual Basic (Usage)
Dim instance As VoiceInfo
Dim value As VoiceAge

value = instance.Age
C#
public VoiceAge Age { get; }

Property Value

Type: Microsoft.Speech.Synthesis..::..VoiceAge

Returns the age of the voice.

Remarks

The Age property gets a member of the VoiceAge enumeration that indicates the age of the voice.

See Also

Reference

VoiceInfo Class
VoiceInfo Members
Microsoft.Speech.Synthesis Namespace
VoiceAge
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Culture Property

[image]

VoiceInfo..::..Culture Property
VoiceInfo Class See Also Send Feedback

Gets the culture of the voice.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Culture As CultureInfo
    Get
Visual Basic (Usage)
Dim instance As VoiceInfo
Dim value As CultureInfo

value = instance.Culture
C#
public CultureInfo Culture { get; }

Property Value

Type: System.Globalization..::..CultureInfo

Returns information about a specific culture, such as the language, the name of the culture, the writing system, the calendar used, and how to format dates and sort strings.

Remarks

The Culture property identifies the single language that a voice supports. Typically, you will select a voice whose Culture property matches the culture parameter that is specified in the content to speak. You can specify a culture parameter for content to be spoken using the PromptBuilder(CultureInfo) constructor or the StartParagraph(CultureInfo) or StartSentence(CultureInfo) method. If authoring in Speech Synthesis Markup Language (SSML), you specify the culture using the xml:lang attribute.

You can change the voice (and thereby the culture) that the SpeechSynthesizer uses with the PromptBuilder's StartVoice(CultureInfo) method or with the SpeechSynthesizer's SelectVoice(String) or SelectVoiceByHints(VoiceGender, VoiceAge, Int32, CultureInfo) methods.

The Microsoft Speech Platform SDK 11 accepts all valid language-country codes as values for culture. See Language Identifier Constants and Strings for a comprehensive list of language codes.

See InstalledVoice for more information.

See Also

Reference

VoiceInfo Class
VoiceInfo Members
Microsoft.Speech.Synthesis Namespace
InstalledVoice
GetInstalledVoices()()()()
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Description Property

[image]

VoiceInfo..::..Description Property
VoiceInfo Class See Also Send Feedback

Gets the description of the voice.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Description As String
    Get
Visual Basic (Usage)
Dim instance As VoiceInfo
Dim value As String

value = instance.Description
C#
public string Description { get; }

Property Value

Type: System..::..String

Returns the description of the voice.

See Also

Reference

VoiceInfo Class
VoiceInfo Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Gender Property

[image]

VoiceInfo..::..Gender Property
VoiceInfo Class See Also Send Feedback

Gets the gender of the voice.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Gender As VoiceGender
    Get
Visual Basic (Usage)
Dim instance As VoiceInfo
Dim value As VoiceGender

value = instance.Gender
C#
public VoiceGender Gender { get; }

Property Value

Type: Microsoft.Speech.Synthesis..::..VoiceGender

Returns the gender of the voice.

Remarks

The Gender property gets a member of the VoiceGender enumeration that indicates the gender of the voice.

See Also

Reference

VoiceInfo Class
VoiceInfo Members
Microsoft.Speech.Synthesis Namespace
VoiceGender
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Id Property

[image]

VoiceInfo..::..Id Property
VoiceInfo Class See Also Send Feedback

Gets the ID of the voice.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Id As String
    Get
Visual Basic (Usage)
Dim instance As VoiceInfo
Dim value As String

value = instance.Id
C#
public string Id { get; }

Property Value

Type: System..::..String

Returns the identifier for the voice.

See Also

Reference

VoiceInfo Class
VoiceInfo Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Name Property

[image]

VoiceInfo..::..Name Property
VoiceInfo Class See Also Send Feedback

Gets the name of the voice.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Name As String
    Get
Visual Basic (Usage)
Dim instance As VoiceInfo
Dim value As String

value = instance.Name
C#
public string Name { get; }

Property Value

Type: System..::..String

Returns the name of the voice.

See Also

Reference

VoiceInfo Class
VoiceInfo Members
Microsoft.Speech.Synthesis Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


SupportedAudioFormats Property

[image]

VoiceInfo..::..SupportedAudioFormats Property
VoiceInfo Class See Also Send Feedback

Gets the collection of audio formats that the voice supports.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property SupportedAudioFormats As ReadOnlyCollection(Of SpeechAudioFormatInfo)
    Get
Visual Basic (Usage)
Dim instance As VoiceInfo
Dim value As ReadOnlyCollection(Of SpeechAudioFormatInfo)

value = instance.SupportedAudioFormats
C#
public ReadOnlyCollection<SpeechAudioFormatInfo> SupportedAudioFormats { get; }

Property Value

Type: System.Collections.ObjectModel..::..ReadOnlyCollection <(Of <(<' SpeechAudioFormatInfo >)>)>

Returns a collection of the audio formats that the voice supports.

See Also

Reference

VoiceInfo Class
VoiceInfo Members
Microsoft.Speech.Synthesis Namespace
SpeechAudioFormatInfo
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Microsoft.Speech.Text Namespace

[image]

Microsoft.Speech.Text Namespace
Send Feedback

The Microsoft.Speech.Text namespace represents the results of normalization.

Classes

 | Class | Description
Public class | NormalizedResult | Represents the results from normalization.
Public class | NormalizedResultAlternate | Represents the basic unit of a normalized result.
Public class | NormalizedResultAlternateCollection | Represents a read-only collection of normalization alternates.
Public class | NormalizerCollection | Provides an application the functionality of selecting, prioritizing, and weighting normalizers.
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedResult Class

[image]

NormalizedResult Class
Members See Also Send Feedback

Represents the results from normalization.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Text..::..NormalizedResult

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

Syntax

Visual Basic (Declaration)
Public Class NormalizedResult
Visual Basic (Usage)
Dim instance As NormalizedResult
C#
public class NormalizedResult

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

NormalizedResult Members
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedResult Members

[image] [image]

NormalizedResult Members
NormalizedResult Class Methods Properties See Also Send Feedback

Represents the results from normalization.

The NormalizedResult type exposes the following members.

Properties

 | Name | Description
Public property | InputString | Gets the original (before normalization) input string.
Public property | TopAlternate | Gets the normalized string with the highest confidence from the list of normalized alternates.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetAlternates | Returns the alternates element for the entire input string.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

NormalizedResult Class
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedResult Methods

[image] [image]

NormalizedResult Methods
NormalizedResult Class See Also Send Feedback

The NormalizedResult type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetAlternates | Returns the alternates element for the entire input string.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

NormalizedResult Class
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


GetAlternates Method

[image]

NormalizedResult..::..GetAlternates Method
NormalizedResult Class See Also Send Feedback

Returns the alternates element for the entire input string.

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

Syntax

Visual Basic (Declaration)
Public Function GetAlternates As NormalizedResultAlternateCollection
Visual Basic (Usage)
Dim instance As NormalizedResult
Dim returnValue As NormalizedResultAlternateCollection

returnValue = instance.GetAlternates()
C#
public NormalizedResultAlternateCollection GetAlternates()

Return Value

Type: Microsoft.Speech.Text..::..NormalizedResultAlternateCollection

A NormalizedResultAlternateCollection that contains a collection of alternate normalized results.

See Also

Reference

NormalizedResult Class
NormalizedResult Members
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedResult Properties

[image] [image]

NormalizedResult Properties
NormalizedResult Class See Also Send Feedback

The NormalizedResult type exposes the following members.

Properties

 | Name | Description
Public property | InputString | Gets the original (before normalization) input string.
Public property | TopAlternate | Gets the normalized string with the highest confidence from the list of normalized alternates.
Top

See Also

Reference

NormalizedResult Class
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


InputString Property

[image]

NormalizedResult..::..InputString Property
NormalizedResult Class See Also Send Feedback

Gets the original (before normalization) input string.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property InputString As String
    Get
Visual Basic (Usage)
Dim instance As NormalizedResult
Dim value As String

value = instance.InputString
C#
public string InputString { get; }

Property Value

Type: System..::..String

A String that contains the original input string.

See Also

Reference

NormalizedResult Class
NormalizedResult Members
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


TopAlternate Property

[image]

NormalizedResult..::..TopAlternate Property
NormalizedResult Class See Also Send Feedback

Gets the normalized string with the highest confidence from the list of normalized alternates.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property TopAlternate As NormalizedResultAlternate
    Get
Visual Basic (Usage)
Dim instance As NormalizedResult
Dim value As NormalizedResultAlternate

value = instance.TopAlternate
C#
public NormalizedResultAlternate TopAlternate { get; }

Property Value

Type: Microsoft.Speech.Text..::..NormalizedResultAlternate

The alternate with the highest confidence or nullNothingnullptrunita null reference (Nothing in Visual Basic) if the list of alternates is empty.

See Also

Reference

NormalizedResult Class
NormalizedResult Members
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedResultAlternate Class

[image]

NormalizedResultAlternate Class
Members See Also Send Feedback

Represents the basic unit of a normalized result.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Text..::..NormalizedResultAlternate

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

Syntax

Visual Basic (Declaration)
Public Class NormalizedResultAlternate
Visual Basic (Usage)
Dim instance As NormalizedResultAlternate
C#
public class NormalizedResultAlternate

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

NormalizedResultAlternate Members
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedResultAlternate Members

[image] [image]

NormalizedResultAlternate Members
NormalizedResultAlternate Class Methods Properties See Also Send Feedback

Represents the basic unit of a normalized result.

The NormalizedResultAlternate type exposes the following members.

Properties

 | Name | Description
Public property | NormalizedString | Gets the normalized string with the highest confidence.
Public property | Result | Gets the normalized result of which this NormalizedResultAlternate is one part.
Top

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

NormalizedResultAlternate Class
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedResultAlternate Methods

[image] [image]

NormalizedResultAlternate Methods
NormalizedResultAlternate Class See Also Send Feedback

The NormalizedResultAlternate type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

NormalizedResultAlternate Class
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedResultAlternate Properties

[image] [image]

NormalizedResultAlternate Properties
NormalizedResultAlternate Class See Also Send Feedback

The NormalizedResultAlternate type exposes the following members.

Properties

 | Name | Description
Public property | NormalizedString | Gets the normalized string with the highest confidence.
Public property | Result | Gets the normalized result of which this NormalizedResultAlternate is one part.
Top

See Also

Reference

NormalizedResultAlternate Class
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedString Property

[image]

NormalizedResultAlternate..::..NormalizedString Property
NormalizedResultAlternate Class See Also Send Feedback

Gets the normalized string with the highest confidence.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property NormalizedString As String
    Get
Visual Basic (Usage)
Dim instance As NormalizedResultAlternate
Dim value As String

value = instance.NormalizedString
C#
public string NormalizedString { get; }

Property Value

Type: System..::..String

A String that contains the normalized string with the highest confidence.

See Also

Reference

NormalizedResultAlternate Class
NormalizedResultAlternate Members
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Result Property

[image]

NormalizedResultAlternate..::..Result Property
NormalizedResultAlternate Class See Also Send Feedback

Gets the normalized result of which this NormalizedResultAlternate is one part.

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

Syntax

Visual Basic (Declaration)
Public ReadOnly Property Result As NormalizedResult
    Get
Visual Basic (Usage)
Dim instance As NormalizedResultAlternate
Dim value As NormalizedResult

value = instance.Result
C#
public NormalizedResult Result { get; }

Property Value

Type: Microsoft.Speech.Text..::..NormalizedResult

A NormalizedResult instance that contains this NormalizedResultAlternate instance.

See Also

Reference

NormalizedResultAlternate Class
NormalizedResultAlternate Members
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedResultAlternateCollection Class

[image]

NormalizedResultAlternateCollection Class
Members See Also Send Feedback

Represents a read-only collection of normalization alternates.

Inheritance Hierarchy

System..::..Object
System.Collections.ObjectModel..::..ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>
Microsoft.Speech.Text..::..NormalizedResultAlternateCollection

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

Syntax

Visual Basic (Declaration)
Public Class NormalizedResultAlternateCollection _
    Inherits ReadOnlyCollection(Of NormalizedResultAlternate)
Visual Basic (Usage)
Dim instance As NormalizedResultAlternateCollection
C#
public class NormalizedResultAlternateCollection : ReadOnlyCollection<NormalizedResultAlternate>

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

NormalizedResultAlternateCollection Members
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedResultAlternateCollection Members

[image] [image]

NormalizedResultAlternateCollection Members
NormalizedResultAlternateCollection Class Methods Properties Explicit Interface Implementations See Also Send Feedback

Represents a read-only collection of normalization alternates.

The NormalizedResultAlternateCollection type exposes the following members.

Properties

 | Name | Description
Public property | Count | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Public property | Item | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Protected property | Items | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Top

Methods

 | Name | Description
Public method | Contains | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Public method | CopyTo | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetEnumerator | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Public method | IndexOf | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

Explicit Interface Implementations

 | Name | Description
Explicit interface implemetation | ICollection<(Of <<'(T>)>>)..::..Add | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..Add | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | ICollection<(Of <<'(T>)>>)..::..Clear | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..Clear | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..Contains | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | ICollection..::..CopyTo | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IEnumerable..::..GetEnumerator | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..IndexOf | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList<(Of <<'(T>)>>)..::..Insert | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..Insert | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..IsFixedSize | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | ICollection<(Of <<'(T>)>>)..::..IsReadOnly | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..IsReadOnly | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | ICollection..::..IsSynchronized | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList<(Of <<'(T>)>>)..::..Item | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..Item | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | ICollection<(Of <<'(T>)>>)..::..Remove | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..Remove | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList<(Of <<'(T>)>>)..::..RemoveAt | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..RemoveAt | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | ICollection..::..SyncRoot | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Top

See Also

Reference

NormalizedResultAlternateCollection Class
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedResultAlternateCollection Methods

[image] [image]

NormalizedResultAlternateCollection Methods
NormalizedResultAlternateCollection Class See Also Send Feedback

The NormalizedResultAlternateCollection type exposes the following members.

Methods

 | Name | Description
Public method | Contains | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Public method | CopyTo | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetEnumerator | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Public method | IndexOf | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

Explicit Interface Implementations

 | Name | Description
Explicit interface implemetation | ICollection<(Of <<'(T>)>>)..::..Add | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..Add | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | ICollection<(Of <<'(T>)>>)..::..Clear | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..Clear | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..Contains | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | ICollection..::..CopyTo | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IEnumerable..::..GetEnumerator | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..IndexOf | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList<(Of <<'(T>)>>)..::..Insert | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..Insert | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | ICollection<(Of <<'(T>)>>)..::..Remove | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..Remove | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList<(Of <<'(T>)>>)..::..RemoveAt | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..RemoveAt | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Top

See Also

Reference

NormalizedResultAlternateCollection Class
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizedResultAlternateCollection Properties

[image] [image]

NormalizedResultAlternateCollection Properties
NormalizedResultAlternateCollection Class See Also Send Feedback

The NormalizedResultAlternateCollection type exposes the following members.

Properties

 | Name | Description
Public property | Count | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Public property | Item | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Protected property | Items | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Top

Explicit Interface Implementations

 | Name | Description
Explicit interface implemetation | IList..::..IsFixedSize | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | ICollection<(Of <<'(T>)>>)..::..IsReadOnly | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..IsReadOnly | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | ICollection..::..IsSynchronized | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList<(Of <<'(T>)>>)..::..Item | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | IList..::..Item | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Explicit interface implemetation | ICollection..::..SyncRoot | (Inherited from ReadOnlyCollection <(Of <(<' NormalizedResultAlternate >)>)>.)
Top

See Also

Reference

NormalizedResultAlternateCollection Class
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizerCollection Class

[image]

NormalizerCollection Class
Members See Also Send Feedback

Provides an application the functionality of selecting, prioritizing, and weighting normalizers.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.Text..::..NormalizerCollection

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

Syntax

Visual Basic (Declaration)
Public Class NormalizerCollection
Visual Basic (Usage)
Dim instance As NormalizerCollection
C#
public class NormalizerCollection

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

NormalizerCollection Members
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizerCollection Members

[image] [image]

NormalizerCollection Members
NormalizerCollection Class Methods See Also Send Feedback

Provides an application the functionality of selecting, prioritizing, and weighting normalizers.

The NormalizerCollection type exposes the following members.

Methods

 | Name | Description
Public method | Dispose | Disposes the underlying speech objects.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | Normalize | Performs normalization of the specified string.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

NormalizerCollection Class
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


NormalizerCollection Methods

[image] [image]

NormalizerCollection Methods
NormalizerCollection Class See Also Send Feedback

The NormalizerCollection type exposes the following members.

Methods

 | Name | Description
Public method | Dispose | Disposes the underlying speech objects.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | Normalize | Performs normalization of the specified string.
Public method | ToString | (Inherited from Object.)
Top

See Also

Reference

NormalizerCollection Class
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Dispose Method

[image]

NormalizerCollection..::..Dispose Method
NormalizerCollection Class See Also Send Feedback

Disposes the underlying speech objects.

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

Syntax

Visual Basic (Declaration)
Public Sub Dispose
Visual Basic (Usage)
Dim instance As NormalizerCollection

instance.Dispose()
C#
public void Dispose()

See Also

Reference

NormalizerCollection Class
NormalizerCollection Members
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Normalize Method

[image]

NormalizerCollection..::..Normalize Method
NormalizerCollection Class See Also Send Feedback

Performs normalization of the specified string.

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

Syntax

Visual Basic (Declaration)
Public Function Normalize ( _
    textToNormalize As String _
) As NormalizedResult
Visual Basic (Usage)
Dim instance As NormalizerCollection
Dim textToNormalize As String
Dim returnValue As NormalizedResult

returnValue = instance.Normalize(textToNormalize)
C#
public NormalizedResult Normalize(
    string textToNormalize
)

Parameters

textToNormalize
Type: System..::..String

The string to normalize.

Return Value

Type: Microsoft.Speech.Text..::..NormalizedResult

A NormalizedResult instance that contains the results from the normalization operation.

Exceptions

Exception | Condition
ArgumentNullException | Thrown when textToNormalize is nullNothingnullptrunita null reference (Nothing in Visual Basic) or when its Length property is zero.

See Also

Reference

NormalizerCollection Class
NormalizerCollection Members
Microsoft.Speech.Text Namespace
© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Microsoft.Speech.VoiceXml Class Library

[image]

Microsoft.Speech.VoiceXml Class Library
Send Feedback

This section contains the managed-code reference for the Microsoft.Speech.VoiceXml namespaces.

In This Section

You will find documentation for the following Microsoft.Speech.VoiceXml namespaces in this section:

Reference

  • Microsoft.Speech.VoiceXml

  • Microsoft.Speech.VoiceXml.Common

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Microsoft.Speech.VoiceXml Namespace

[image]

Microsoft.Speech.VoiceXml Namespace
Send Feedback

Classes

 | Class | Description
Public class | Browser | The Browser class in the Microsoft.Speech.VoiceXml namespace provides platform-independent access to the VoiceXML runtime.
Protected class | Browser..::..CallProxy | The CallProxy class is used by classes that derive from Browser to pass information about calls to the VoiceXML interpreter.

Enumerations

 | Enumeration | Description
Protected enumeration | Browser..::..CallProxy..::..ProxyCallState | The ProxyCallState enumeration is used to relay information about the current call state.
Protected enumeration | Browser..::..CallProxy..::..ProxyCallStateTransitionReason | Represents the reasons for call state transitions.
Protected enumeration | Browser..::..CallProxy..::..ProxyPageState | Represents the state of an attempt to load a VoiceXML document.
Protected enumeration | Browser..::..CallProxy..::..ProxyRecorderState | Represents the state of the recorder.
Protected enumeration | Browser..::..CallProxy..::..ProxyReferState | Indicates possible states for the signaling session.
Protected enumeration | Browser..::..CallProxy..::..ProxyTransferType | Indicates the type of transfer requested in the VoiceXML document.
Send feedback on this topic to Microsoft.


Browser Class

[image]

Browser Class
Members See Also Send Feedback

The Browser class in the Microsoft.Speech.VoiceXml namespace provides platform-independent access to the VoiceXML runtime.

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

Syntax

C#
public abstract class Browser : IDisposable

Remarks

Browser is an abstract class that provides a base from which to derive platform-specific classes. The Browser class cannot be used directly. Most developers will use a platform-specific VoiceXML Browser class that derives from the base Browser class.

An active Browser instance contains a VoiceXML interpreter and the system resources that are required to process an automated interaction with a caller including speech engines, a Dual-Tone Multi-Frequency (DTMF) tone controller, a recorder, and connections to audio inputs and outputs.

You can launch a Browser instance in either synchronous or asynchronous mode.

NOTE: Only use the synchronous Run(Uri, CookieContainer) method for prototyping and experimentation. Do not use it in a production application.

During an asynchronous Browser session, events are raised that report the state of the session to the application. At the end of an asynchronous Browser session, the handler for the SessionCompleted event contains information about the result of the session.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.VoiceXml..::..Browser

See Also

Browser Members
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser Members

[image] [image]

Browser Members
Browser Class Constructors Methods Properties Events See Also Send Feedback

The Browser type exposes the following members.

Constructors

 | Name | Description
Protected method | Browser | Creates a new instance of the Browser class.

Methods

 | Name | Description
Public method | Dispose()()()() | Disposes the Browser object and releases native resources.
Protected method | Dispose(Boolean) | Disposes the Browser object and releases resources used during the session.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | OnDisconnected | Raises a Disconnected event during an asynchronous Browser session.
Protected method | OnDisconnecting | Raises a Disconnecting event during an asynchronous Browser session.
Protected method | OnSessionCompleted | Raises a SessionCompleted event during an asynchronous Browser session.
Protected method | OnTransferred(Object, TransferredEventArgs) | Raises a Transferred event during an asynchronous Browser session.
Protected method | OnTransferred(Object, String, TransferType, TransferState) | Provides information about the TargetSip, the type()()()(), and the state()()()() for a Transferred event during an asynchronous Browser session.
Protected method | OnTransferring(Object, TransferringEventArgs) | Raises a Transferring event during an asynchronous Browser session.
Protected method | OnTransferring(Object, String, TransferType, TransferState) | Provides information about the TargetSip, the type()()()(), and the state()()()() for a Transferring event during an asynchronous Browser session.
Public method | Run | Launches a synchronous instance of the VoiceXML Browser and specifies the URI of the VoiceXML start page to load, and a CookieContainer parameter.
Public method | RunAsync | Launches an asynchronous instance of the VoiceXML Browser, specifying the URI of the VoiceXML start page to load, and a CookieContainer parameter.
Protected method | SetCallProxy | Associates a VoiceXML Browser session with a Browser..::..CallProxy object.
Protected method | SetInputToAudioStream | Assigns a specific audio stream as the input for the speech recognition engine.
Protected method | SetInputToDefaultAudioDevice | Assigns the system default audio input device as the input to the speech recognition engine.
Protected method | SetInputToNull | Assigns a null device as the input to the speech recognition engine.
Protected method | SetInputToWaveFile | Assigns a specific .WAV format audio file as input to the speech recognition engine.
Protected method | SetInputToWaveStream | Assigns an audio stream in .WAV format as input to the speech recognition engine.
Protected method | SetOutputToAudioStream | Assigns a specific audio stream as the output of the speech synthesizer.
Protected method | SetOutputToDefaultAudioDevice | Assigns the system default audio output device as the output of the speech synthesizer.
Protected method | SetOutputToNull | Assigns a null device as the output of the speech synthesizer.
Protected method | SetOutputToWaveFile | Assigns a specific .WAV format audio file as the output of the speech synthesizer.
Protected method | SetOutputToWaveStream | Assigns an audio stream in .WAV format as output of the speech synthesizer.
Public method | StopAsync | Terminates the processing of a VoiceXML page, but allows the Browser to finish processing the current VoiceXML element.
Public method | ToString | (Inherited from Object.)

Properties

 | Name | Description
Public property | State | Gets the SessionState to determine whether a Browser instance is running.

Events

 | Name | Description
Public event | Disconnected | Raised after a call is disconnected from an asynchronous Browser session.
Public event | Disconnecting | Raised just before a call is disconnected from an asynchronous Browser session.
Public event | SessionCompleted | Raised when the Browser exits a VoiceXML page during an asynchronous Browser session.
Public event | Transferred | Raised when the VoiceXML runtime has completed a phone call transfer to a recipient during an asynchronous Browser session.
Public event | Transferring | Raised when the VoiceXML page is about to process a <transfer> element during an asynchronous Browser session.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser Constructor

[image]

Browser Constructor
Browser Class See Also Send Feedback

Creates a new instance of the Browser class.

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

Syntax

C#
protected Browser()

Remarks

The default constructor returns an empty object.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser Methods

[image] [image]

Browser Methods
Browser Class See Also Send Feedback

The Browser type exposes the following members.

Methods

 | Name | Description
Public method | Dispose()()()() | Disposes the Browser object and releases native resources.
Protected method | Dispose(Boolean) | Disposes the Browser object and releases resources used during the session.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | OnDisconnected | Raises a Disconnected event during an asynchronous Browser session.
Protected method | OnDisconnecting | Raises a Disconnecting event during an asynchronous Browser session.
Protected method | OnSessionCompleted | Raises a SessionCompleted event during an asynchronous Browser session.
Protected method | OnTransferred(Object, TransferredEventArgs) | Raises a Transferred event during an asynchronous Browser session.
Protected method | OnTransferred(Object, String, TransferType, TransferState) | Provides information about the TargetSip, the type()()()(), and the state()()()() for a Transferred event during an asynchronous Browser session.
Protected method | OnTransferring(Object, TransferringEventArgs) | Raises a Transferring event during an asynchronous Browser session.
Protected method | OnTransferring(Object, String, TransferType, TransferState) | Provides information about the TargetSip, the type()()()(), and the state()()()() for a Transferring event during an asynchronous Browser session.
Public method | Run | Launches a synchronous instance of the VoiceXML Browser and specifies the URI of the VoiceXML start page to load, and a CookieContainer parameter.
Public method | RunAsync | Launches an asynchronous instance of the VoiceXML Browser, specifying the URI of the VoiceXML start page to load, and a CookieContainer parameter.
Protected method | SetCallProxy | Associates a VoiceXML Browser session with a Browser..::..CallProxy object.
Protected method | SetInputToAudioStream | Assigns a specific audio stream as the input for the speech recognition engine.
Protected method | SetInputToDefaultAudioDevice | Assigns the system default audio input device as the input to the speech recognition engine.
Protected method | SetInputToNull | Assigns a null device as the input to the speech recognition engine.
Protected method | SetInputToWaveFile | Assigns a specific .WAV format audio file as input to the speech recognition engine.
Protected method | SetInputToWaveStream | Assigns an audio stream in .WAV format as input to the speech recognition engine.
Protected method | SetOutputToAudioStream | Assigns a specific audio stream as the output of the speech synthesizer.
Protected method | SetOutputToDefaultAudioDevice | Assigns the system default audio output device as the output of the speech synthesizer.
Protected method | SetOutputToNull | Assigns a null device as the output of the speech synthesizer.
Protected method | SetOutputToWaveFile | Assigns a specific .WAV format audio file as the output of the speech synthesizer.
Protected method | SetOutputToWaveStream | Assigns an audio stream in .WAV format as output of the speech synthesizer.
Public method | StopAsync | Terminates the processing of a VoiceXML page, but allows the Browser to finish processing the current VoiceXML element.
Public method | ToString | (Inherited from Object.)

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Dispose Method

[image] [image]

Browser..::..Dispose Method
Browser Class See Also Send Feedback

Overload List

 | Name | Description
Public method | Dispose()()()() | Disposes the Browser object and releases native resources.
Protected method | Dispose(Boolean) | Disposes the Browser object and releases resources used during the session.

See Also

Browser Class
Browser Members
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Dispose Method

[image]

Browser..::..Dispose Method
Browser Class See Also Send Feedback

Disposes the Browser object and releases native resources.

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

Syntax

C#
public void Dispose()

Implements

IDisposable..::..Dispose()()()()

See Also

Browser Class
Dispose Overload
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Dispose Method (Boolean)

[image]

Browser..::..Dispose Method (Boolean)
Browser Class See Also Send Feedback

Disposes the Browser object and releases resources used during the session.

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

Syntax

C#
protected virtual void Dispose(
    bool disposing
)

Parameters

disposing
Type: System..::..Boolean
Indicates whether the Browser is directly disposing.

Remarks

This method can be overridden by derived Browser classes.

See Also

Browser Class
Dispose Overload
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


OnDisconnected Method

[image]

Browser..::..OnDisconnected Method
Browser Class See Also Send Feedback

Raises a Disconnected event during an asynchronous Browser session.

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

Syntax

C#
protected virtual void OnDisconnected(
    Object sender,
    DisconnectedEventArgs e
)

Parameters

sender
Type: System..::..Object
The object that initiated the Disconnected event.
e
Type: Microsoft.Speech.VoiceXml.Common..::..DisconnectedEventArgs
An instance of DisconnectedEventArgs that contains information from the Disconnected event.

Remarks

You can override the OnDisconnected method to customize its functionality.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


OnDisconnecting Method

[image]

Browser..::..OnDisconnecting Method
Browser Class See Also Send Feedback

Raises a Disconnecting event during an asynchronous Browser session.

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

Syntax

C#
protected virtual void OnDisconnecting(
    Object sender,
    DisconnectingEventArgs e
)

Parameters

sender
Type: System..::..Object
The object that initiated the Disconnecting event.
e
Type: Microsoft.Speech.VoiceXml.Common..::..DisconnectingEventArgs
An instance of DisconnectingEventArgs that contains information from the Disconnecting event.

Remarks

You can override the OnDisconnecting method to customize its functionality.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


OnSessionCompleted Method

[image]

Browser..::..OnSessionCompleted Method
Browser Class See Also Send Feedback

Raises a SessionCompleted event during an asynchronous Browser session.

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

Syntax

C#
protected virtual void OnSessionCompleted(
    Object sender,
    SessionCompletedEventArgs e
)

Parameters

sender
Type: System..::..Object
The object that initiated the SessionCompleted event.
e
Type: Microsoft.Speech.VoiceXml.Common..::..SessionCompletedEventArgs
An instance of SessionCompletedEventArgs that contains information from the SessionCompleted event.

Remarks

You can override the OnSessionCompleted method to customize its functionality.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


OnTransferred Method

[image] [image]

Browser..::..OnTransferred Method
Browser Class See Also Send Feedback

Overload List

 | Name | Description
Protected method | OnTransferred(Object, TransferredEventArgs) | Raises a Transferred event during an asynchronous Browser session.
Protected method | OnTransferred(Object, String, TransferType, TransferState) | Provides information about the TargetSip, the type()()()(), and the state()()()() for a Transferred event during an asynchronous Browser session.

See Also

Browser Class
Browser Members
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


OnTransferred Method (Object, TransferredEventArgs)

[image]

Browser..::..OnTransferred Method (Object, TransferredEventArgs)
Browser Class See Also Send Feedback

Raises a Transferred event during an asynchronous Browser session.

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

Syntax

C#
protected virtual void OnTransferred(
    Object sender,
    TransferredEventArgs e
)

Parameters

sender
Type: System..::..Object
The object that initiated the Transferred event.
e
Type: Microsoft.Speech.VoiceXml.Common..::..TransferredEventArgs
An instance of TransferredEventArgs that contains information from the Transferred event.

Remarks

You can override the OnTransferred method to customize its functionality.

See Also

Browser Class
OnTransferred Overload
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


OnTransferred Method (Object, String, TransferType, TransferState)

[image]

Browser..::..OnTransferred Method (Object, String, TransferType, TransferState)
Browser Class See Also Send Feedback

Provides information about the TargetSip, the type()()()(), and the state()()()() for a Transferred event during an asynchronous Browser session.

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

Syntax

C#
protected virtual void OnTransferred(
    Object sender,
    string targetSip,
    TransferType transferType,
    TransferState transferState
)

Parameters

sender
Type: System..::..Object
The object that initiated the Transferred event.
targetSip
Type: System..::..String
The SIP URI of the transfer destination.
transferType
Type: Microsoft.Speech.VoiceXml.Common..::..TransferType
The type of phone call transfer to be performed.
transferState
Type: Microsoft.Speech.VoiceXml.Common..::..TransferState
The state of a VoiceXML phone call transfer request.

See Also

Browser Class
OnTransferred Overload
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


OnTransferring Method

[image] [image]

Browser..::..OnTransferring Method
Browser Class See Also Send Feedback

Overload List

 | Name | Description
Protected method | OnTransferring(Object, TransferringEventArgs) | Raises a Transferring event during an asynchronous Browser session.
Protected method | OnTransferring(Object, String, TransferType, TransferState) | Provides information about the TargetSip, the type()()()(), and the state()()()() for a Transferring event during an asynchronous Browser session.

See Also

Browser Class
Browser Members
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


OnTransferring Method (Object, TransferringEventArgs)

[image]

Browser..::..OnTransferring Method (Object, TransferringEventArgs)
Browser Class See Also Send Feedback

Raises a Transferring event during an asynchronous Browser session.

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

Syntax

C#
protected virtual void OnTransferring(
    Object sender,
    TransferringEventArgs e
)

Parameters

sender
Type: System..::..Object
The object that initiated the Transferring event.
e
Type: Microsoft.Speech.VoiceXml.Common..::..TransferringEventArgs
An instance of TransferringEventArgs that contains information from the Transferring event.

Remarks

You can override the OnTransferring method to customize its functionality.

See Also

Browser Class
OnTransferring Overload
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


OnTransferring Method (Object, String, TransferType, TransferState)

[image]

Browser..::..OnTransferring Method (Object, String, TransferType, TransferState)
Browser Class See Also Send Feedback

Provides information about the TargetSip, the type()()()(), and the state()()()() for a Transferring event during an asynchronous Browser session.

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

Syntax

C#
protected virtual void OnTransferring(
    Object sender,
    string targetSip,
    TransferType transferType,
    TransferState transferState
)

Parameters

sender
Type: System..::..Object
The object that initiated the Transferring event.
targetSip
Type: System..::..String
The SIP URI of the transfer destination.
transferType
Type: Microsoft.Speech.VoiceXml.Common..::..TransferType
The type of phone call transfer to be performed.
transferState
Type: Microsoft.Speech.VoiceXml.Common..::..TransferState
The state of a VoiceXML phone call transfer request.

See Also

Browser Class
OnTransferring Overload
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Run Method

[image]

Browser..::..Run Method
Browser Class See Also Send Feedback

Launches a synchronous instance of the VoiceXML Browser and specifies the URI of the VoiceXML start page to load, and a CookieContainer parameter.

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

Syntax

C#
public VoiceXmlResult Run(
    Uri vxmlPage,
    CookieContainer container
)

Parameters

vxmlPage
Type: System..::..Uri
The URI of the VoiceXML start page to load.
container
Type: System.Net..::..CookieContainer
Contains state information associated with a request for a VoiceXML page. The value can be null.

Return Value

A VoiceXMLResult object that references the synchronous operation.

Remarks

When initiated, the Run method checks the value of the Browser's State property to determine if the Browser is already running. If Browser.State equals Active, then the Browser is running and the Run method throws an InvalidOperationException. If Browser.State equals Idle, then the Run method sets Browser.State to Active and launches the Browser instance.

You can instantiate and run multiple Browser objects simultaneously, for example Browser1, Browser2, Browser3. You cannot run the same Browser instance concurrently on multiple sessions, for example Browser1(a), Browser1(b), Browser1(c).

Upon successful completion of a VoiceXML page, the Run method returns a VoiceXmlResult object, which may include a CookieContainer object with state information about the session for use by the Web server serving the VoiceXML documents.

If the session completes without errors, that is if the ExitReason value is HostExitRequested, ExitElementEncountered, or DialogEndEncountered, then the UnhandledThrowElement will be null.

Exceptions

Exception | Condition
System..::..ArgumentNullException | Thrown when the Run method is called and the URI of the VoiceXML start page to load contains a null argument value.
System..::..InvalidOperationException | Thrown when the Run method is called on a Browser instance that is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


RunAsync Method

[image]

Browser..::..RunAsync Method
Browser Class See Also Send Feedback

Launches an asynchronous instance of the VoiceXML Browser, specifying the URI of the VoiceXML start page to load, and a CookieContainer parameter.

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

Syntax

C#
public void RunAsync(
    Uri vxmlPage,
    CookieContainer container
)

Parameters

vxmlPage
Type: System..::..Uri
The URI of the VoiceXML start page to load.
container
Type: System.Net..::..CookieContainer
Contains state information associated with a request for a VoiceXML page. The value can be null.

Remarks

When initiated, the RunAsync method checks the value of the Browser's State property to determine if the Browser is already running. If Browser.State equals Active, then the Browser is running and the RunAsync method throws an InvalidOperationException. If Browser.State equals Idle, then the RunAsync method sets Browser.State to Active and launches the Browser instance.

You can instantiate and run multiple Browser objects simultaneously, for example Browser1, Browser2, Browser3. You cannot run the same Browser instance concurrently on multiple sessions, for example Browser1(a), Browser1(b), Browser1(c).

The Browser may raise any of the following events during an asynchronous session: Disconnecting, Disconnected, Transferring, Transferred, or SessionCompleted. The SessionCompleted event is raised at the end of an asynchronous Browser session, and represents the result of the Browser session with a VoiceXmlResult object.

Exceptions

Exception | Condition
System..::..ArgumentNullException | Thrown when the RunAsync method is called and the URI of the VoiceXML start page to load contains a null argument value.
System..::..InvalidOperationException | Thrown when the RunAsync method is called on a Browser instance that is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


SetCallProxy Method

[image]

Browser..::..SetCallProxy Method
Browser Class See Also Send Feedback

Associates a VoiceXML Browser session with a Browser..::..CallProxy object.

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

Syntax

C#
protected void SetCallProxy(
    Browser..::..CallProxy proxy
)

Parameters

proxy
Type: Microsoft.Speech.VoiceXml..::..Browser..::..CallProxy
Represents a CallProxy object.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


SetInputToAudioStream Method

[image]

Browser..::..SetInputToAudioStream Method
Browser Class See Also Send Feedback

Assigns a specific audio stream as the input for the speech recognition engine.

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

Syntax

C#
protected void SetInputToAudioStream(
    Stream audioSource,
    SpeechAudioFormatInfo audioSourceFormat
)

Parameters

audioSource
Type: System.IO..::..Stream
The specific stream that will be the input for the speech recognition engine.
audioSourceFormat
Type: Microsoft.Speech.AudioFormat..::..SpeechAudioFormatInfo
The format of the audio in the input stream.

Exceptions

Exception | Condition
System..::..InvalidOperationException | Thrown when the SetInputToAudioStream(Stream audioSource, SpeechAudioFormatInfo audioSourceFormat) method is called on a Browser instance that is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


SetInputToDefaultAudioDevice Method

[image]

Browser..::..SetInputToDefaultAudioDevice Method
Browser Class See Also Send Feedback

Assigns the system default audio input device as the input to the speech recognition engine.

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

Syntax

C#
protected void SetInputToDefaultAudioDevice()

Exceptions

Exception | Condition
System..::..InvalidOperationException | Thrown when the SetInputToDefaultAudioDevice() method is called on a Browser instance that is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


SetInputToNull Method

[image]

Browser..::..SetInputToNull Method
Browser Class See Also Send Feedback

Assigns a null device as the input to the speech recognition engine.

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

Syntax

C#
protected void SetInputToNull()

Remarks

This detaches the audio input without disconnecting from the speech recognition engine.

Exceptions

Exception | Condition
System..::..InvalidOperationException | Thrown when the SetInputToNull() method is called on a Browser instance that is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


SetInputToWaveFile Method

[image]

Browser..::..SetInputToWaveFile Method
Browser Class See Also Send Feedback

Assigns a specific .WAV format audio file as input to the speech recognition engine.

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

Syntax

C#
protected void SetInputToWaveFile(
    string audioInputPath
)

Parameters

audioInputPath
Type: System..::..String
The path to the .WAV file to be used as input.

Exceptions

Exception | Condition
System..::..InvalidOperationException | Thrown when the SetInputToWaveFile(string audioInputPath) method is called on a Browser instance that is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


SetInputToWaveStream Method

[image]

Browser..::..SetInputToWaveStream Method
Browser Class See Also Send Feedback

Assigns an audio stream in .WAV format as input to the speech recognition engine.

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

Syntax

C#
protected void SetInputToWaveStream(
    Stream audioSource
)

Parameters

audioSource
Type: System.IO..::..Stream
A stream instance connected to an audio source in .WAV format

Exceptions

Exception | Condition
System..::..InvalidOperationException | Thrown when the SetInputToWaveStream(Stream audioSource) method is called on a Browser instance that is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


SetOutputToAudioStream Method

[image]

Browser..::..SetOutputToAudioStream Method
Browser Class See Also Send Feedback

Assigns a specific audio stream as the output of the speech synthesizer.

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

Syntax

C#
protected void SetOutputToAudioStream(
    Stream audioOutput,
    SpeechAudioFormatInfo audioOutputFormat
)

Parameters

audioOutput
Type: System.IO..::..Stream
The specific stream that will receive the output of the speech synthesizer.
audioOutputFormat
Type: Microsoft.Speech.AudioFormat..::..SpeechAudioFormatInfo
The format of the audio in the output stream.

Exceptions

Exception | Condition
System..::..InvalidOperationException | Thrown when the SetOutputToAudioStream(Stream audioOutput, SpeechAudioFormatInfo audioOutputFormat) method is called on a Browser instance that is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


SetOutputToDefaultAudioDevice Method

[image]

Browser..::..SetOutputToDefaultAudioDevice Method
Browser Class See Also Send Feedback

Assigns the system default audio output device as the output of the speech synthesizer.

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

Syntax

C#
protected void SetOutputToDefaultAudioDevice()

Exceptions

Exception | Condition
System..::..InvalidOperationException | Thrown when the SetOutputToDefaultAudioDevice() method is called on a Browser instance that is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


SetOutputToNull Method

[image]

Browser..::..SetOutputToNull Method
Browser Class See Also Send Feedback

Assigns a null device as the output of the speech synthesizer.

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

Syntax

C#
protected void SetOutputToNull()

Exceptions

Exception | Condition
System..::..InvalidOperationException | Thrown when the SetOutputToNull() method is called on a Browser instance that is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


SetOutputToWaveFile Method

[image]

Browser..::..SetOutputToWaveFile Method
Browser Class See Also Send Feedback

Assigns a specific .WAV format audio file as the output of the speech synthesizer.

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

Syntax

C#
protected void SetOutputToWaveFile(
    string audioOutputPath
)

Parameters

audioOutputPath
Type: System..::..String
The path to the .WAV file to be used as output.

Exceptions

Exception | Condition
System..::..InvalidOperationException | Thrown when the SetOutputToWaveFile(string audioOutputPath) method is called on a Browser instance that is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


SetOutputToWaveStream Method

[image]

Browser..::..SetOutputToWaveStream Method
Browser Class See Also Send Feedback

Assigns an audio stream in .WAV format as output of the speech synthesizer.

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

Syntax

C#
protected void SetOutputToWaveStream(
    Stream audioOutput
)

Parameters

audioOutput
Type: System.IO..::..Stream
A stream instance connected to an audio target in .WAV format

Exceptions

Exception | Condition
System..::..InvalidOperationException | Thrown when the SetOutputToWaveStream(Stream audioOutput) method is called on a Browser instance that is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


StopAsync Method

[image]

Browser..::..StopAsync Method
Browser Class See Also Send Feedback

Terminates the processing of a VoiceXML page, but allows the Browser to finish processing the current VoiceXML element.

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

Syntax

C#
public virtual void StopAsync()

Remarks

The StopAsync method resets the Browser state, freeing the Browser for a new session. If the Browser has already stopped, calling StopAsync has no effect. You can override the StopAsync method to customize its functionality.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser Properties

[image] [image]

Browser Properties
Browser Class See Also Send Feedback

The Browser type exposes the following members.

Properties

 | Name | Description
Public property | State | Gets the SessionState to determine whether a Browser instance is running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


State Property

[image]

Browser..::..State Property
Browser Class See Also Send Feedback

Gets the SessionState to determine whether a Browser instance is running.

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

Syntax

C#
public SessionState State { get; }

Remarks

The value of the State property is Active if the Browser is running, or Idle if the Browser is not running.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser Events

[image] [image]

Browser Events
Browser Class See Also Send Feedback

The Browser type exposes the following members.

Events

 | Name | Description
Public event | Disconnected | Raised after a call is disconnected from an asynchronous Browser session.
Public event | Disconnecting | Raised just before a call is disconnected from an asynchronous Browser session.
Public event | SessionCompleted | Raised when the Browser exits a VoiceXML page during an asynchronous Browser session.
Public event | Transferred | Raised when the VoiceXML runtime has completed a phone call transfer to a recipient during an asynchronous Browser session.
Public event | Transferring | Raised when the VoiceXML page is about to process a <transfer> element during an asynchronous Browser session.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Disconnected Event

[image]

Browser..::..Disconnected Event
Browser Class See Also Send Feedback

Raised after a call is disconnected from an asynchronous Browser session.

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

Syntax

C#
public event EventHandler<DisconnectedEventArgs> Disconnected

Remarks

When the Disconnected event is raised, the State property on the DisconnectedEventArgs instance indicates the DisconnectState.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Disconnecting Event

[image]

Browser..::..Disconnecting Event
Browser Class See Also Send Feedback

Raised just before a call is disconnected from an asynchronous Browser session.

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

Syntax

C#
public event EventHandler<DisconnectingEventArgs> Disconnecting

Remarks

When the Disconnecting event is raised, the SessionState property on the DisconnectingEventArgs instance indicates the session state.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


SessionCompleted Event

[image]

Browser..::..SessionCompleted Event
Browser Class See Also Send Feedback

Raised when the Browser exits a VoiceXML page during an asynchronous Browser session.

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

Syntax

C#
public event EventHandler<SessionCompletedEventArgs> SessionCompleted

Remarks

When the SessionCompleted event is raised, the Result property on the SessionCompletedEventArgs instance contains a VoiceXmlResult object, which has information about the result of the session.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Transferred Event

[image]

Browser..::..Transferred Event
Browser Class See Also Send Feedback

Raised when the VoiceXML runtime has completed a phone call transfer to a recipient during an asynchronous Browser session.

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

Syntax

C#
public event EventHandler<TransferredEventArgs> Transferred

Remarks

When the Transferred event is raised, the State property on the TransferredEventArgs instance indicates the transfer state, and the Type property on the TransferredEventArgs instance indicates the transfer type.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Transferring Event

[image]

Browser..::..Transferring Event
Browser Class See Also Send Feedback

Raised when the VoiceXML page is about to process a <transfer> element during an asynchronous Browser session.

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

Syntax

C#
public event EventHandler<TransferringEventArgs> Transferring

Remarks

When the Transferring event is raised, the State property on the TransferringEventArgs instance indicates the transfer state, and the Type property on the TransferringEventArgs instance indicates the transfer type.

See Also

Browser Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser.CallProxy Class

[image]

Browser..::..CallProxy Class
Browser Class Members See Also Send Feedback

The CallProxy class is used by classes that derive from Browser to pass information about calls to the VoiceXML interpreter.

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

Syntax

C#
protected abstract class CallProxy

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.VoiceXml..::..Browser..::..CallProxy

See Also

Browser..::..CallProxy Members
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser.CallProxy Members

[image] [image]

Browser..::..CallProxy Members
Browser..::..CallProxy Class Constructors Methods Properties See Also Send Feedback

The Browser class in the Microsoft.Speech.VoiceXml namespace provides platform-independent access to the VoiceXML runtime.

The Browser..::..CallProxy type exposes the following members.

Constructors

 | Name | Description
Protected method | Browser..::..CallProxy | Creates a new instance of the CallProxy object.

Methods

 | Name | Description
Protected method | BeginAccept | Accepts an incoming call.
Protected method | BeginTerminate | Terminates the call. A terminated call is no longer usable.
Protected method | BeginTransfer(String, AsyncCallback, Object) | Initiates a transfer request to the remote participant.
Protected method | BeginTransfer(String, Boolean, AsyncCallback, Object) | Initiates a transfer request to the remote participant.
Protected method | BeginTransferSupervised | Initiates a supervised transfer request to the remote participant.
Protected method | EndAccept | This method is used to determine whether the corresponding operation completed successfully. This method will wait if the operation has not yet completed.
Protected method | EndTerminate | This method is used to determine whether the corresponding operation completed successfully. This method will wait if the operation has not yet completed.
Protected method | EndTransfer | The EndTransfer method is used to determine whether the corresponding operation completed successfully. This method will wait if the operation has not yet completed.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | NotifyOpenCompleted | Raises an OpenCompleted event.
Protected method | NotifyRecorderStopped | Raises a RecorderStopped event.
Protected method | NotifyStateChanged | Raises a StateChanged event.
Protected method | NotifyToneReceived | Raises a ToneReceived event.
Protected method | NotifyTransferStateChanged | Raises a TransferStateChanged event.
Protected method | OpenAsync | Accepts an incoming telephony session invite and sends a response.
Protected method | StartRecording | Begins recording audio input from the call.
Protected method | StopRecording | Stops recording audio.
Public method | ToString | (Inherited from Object.)

Properties

 | Name | Description
Protected property | CallId | Gets the CallID of the current call.
Protected property | LocalParticipantUri | Gets the URI of the local call.
Protected property | RecorderState | Gets the state of the Recorder.
Protected property | RemoteParticipantUri | Gets the URI of the remote call.
Protected property | State | Gets the current call state.
Protected property | TargetSip | Gets and sets the SIP for call transfers.
Protected property | TransferTypeRequested | Gets the transfer type of the requested transfer.

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser.CallProxy Constructor

[image]

Browser..::..CallProxy Constructor
Browser..::..CallProxy Class See Also Send Feedback

Creates a new instance of the CallProxy object.

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

Syntax

C#
protected CallProxy()

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser.CallProxy Methods

[image] [image]

Browser..::..CallProxy Methods
Browser..::..CallProxy Class See Also Send Feedback

The Browser..::..CallProxy type exposes the following members.

Methods

 | Name | Description
Protected method | BeginAccept | Accepts an incoming call.
Protected method | BeginTerminate | Terminates the call. A terminated call is no longer usable.
Protected method | BeginTransfer(String, AsyncCallback, Object) | Initiates a transfer request to the remote participant.
Protected method | BeginTransfer(String, Boolean, AsyncCallback, Object) | Initiates a transfer request to the remote participant.
Protected method | BeginTransferSupervised | Initiates a supervised transfer request to the remote participant.
Protected method | EndAccept | This method is used to determine whether the corresponding operation completed successfully. This method will wait if the operation has not yet completed.
Protected method | EndTerminate | This method is used to determine whether the corresponding operation completed successfully. This method will wait if the operation has not yet completed.
Protected method | EndTransfer | The EndTransfer method is used to determine whether the corresponding operation completed successfully. This method will wait if the operation has not yet completed.
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | NotifyOpenCompleted | Raises an OpenCompleted event.
Protected method | NotifyRecorderStopped | Raises a RecorderStopped event.
Protected method | NotifyStateChanged | Raises a StateChanged event.
Protected method | NotifyToneReceived | Raises a ToneReceived event.
Protected method | NotifyTransferStateChanged | Raises a TransferStateChanged event.
Protected method | OpenAsync | Accepts an incoming telephony session invite and sends a response.
Protected method | StartRecording | Begins recording audio input from the call.
Protected method | StopRecording | Stops recording audio.
Public method | ToString | (Inherited from Object.)

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


BeginAccept Method

[image]

Browser..::..CallProxy..::..BeginAccept Method
Browser..::..CallProxy Class See Also Send Feedback

Accepts an incoming call.

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

Syntax

C#
protected abstract IAsyncResult BeginAccept(
    AsyncCallback userCallback,
    Object state
)

Parameters

userCallback
Type: System..::..AsyncCallback
The method to be called when the asynchronous operation is completed.
state
Type: System..::..Object
A user-provided object that distinguishes this particular asynchronous operation from other asynchronous operations.

Remarks

The state of the call can change if the remote party decides to cancel the call.

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


BeginTerminate Method

[image]

Browser..::..CallProxy..::..BeginTerminate Method
Browser..::..CallProxy Class See Also Send Feedback

Terminates the call. A terminated call is no longer usable.

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

Syntax

C#
protected abstract IAsyncResult BeginTerminate(
    AsyncCallback userCallback,
    Object state
)

Parameters

userCallback
Type: System..::..AsyncCallback
The method to be called when the asynchronous operation is completed.
state
Type: System..::..Object
A user-provided object that distinguishes this particular asynchronous operation from other asynchronous operations.

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


BeginTransfer Method

[image] [image]

Browser..::..CallProxy..::..BeginTransfer Method
Browser..::..CallProxy Class See Also Send Feedback

Overload List

 | Name | Description
Protected method | BeginTransfer(String, AsyncCallback, Object) | Initiates a transfer request to the remote participant.
Protected method | BeginTransfer(String, Boolean, AsyncCallback, Object) | Initiates a transfer request to the remote participant.

See Also

Browser..::..CallProxy Class
Browser..::..CallProxy Members
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


BeginTransfer Method (String, AsyncCallback, Object)

[image]

Browser..::..CallProxy..::..BeginTransfer Method (String, AsyncCallback, Object)
Browser..::..CallProxy Class See Also Send Feedback

Initiates a transfer request to the remote participant.

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

Syntax

C#
protected abstract IAsyncResult BeginTransfer(
    string targetUri,
    AsyncCallback userCallback,
    Object state
)

Parameters

targetUri
Type: System..::..String
The URI of the transfer target.
userCallback
Type: System..::..AsyncCallback
The method to be called when the asynchronous operation is completed.
state
Type: System..::..Object
A user-provided object that distinguishes this particular asynchronous operation from other asynchronous operations.

See Also

Browser..::..CallProxy Class
BeginTransfer Overload
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


BeginTransfer Method (String, Boolean, AsyncCallback, Object)

[image]

Browser..::..CallProxy..::..BeginTransfer Method (String, Boolean, AsyncCallback, Object)
Browser..::..CallProxy Class See Also Send Feedback

Initiates a transfer request to the remote participant.

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

Syntax

C#
protected abstract IAsyncResult BeginTransfer(
    string targetUri,
    bool attended,
    AsyncCallback userCallback,
    Object state
)

Parameters

targetUri
Type: System..::..String
The transfer target URI.
attended
Type: System..::..Boolean
Boolean value that is true if the transfer is attended.
userCallback
Type: System..::..AsyncCallback
The method to be called when the asynchronous operation is completed.
state
Type: System..::..Object
A user-provided object that distinguishes this particular asynchronous operation from other asynchronous operations.

See Also

Browser..::..CallProxy Class
BeginTransfer Overload
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


BeginTransferSupervised Method

[image]

Browser..::..CallProxy..::..BeginTransferSupervised Method
Browser..::..CallProxy Class See Also Send Feedback

Initiates a supervised transfer request to the remote participant.

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

Syntax

C#
protected abstract IAsyncResult BeginTransferSupervised()

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


EndAccept Method

[image]

Browser..::..CallProxy..::..EndAccept Method
Browser..::..CallProxy Class See Also Send Feedback

This method is used to determine whether the corresponding operation completed successfully. This method will wait if the operation has not yet completed.

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

Syntax

C#
protected abstract void EndAccept(
    IAsyncResult result
)

Parameters

result
Type: System..::..IAsyncResult
The reference to the pending asynchronous operation.

Exceptions

Exception | Condition
System..::..InvalidOperationException | Thrown when this method is invoked multiple times using the same asyncResult.
System..::..ArgumentNullException | Thrown when the result parameter is null.
System..::..ArgumentException | Thrown when the result parameter is invalid.

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


EndTerminate Method

[image]

Browser..::..CallProxy..::..EndTerminate Method
Browser..::..CallProxy Class See Also Send Feedback

This method is used to determine whether the corresponding operation completed successfully. This method will wait if the operation has not yet completed.

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

Syntax

C#
protected abstract void EndTerminate(
    IAsyncResult result
)

Parameters

result
Type: System..::..IAsyncResult
The reference to the pending asynchronous operation.

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


EndTransfer Method

[image]

Browser..::..CallProxy..::..EndTransfer Method
Browser..::..CallProxy Class See Also Send Feedback

The EndTransfer method is used to determine whether the corresponding operation completed successfully. This method will wait if the operation has not yet completed.

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

Syntax

C#
protected abstract void EndTransfer(
    IAsyncResult result
)

Parameters

result
Type: System..::..IAsyncResult
The reference to the pending asynchronous operation.

Exceptions

Exception | Condition
System..::..InvalidOperationException | Thrown when this method is invoked multiple times using the same asyncResult.
System..::..ArgumentNullException | Thrown when the result parameter is null.
System..::..ArgumentException | Thrown when the result parameter is invalid.

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


NotifyOpenCompleted Method

[image]

Browser..::..CallProxy..::..NotifyOpenCompleted Method
Browser..::..CallProxy Class See Also Send Feedback

Raises an OpenCompleted event.

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

Syntax

C#
protected void NotifyOpenCompleted(
    Object sender,
    bool canceled
)

Parameters

sender
Type: System..::..Object
canceled
Type: System..::..Boolean

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


NotifyRecorderStopped Method

[image]

Browser..::..CallProxy..::..NotifyRecorderStopped Method
Browser..::..CallProxy Class See Also Send Feedback

Raises a RecorderStopped event.

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

Syntax

C#
protected void NotifyRecorderStopped(
    Object sender,
    bool methodResult,
    Exception exception
)

Parameters

sender
Type: System..::..Object
methodResult
Type: System..::..Boolean
exception
Type: System..::..Exception

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


NotifyStateChanged Method

[image]

Browser..::..CallProxy..::..NotifyStateChanged Method
Browser..::..CallProxy Class See Also Send Feedback

Raises a StateChanged event.

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

Syntax

C#
protected void NotifyStateChanged(
    Object sender,
    Browser..::..CallProxy..::..ProxyCallState callState,
    Browser..::..CallProxy..::..ProxyCallStateTransitionReason transitionReason
)

Parameters

sender
Type: System..::..Object
callState
Type: Microsoft.Speech.VoiceXml..::..Browser..::..CallProxy..::..ProxyCallState
transitionReason
Type: Microsoft.Speech.VoiceXml..::..Browser..::..CallProxy..::..ProxyCallStateTransitionReason

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


NotifyToneReceived Method

[image]

Browser..::..CallProxy..::..NotifyToneReceived Method
Browser..::..CallProxy Class See Also Send Feedback

Raises a ToneReceived event.

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

Syntax

C#
protected void NotifyToneReceived(
    Object sender,
    DtmfTone tone
)

Parameters

sender
Type: System..::..Object
tone
Type: Microsoft.Speech.Recognition..::..DtmfTone

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


NotifyTransferStateChanged Method

[image]

Browser..::..CallProxy..::..NotifyTransferStateChanged Method
Browser..::..CallProxy Class See Also Send Feedback

Raises a TransferStateChanged event.

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

Syntax

C#
protected void NotifyTransferStateChanged(
    Object sender,
    Browser..::..CallProxy..::..ProxyReferState referState
)

Parameters

sender
Type: System..::..Object
referState
Type: Microsoft.Speech.VoiceXml..::..Browser..::..CallProxy..::..ProxyReferState

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


OpenAsync Method

[image]

Browser..::..CallProxy..::..OpenAsync Method
Browser..::..CallProxy Class See Also Send Feedback

Accepts an incoming telephony session invite and sends a response.

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

Syntax

C#
protected abstract void OpenAsync(
    string toAddress,
    string fromAddress
)

Parameters

toAddress
Type: System..::..String
The SipUri of the final destination.
fromAddress
Type: System..::..String
The SipUri of the calling party.

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


StartRecording Method

[image]

Browser..::..CallProxy..::..StartRecording Method
Browser..::..CallProxy Class See Also Send Feedback

Begins recording audio input from the call.

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

Syntax

C#
protected abstract void StartRecording(
    string recordedFilePath,
    EncodingFormat audioEncoding
)

Parameters

recordedFilePath
Type: System..::..String
The name and path of the file to which audio will be recorded.
audioEncoding
Type: Microsoft.Speech.AudioFormat..::..EncodingFormat
The Codec to use for recording.

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


StopRecording Method

[image]

Browser..::..CallProxy..::..StopRecording Method
Browser..::..CallProxy Class See Also Send Feedback

Stops recording audio.

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

Syntax

C#
protected abstract void StopRecording()

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser.CallProxy Properties

[image] [image]

Browser..::..CallProxy Properties
Browser..::..CallProxy Class See Also Send Feedback

The Browser..::..CallProxy type exposes the following members.

Properties

 | Name | Description
Protected property | CallId | Gets the CallID of the current call.
Protected property | LocalParticipantUri | Gets the URI of the local call.
Protected property | RecorderState | Gets the state of the Recorder.
Protected property | RemoteParticipantUri | Gets the URI of the remote call.
Protected property | State | Gets the current call state.
Protected property | TargetSip | Gets and sets the SIP for call transfers.
Protected property | TransferTypeRequested | Gets the transfer type of the requested transfer.

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


CallId Property

[image]

Browser..::..CallProxy..::..CallId Property
Browser..::..CallProxy Class See Also Send Feedback

Gets the CallID of the current call.

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

Syntax

C#
protected abstract string CallId { get; }

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


LocalParticipantUri Property

[image]

Browser..::..CallProxy..::..LocalParticipantUri Property
Browser..::..CallProxy Class See Also Send Feedback

Gets the URI of the local call.

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

Syntax

C#
protected abstract string LocalParticipantUri { get; }

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


RecorderState Property

[image]

Browser..::..CallProxy..::..RecorderState Property
Browser..::..CallProxy Class See Also Send Feedback

Gets the state of the Recorder.

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

Syntax

C#
protected abstract Browser..::..CallProxy..::..ProxyRecorderState RecorderState { get; }

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


RemoteParticipantUri Property

[image]

Browser..::..CallProxy..::..RemoteParticipantUri Property
Browser..::..CallProxy Class See Also Send Feedback

Gets the URI of the remote call.

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

Syntax

C#
protected abstract string RemoteParticipantUri { get; }

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


State Property

[image]

Browser..::..CallProxy..::..State Property
Browser..::..CallProxy Class See Also Send Feedback

Gets the current call state.

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

Syntax

C#
protected abstract Browser..::..CallProxy..::..ProxyCallState State { get; }

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


TargetSip Property

[image]

Browser..::..CallProxy..::..TargetSip Property
Browser..::..CallProxy Class See Also Send Feedback

Gets and sets the SIP for call transfers.

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

Syntax

C#
protected string TargetSip { get; set; }

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


TransferTypeRequested Property

[image]

Browser..::..CallProxy..::..TransferTypeRequested Property
Browser..::..CallProxy Class See Also Send Feedback

Gets the transfer type of the requested transfer.

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

Syntax

C#
protected Browser..::..CallProxy..::..ProxyTransferType TransferTypeRequested { get; }

See Also

Browser..::..CallProxy Class
Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser.CallProxy.ProxyCallState Enumeration

[image]

Browser..::..CallProxy..::..ProxyCallState Enumeration
Browser..::..CallProxy Class See Also Send Feedback

The ProxyCallState enumeration is used to relay information about the current call state.

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

Syntax

C#
protected enum ProxyCallState

Members

Member name | Value | Description
Idle | 0 | The call is idle.
Incoming | 1 | The call has just been received.
Establishing | 2 | The call establishment is in progress after initiating or accepting the call.
Established | 3 | The call is established.
Transferring | 5 | The call has initiated a transfer.
Terminating | 7 | The call is terminating.
Terminated | 8 | The call has terminated.
Parking | 9 | The call is to be put on hold.

See Also

Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser.CallProxy.ProxyCallStateTransitionReason Enumeration

[image]

Browser..::..CallProxy..::..ProxyCallStateTransitionReason Enumeration
Browser..::..CallProxy Class See Also Send Feedback

Represents the reasons for call state transitions.

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

Syntax

C#
protected enum ProxyCallStateTransitionReason

Members

Member name | Value | Description
None | 0 | Unspecified or unknown reason.
Ringing | 1 | One of the remote endpoints is ringing. This reason is only raised once.
CallDelayed | 2 | The call is delayed.
Establishing | 3 | The call is being initiated.
Accepted | 4 | The call is being accepted.
Established | 5 | Call establishment is completed.
EstablishFailed | 6 | Call establishment failed.
TerminatedLocally | 7 | The local participant has terminated the call.
TerminatedRemotely | 8 | The remote participant has terminated the call.
Canceled | 9 | The call has been canceled.
TransferredLocally | 10 | The call has been transferred by the local participant.
TransferredRemotely | 11 | The call has been transferred by the remote participant.
TransferSent | 12 | The transfer message was sent.
TransferAccepted | 13 | The incoming transfer request was accepted.
TransferFailed | 14 | The transfer operation failed.
CallTransferred | 15 | The call was transferred successfully.
Terminated | 16 | The call was terminated.
Deflected | 17 | No reason was specified.
DeflectedWithUnknownReason | 18 | The reason specified is unknown.
DeflectedToAnotherDestination | 19 | The call is being forwarded to another target.
DeflectedToTeam | 20 | The call is being forwarded as a team call.
DeflectedToDelegate | 21 | The call is being forwarded to a delegate.
DeflectedByAutomaticCallDistributor | 22 | The call is being forwarded to an automatic call distributor.
CallParked | 23 | The call has been put on hold.
ParkFailed | 24 | The attempt to put the call on hold failed.
CallReplaced | 25 | The call was replaced with another call.

See Also

Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser.CallProxy.ProxyPageState Enumeration

[image]

Browser..::..CallProxy..::..ProxyPageState Enumeration
Browser..::..CallProxy Class See Also Send Feedback

Represents the state of an attempt to load a VoiceXML document.

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

Syntax

C#
protected enum ProxyPageState

Members

Member name | Value | Description
Success | 0 | The page is loaded.
StartPageInInvalidUri | 1 | The URI given for the start page is not valid.
VoiceXmlBrowserFailedToLoadPage | 2 | The Browser could not load the start page.
VoiceXmlGeneralError | 3 | An error occurred in processing the page.
VoiceXmlGeneralWarning | 4 | A non-fatal error occurred in processing the page.
PageNotFound | 5 | The page specified by the URI could not be retrieved.
ServerNotAvailable | 6 | The server that contains the VoiceXML start page could not be contacted.
MalFormedXml | 7 | There is an error in the syntax or structure of the VoiceXML page.

See Also

Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser.CallProxy.ProxyRecorderState Enumeration

[image]

Browser..::..CallProxy..::..ProxyRecorderState Enumeration
Browser..::..CallProxy Class See Also Send Feedback

Represents the state of the recorder.

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

Syntax

C#
protected enum ProxyRecorderState

Members

Member name | Value | Description
Started | 0 | The recorder is recording.
Stopped | 1 | The recorder is stopped.
Paused | 2 | The recorder is paused.

See Also

Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser.CallProxy.ProxyReferState Enumeration

[image]

Browser..::..CallProxy..::..ProxyReferState Enumeration
Browser..::..CallProxy Class See Also Send Feedback

Indicates possible states for the signaling session.

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

Syntax

C#
protected enum ProxyReferState

Members

Member name | Value | Description
Idle | 0 | The refer has not been sent yet.
ReferRequested | 1 | The refer message has been sent.
ReferAccepted | 2 | The refer has been accepted.
ReferRejected | 3 | The refer has been rejected.
ReferFailed | 4 | The refer operation was not sent successfully or did not receive a response.
Trying | 5 | The refer target is being connected by the remote participant.
Alerted | 6 | The refer target has been alerted.
Succeeded | 7 | The refer operation was completed successfully by the remote participant.
Failed | 8 | The refer operation was not completed successfully by the remote participant.
Redirected | 9 | The refer target has redirected but the redirect was not acted upon.

See Also

Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Browser.CallProxy.ProxyTransferType Enumeration

[image]

Browser..::..CallProxy..::..ProxyTransferType Enumeration
Browser..::..CallProxy Class See Also Send Feedback

Indicates the type of transfer requested in the VoiceXML document.

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

Syntax

C#
protected enum ProxyTransferType

Members

Member name | Value | Description
None | 0 | No transfer type is given.
Bridge | 1 | The application redirects the caller to the recipient and remains in the connection. Document interpretation suspends until the transferred call terminates.
Blind | 2 | The application redirects the caller to the recipient without remaining in the connection, and does not monitor the outcome. The Browser exits the page.
Consultation | 3 | The application redirects the caller to the recipient and monitors the progress of the transfer until the connection is established between caller and recipient. If the connection is established, the Browser disconnects from the session.

See Also

Microsoft.Speech.VoiceXml Namespace
Send feedback on this topic to Microsoft.


Microsoft.Speech.VoiceXml.Common Namespace

[image]

Microsoft.Speech.VoiceXml.Common Namespace
Send Feedback

Classes

 | Class | Description
Public class | DisconnectedEventArgs | Contains information that can be used in the event handler of the application when the Disconnected event is raised during an asynchronous Browser session.
Public class | DisconnectingEventArgs | Contains information that can be used in the event handler of the application when the Disconnecting event is raised.
Public class | PageEvent | Contains information about an event that was thrown from within a VoiceXML page.
Public class | SessionCompletedEventArgs | Contains information that can be used in the event handler of the application when the SessionCompleted event is raised during an asynchronous Browser session.
Public class | TransferredEventArgs | Contains information that can be used in the event handler of the application when the Transferred event is raised during an asynchronous Browser session.
Public class | TransferringEventArgs | Contains information that can be used in the event handler of the application when the event is raised.
Public class | VoiceXmlResult | Contains information about the result of a synchronous or an asynchronous Browser session.

Enumerations

 | Enumeration | Description
Public enumeration | DisconnectState | Represents the possible states of a VoiceXML disconnect request during an asynchronous Browser session.
Public enumeration | ExitReason | Contains a list of reasons that indicate why a Browser instance exited from a VoiceXML page.
Public enumeration | SessionState | Represents possible states for an asynchronous VoiceXML Browser session.
Public enumeration | TransferState | Represents the state of a VoiceXML phone call transfer request during an asynchronous session.
Public enumeration | TransferType | Represents the type of call transfer to be performed during an asynchronous session.
Send feedback on this topic to Microsoft.


DisconnectedEventArgs Class

[image]

DisconnectedEventArgs Class
Members See Also Send Feedback

Contains information that can be used in the event handler of the application when the Disconnected event is raised during an asynchronous Browser session.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public class DisconnectedEventArgs : EventArgs

Remarks

The Disconnected event is raised when a call has disconnected from an asynchronous Browser session.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.VoiceXml.Common..::..DisconnectedEventArgs

See Also

DisconnectedEventArgs Members
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


DisconnectedEventArgs Members

[image] [image]

DisconnectedEventArgs Members
DisconnectedEventArgs Class Methods Properties See Also Send Feedback

The DisconnectedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)

Properties

 | Name | Description
Public property | Namelist | Gets a Namelist object when the Disconnected event is raised.
Public property | State | Gets the DisconnectState when the Disconnected event is raised.

See Also

DisconnectedEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


DisconnectedEventArgs Methods

[image] [image]

DisconnectedEventArgs Methods
DisconnectedEventArgs Class See Also Send Feedback

The DisconnectedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)

See Also

DisconnectedEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


DisconnectedEventArgs Properties

[image] [image]

DisconnectedEventArgs Properties
DisconnectedEventArgs Class See Also Send Feedback

The DisconnectedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Namelist | Gets a Namelist object when the Disconnected event is raised.
Public property | State | Gets the DisconnectState when the Disconnected event is raised.

See Also

DisconnectedEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


Namelist Property

[image]

DisconnectedEventArgs..::..Namelist Property
DisconnectedEventArgs Class See Also Send Feedback

Gets a Namelist object when the Disconnected event is raised.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public Dictionary<string, Object> Namelist { get; }

See Also

DisconnectedEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


State Property

[image]

DisconnectedEventArgs..::..State Property
DisconnectedEventArgs Class See Also Send Feedback

Gets the DisconnectState when the Disconnected event is raised.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public DisconnectState State { get; }

See Also

DisconnectedEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


DisconnectingEventArgs Class

[image]

DisconnectingEventArgs Class
Members See Also Send Feedback

Contains information that can be used in the event handler of the application when the Disconnecting event is raised.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public class DisconnectingEventArgs : EventArgs

Remarks

The Disconnecting event is raised just before a call is disconnected during an asynchronous Browser session.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.VoiceXml.Common..::..DisconnectingEventArgs

See Also

DisconnectingEventArgs Members
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


DisconnectingEventArgs Members

[image] [image]

DisconnectingEventArgs Members
DisconnectingEventArgs Class Methods Properties See Also Send Feedback

The DisconnectingEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)

Properties

 | Name | Description
Public property | SessionState | Gets the SessionState when the Disconnecting event is raised.

See Also

DisconnectingEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


DisconnectingEventArgs Methods

[image] [image]

DisconnectingEventArgs Methods
DisconnectingEventArgs Class See Also Send Feedback

The DisconnectingEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)

See Also

DisconnectingEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


DisconnectingEventArgs Properties

[image] [image]

DisconnectingEventArgs Properties
DisconnectingEventArgs Class See Also Send Feedback

The DisconnectingEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | SessionState | Gets the SessionState when the Disconnecting event is raised.

See Also

DisconnectingEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


SessionState Property

[image]

DisconnectingEventArgs..::..SessionState Property
DisconnectingEventArgs Class See Also Send Feedback

Gets the SessionState when the Disconnecting event is raised.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public SessionState SessionState { get; }

See Also

DisconnectingEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


DisconnectState Enumeration

[image]

DisconnectState Enumeration
See Also Send Feedback

Represents the possible states of a VoiceXML disconnect request during an asynchronous Browser session.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public enum DisconnectState

Members

Member name | Value | Description
None | 0 | There was no reason for the disconnection.
UserDisconnected | 1 | The caller discontinued the call, for example by hanging up.
HostDisconnected | 2 | The application disconnected from the VoiceXML session.
PageDisconnected | 3 | The Browser is no longer connected to the VoiceXML page.
ConnectionError | 4 | There was an error in the connection to a call or an audio input that caused the Browser session to end.
UnknownError | 2147483647 | There was a disconnect error but its cause could not be determined.

See Also

Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


ExitReason Enumeration

[image]

ExitReason Enumeration
See Also Send Feedback

Contains a list of reasons that indicate why a Browser instance exited from a VoiceXML page.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public enum ExitReason

Members

Member name | Value | Description
None | 0 | No exit reason is given.
HostExitRequested | 1 | The application called the StopAsync()()()() method.
ExitElementEncountered | 2 | The VoiceXML interpreter encountered and processed an <exit> element on a VoiceXML page.
DialogEndEncountered | 3 | The VoiceXML interpreter arrived at the end of a dialog and there was no successor element.
UnhandledPageException | 4 | An exception is thrown in processing the VoiceXML page that is not handled by the VoiceXML <error> element.
MalFormedXml | 5 | The Browser encountered errors in the syntax or structure of the VoiceXML page.
ServerNotAvailable | 6 | The server that contains the VoiceXML start page could not be contacted.
AudioTerminated | 7 | The audio that was present at the input connection can no longer be detected.
PageNotFound | 8 | The page specified by the URI parameter in a Run(Uri, CookieContainer) or RunAsync(Uri, CookieContainer) method could not be retrieved.
UnknownExit | 2147483647 | The reason for the exit could not be determined.

Remarks

The Reason property of the VoiceXmlResult class gets the ExitReason when the Browser exits a VoiceXML page. For synchronous Browser instances, the VoiceXmlResult is returned by the Run(Uri, CookieContainer) method. For asynchronous Browser instances, initiated with the RunAsync(Uri, CookieContainer) method, the SessionCompletedEventArgs class contains the VoiceXmlResult.

See Also

Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


PageEvent Class

[image]

PageEvent Class
Members See Also Send Feedback

Contains information about an event that was thrown from within a VoiceXML page.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public class PageEvent

Remarks

If the session completes without errors, that is if the ExitReason value is HostExitRequested, ExitElementEncountered, or DialogEndEncountered, then the PageEvent will be null.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.VoiceXml.Common..::..PageEvent

See Also

PageEvent Members
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


PageEvent Members

[image] [image]

PageEvent Members
PageEvent Class Methods Properties See Also Send Feedback

The PageEvent type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)

Properties

 | Name | Description
Public property | Event | Gets the name of the event that was thrown from within the VoiceXML page.
Public property | Message | Gets a message that is associated with an event that was thrown from within the VoiceXML page.

See Also

PageEvent Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


PageEvent Methods

[image] [image]

PageEvent Methods
PageEvent Class See Also Send Feedback

The PageEvent type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)

See Also

PageEvent Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


PageEvent Properties

[image] [image]

PageEvent Properties
PageEvent Class See Also Send Feedback

The PageEvent type exposes the following members.

Properties

 | Name | Description
Public property | Event | Gets the name of the event that was thrown from within the VoiceXML page.
Public property | Message | Gets a message that is associated with an event that was thrown from within the VoiceXML page.

See Also

PageEvent Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


Event Property

[image]

PageEvent..::..Event Property
PageEvent Class See Also Send Feedback

Gets the name of the event that was thrown from within the VoiceXML page.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public string Event { get; }

See Also

PageEvent Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


Message Property

[image]

PageEvent..::..Message Property
PageEvent Class See Also Send Feedback

Gets a message that is associated with an event that was thrown from within the VoiceXML page.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public string Message { get; }

See Also

PageEvent Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


SessionCompletedEventArgs Class

[image]

SessionCompletedEventArgs Class
Members See Also Send Feedback

Contains information that can be used in the event handler of the application when the SessionCompleted event is raised during an asynchronous Browser session.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public class SessionCompletedEventArgs : AsyncCompletedEventArgs

Remarks

The SessionCompleted event is raised at the end of an asynchronous Browser session. SessionCompletedEventArgs derives from AsyncCompletedEventArgs.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
System.ComponentModel..::..AsyncCompletedEventArgs
Microsoft.Speech.VoiceXml.Common..::..SessionCompletedEventArgs

See Also

SessionCompletedEventArgs Members
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


SessionCompletedEventArgs Members

[image] [image]

SessionCompletedEventArgs Members
SessionCompletedEventArgs Class Methods Properties See Also Send Feedback

The SessionCompletedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Result | Gets the result of a completed Browser session, represented by a VoiceXmlResult object.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)

See Also

SessionCompletedEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


SessionCompletedEventArgs Methods

[image] [image]

SessionCompletedEventArgs Methods
SessionCompletedEventArgs Class See Also Send Feedback

The SessionCompletedEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Protected method | RaiseExceptionIfNecessary | (Inherited from AsyncCompletedEventArgs.)
Public method | ToString | (Inherited from Object.)

See Also

SessionCompletedEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


SessionCompletedEventArgs Properties

[image] [image]

SessionCompletedEventArgs Properties
SessionCompletedEventArgs Class See Also Send Feedback

The SessionCompletedEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | Cancelled | (Inherited from AsyncCompletedEventArgs.)
Public property | Error | (Inherited from AsyncCompletedEventArgs.)
Public property | Result | Gets the result of a completed Browser session, represented by a VoiceXmlResult object.
Public property | UserState | (Inherited from AsyncCompletedEventArgs.)

See Also

SessionCompletedEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


Result Property

[image]

SessionCompletedEventArgs..::..Result Property
SessionCompletedEventArgs Class See Also Send Feedback

Gets the result of a completed Browser session, represented by a VoiceXmlResult object.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public VoiceXmlResult Result { get; }

See Also

SessionCompletedEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


SessionState Enumeration

[image]

SessionState Enumeration
See Also Send Feedback

Represents possible states for an asynchronous VoiceXML Browser session.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public enum SessionState

Members

Member name | Value | Description
Idle | 0 | The Browser is not running.
Active | 1 | The Browser is processing a Run(Uri, CookieContainer) or a RunAsync(Uri, CookieContainer) method.

Remarks

When the Disconnecting event is raised, the SessionState property on the DisconnectingEventArgs instance indicates the session state.

Note: Although the TransferType enumeration contains all three types of transfer defined in the VoiceXML 2.1 standard, the current version of the VoiceXML runtime supports only the Blind transfer type.

See Also

Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


TransferredEventArgs Class

[image]

TransferredEventArgs Class
Members See Also Send Feedback

Contains information that can be used in the event handler of the application when the Transferred event is raised during an asynchronous Browser session.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public class TransferredEventArgs : EventArgs

Remarks

The Transferred event is raised when the VoiceXML application has completed a phone call transfer to a recipient during an asynchronous Browser session.

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.VoiceXml.Common..::..TransferredEventArgs

See Also

TransferredEventArgs Members
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


TransferredEventArgs Members

[image] [image]

TransferredEventArgs Members
TransferredEventArgs Class Methods Properties See Also Send Feedback

The TransferredEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)

Properties

 | Name | Description
Public property | State | Gets the TransferState when the Transferred event is raised.
Public property | TargetSip | Gets the SIP URI of the transfer destination.
Public property | Type | Gets the TransferType that was used to transfer a phone call when the Transferred event is raised.

See Also

TransferredEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


TransferredEventArgs Methods

[image] [image]

TransferredEventArgs Methods
TransferredEventArgs Class See Also Send Feedback

The TransferredEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)

See Also

TransferredEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


TransferredEventArgs Properties

[image] [image]

TransferredEventArgs Properties
TransferredEventArgs Class See Also Send Feedback

The TransferredEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | State | Gets the TransferState when the Transferred event is raised.
Public property | TargetSip | Gets the SIP URI of the transfer destination.
Public property | Type | Gets the TransferType that was used to transfer a phone call when the Transferred event is raised.

See Also

TransferredEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


State Property

[image]

TransferredEventArgs..::..State Property
TransferredEventArgs Class See Also Send Feedback

Gets the TransferState when the Transferred event is raised.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public TransferState State { get; }

See Also

TransferredEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


TargetSip Property

[image]

TransferredEventArgs..::..TargetSip Property
TransferredEventArgs Class See Also Send Feedback

Gets the SIP URI of the transfer destination.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public string TargetSip { get; }

See Also

TransferredEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


Type Property

[image]

TransferredEventArgs..::..Type Property
TransferredEventArgs Class See Also Send Feedback

Gets the TransferType that was used to transfer a phone call when the Transferred event is raised.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public TransferType Type { get; }

See Also

TransferredEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


TransferringEventArgs Class

[image]

TransferringEventArgs Class
Members See Also Send Feedback

Contains information that can be used in the event handler of the application when the event is raised.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public class TransferringEventArgs : EventArgs

Inheritance Hierarchy

System..::..Object
System..::..EventArgs
Microsoft.Speech.VoiceXml.Common..::..TransferringEventArgs

See Also

TransferringEventArgs Members
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


TransferringEventArgs Members

[image] [image]

TransferringEventArgs Members
TransferringEventArgs Class Methods Properties See Also Send Feedback

The TransferringEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)

Properties

 | Name | Description
Public property | State | Gets the TransferState when the Transferring event is raised.
Public property | TargetSip | Gets the SIP URI of the transfer destination.
Public property | Type | Gets the TransferType being used to transfer the phone call when the Transferring event is raised.

See Also

TransferringEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


TransferringEventArgs Methods

[image] [image]

TransferringEventArgs Methods
TransferringEventArgs Class See Also Send Feedback

The TransferringEventArgs type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)

See Also

TransferringEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


TransferringEventArgs Properties

[image] [image]

TransferringEventArgs Properties
TransferringEventArgs Class See Also Send Feedback

The TransferringEventArgs type exposes the following members.

Properties

 | Name | Description
Public property | State | Gets the TransferState when the Transferring event is raised.
Public property | TargetSip | Gets the SIP URI of the transfer destination.
Public property | Type | Gets the TransferType being used to transfer the phone call when the Transferring event is raised.

See Also

TransferringEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


State Property

[image]

TransferringEventArgs..::..State Property
TransferringEventArgs Class See Also Send Feedback

Gets the TransferState when the Transferring event is raised.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public TransferState State { get; }

See Also

TransferringEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


TargetSip Property

[image]

TransferringEventArgs..::..TargetSip Property
TransferringEventArgs Class See Also Send Feedback

Gets the SIP URI of the transfer destination.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public string TargetSip { get; }

See Also

TransferringEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


Type Property

[image]

TransferringEventArgs..::..Type Property
TransferringEventArgs Class See Also Send Feedback

Gets the TransferType being used to transfer the phone call when the Transferring event is raised.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public TransferType Type { get; }

See Also

TransferringEventArgs Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


TransferState Enumeration

[image]

TransferState Enumeration
See Also Send Feedback

Represents the state of a VoiceXML phone call transfer request during an asynchronous session.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public enum TransferState

Members

Member name | Value | Description
None | 0 | The state for the transfer was not given.
Transferring | 1 | A call transfer is in progress.
Transferred | 2 | The call transfer to the recipient was successful.
Failed | 3 | The call transfer to the recipient was not successful, for example there was no answer or the line was busy.
UnknownError | 2147483647 | There was an error during transfer, but its cause could not be determined.

Remarks

When the Transferred event is raised, the State property on the TransferredEventArgs instance indicates the transfer state. When the Transferring event is raised, the State property on the TransferringEventArgs instance indicates the transfer state.

See Also

Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


TransferType Enumeration

[image]

TransferType Enumeration
See Also Send Feedback

Represents the type of call transfer to be performed during an asynchronous session.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public enum TransferType

Members

Member name | Value | Description
Blind | 0 | The application redirects the caller to the recipient without remaining in the connection, and does not monitor the outcome. The Browser exits the page.
Bridge | 1 | The application redirects the caller to the recipient and remains in the connection. Document interpretation suspends until the transferred call terminates.
Consultation | 2 | The application redirects the caller to the recipient and monitors the progress of the transfer until the connection is established between caller and recipient. If the connection is established, the Browser disconnects from the session.

Remarks

When the Transferred event is raised, the Type property on the TransferredEventArgs instance indicates the transfer type. When the Transferring event is raised, the Type property on the TransferringEventArgs instance indicates the transfer type.

See Also

Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


VoiceXmlResult Class

[image]

VoiceXmlResult Class
Members See Also Send Feedback

Contains information about the result of a synchronous or an asynchronous Browser session.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public class VoiceXmlResult

Remarks

For synchronous Browser instances, the VoiceXmlResult is returned by the Run(Uri, CookieContainer) method. For asynchronous Browser instances, initiated with RunAsync(Uri, CookieContainer), the Result property of the SessionCompletedEventArgs class gets the VoiceXmlResult.

Inheritance Hierarchy

System..::..Object
Microsoft.Speech.VoiceXml.Common..::..VoiceXmlResult

See Also

VoiceXmlResult Members
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


VoiceXmlResult Members

[image] [image]

VoiceXmlResult Members
VoiceXmlResult Class Methods Properties See Also Send Feedback

The VoiceXmlResult type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)

Properties

 | Name | Description
Public property | Cookies | Gets a CookieContainer object.
Public property | Namelist | Gets a list of key/value pairs defined in the <exit> element of a VoiceXML document.
Public property | Reason | Gets the reason that the Browser exited a VoiceXML page.
Public property | UnhandledThrowElement | Gets a PageEvent object for a VoiceXML page event that was not handled in the page.

See Also

VoiceXmlResult Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


VoiceXmlResult Methods

[image] [image]

VoiceXmlResult Methods
VoiceXmlResult Class See Also Send Feedback

The VoiceXmlResult type exposes the following members.

Methods

 | Name | Description
Public method | Equals | (Inherited from Object.)
Protected method | Finalize | (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)

See Also

VoiceXmlResult Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


VoiceXmlResult Properties

[image] [image]

VoiceXmlResult Properties
VoiceXmlResult Class See Also Send Feedback

The VoiceXmlResult type exposes the following members.

Properties

 | Name | Description
Public property | Cookies | Gets a CookieContainer object.
Public property | Namelist | Gets a list of key/value pairs defined in the <exit> element of a VoiceXML document.
Public property | Reason | Gets the reason that the Browser exited a VoiceXML page.
Public property | UnhandledThrowElement | Gets a PageEvent object for a VoiceXML page event that was not handled in the page.

See Also

VoiceXmlResult Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


Cookies Property

[image]

VoiceXmlResult..::..Cookies Property
VoiceXmlResult Class See Also Send Feedback

Gets a CookieContainer object.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public CookieContainer Cookies { get; }

See Also

VoiceXmlResult Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


Namelist Property

[image]

VoiceXmlResult..::..Namelist Property
VoiceXmlResult Class See Also Send Feedback

Gets a list of key/value pairs defined in the <exit> element of a VoiceXML document.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public Dictionary<string, Object> Namelist { get; }

See Also

VoiceXmlResult Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


Reason Property

[image]

VoiceXmlResult..::..Reason Property
VoiceXmlResult Class See Also Send Feedback

Gets the reason that the Browser exited a VoiceXML page.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public ExitReason Reason { get; }

See Also

VoiceXmlResult Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


UnhandledThrowElement Property

[image]

VoiceXmlResult..::..UnhandledThrowElement Property
VoiceXmlResult Class See Also Send Feedback

Gets a PageEvent object for a VoiceXML page event that was not handled in the page.

Namespace: Microsoft.Speech.VoiceXml.Common
Assembly: Microsoft.Speech.VoiceXml (in Microsoft.Speech.VoiceXml.dll)

Syntax

C#
public PageEvent UnhandledThrowElement { get; }

See Also

VoiceXmlResult Class
Microsoft.Speech.VoiceXml.Common Namespace
Send feedback on this topic to Microsoft.


Speech API Overview (Microsoft Speech Platform)

 Microsoft Speech Platform

Speech API Overview

The Microsoft Speech Platform application programming interface (API) dramatically reduces the code overhead required for an application to use speech recognition and text-to-speech, making speech technology more accessible and robust for a wide range of applications.

This section covers the following topics:

  • API Overview
  • API for Text-to-Speech
  • API for Speech Recognition

API Overview

The Microsoft Speech Platform API provides a high-level interface between an application and speech engines. The Speech Platform API implements all the low-level details needed to control and manage the real-time operations of various speech engines.

You can manage two types of speech engines using the Speech Platform API: speech synthesis engines (text-to-speech or TTS) and recognition engines (speech recognizers). TTS engines synthesize text strings and files into spoken audio using synthetic voices. Speech recognizers convert human spoken audio into readable text strings and files.

Speech Platform API Overview Diagram

API for Text-to-Speech

Applications can control text-to-speech (TTS) using the ISpVoice Component Object Model (COM) interface. Once an application has created an ISpVoice object, the application only needs to call ISpVoice::Speak to generate speech output from some text data. In addition, the IspVoice interface also provides several methods for changing voice and synthesis properties such as speaking rate ISpVoice::SetRate, output volume ISpVoice::SetVolume, and changing the current speaking voice ISpVoice::SetVoice

Using the Speech Platform API, you can also insert special controls together with the input text to change real-time synthesis properties like voice, pitch, word emphasis, speaking rate, and volume. This synthesis markup, using standard XML format, is a simple but powerful way to customize TTS speech, independent of the specific engine or voice currently in use.

The IspVoice::Speak method can operate either synchronously (return only when completely finished speaking) or asynchronously (return immediately and speak as a background process). When speaking asynchronously (SPF_ASYNC), you can poll for real-time status information such as speaking state and current text location using ISpVoice::GetStatus. Also while speaking asynchronously, you can generate new speech output by either immediately interrupting the current output (SPF_PURGEBEFORESPEAK), or by automatically appending new text to the end of the current output.

In addition to the ISpVoice interface, the Speech Platform API also provides many utility COM interfaces for more advanced TTS applications.

Events

The Speech Platform API communicates with applications by sending events using standard callback mechanisms (Window Message, callback proc, or Win32 Event). You typically use TTS events for synchronizing to the speech output. Applications can synchronize to real-time actions as they occur such as word boundaries, phoneme or viseme (mouth animation) boundaries, or custom bookmarks. Applications can initialize and handle these real-time events using ISpNotifySource, ISpNotifySink, ISpNotifyTranslator, ISpEventSink, ISpEventSource, and ISpNotifyCallback.

Lexicons

Applications can provide custom word pronunciations for speech synthesis engines using methods provided by ISpContainerLexicon, ISpLexicon and ISpPhoneConverter.

Resources

You can find and select speech data, such as voice files and pronunciation lexicons, using the following COM interfaces in the Speech Platform API: ISpDataKey, ISpRegDataKey, ISpObjectTokenInit, ISpObjectTokenCategory, ISpObjectToken, IEnumSpObjectTokens, ISpObjectWithToken, and ISpResourceManager.

Audio

Finally, there is an interface for customizing the audio output to some special destination such as telephony and custom hardware (ISpAudio, ISpMMSysAudio, ISpStream, ISpStreamFormat, ISpStreamFormatConverter).

return to the top of this page Back to top

API for Speech Recognition

Just as ISpVoice is the main interface for speech synthesis, ISpRecoContext is the main interface for speech recognition. Like the ISpVoice, ISpRecoContext is an ISpEventSource, which means that it is the speech application's vehicle for receiving notifications for the requested speech recognition events.

An application has the choice of two different types of speech recognition engines (ISpRecognizer). A shared recognizer, which may be shared with other speech recognition applications, is recommended for most speech applications. To create an ISpRecoContext for a shared ISpRecognizer, an application need only call COM's CoCreateInstance on the component CLSID_SpSharedRecoContext. In this case, the Speech Platform API will set up the audio input stream, setting it to the default audio input stream. For large server applications that run alone on a system, and for which performance is key, an in-process (InProc) speech recognition engine is more appropriate. To create an ISpRecoContext for an InProc ISpRecognizer, the application must first call CoCreateInstance on the component CLSID_SpInprocRecoInstance to create its own InProc ISpRecognizer. Then the application must make a call to ISpRecognizer::SetInput (see also ISpObjectToken) to set up the audio input. Finally, the application can call ISpRecognizer::CreateRecoContext to obtain an ISpRecoContext.

The next step is to register for notifications of events that are of interest to your application. As the ISpRecognizer is also an ISpEventSource, which in turn is an ISpNotifySource, your application can call one of the ISpNotifySource methods from its ISpRecoContext to indicate where the events for that ISpRecoContext should be reported. Then it should call ISpEventSource::SetInterest to indicate for which events it wants to receive notification. The most important event is SPEI_RECOGNITION, which indicates that the ISpRecognizer has recognized some speech for this ISpRecoContext. See SPEVENTENUM for details on the other available speech recognition events.

Finally, a speech application must create, load, and activate an ISpRecoGrammar. The recognition engine uses the contents of ISpRecoGrammar to define the utterances that can be recognized, either free dictation (broad coverage of the words in a language), or a limited set of words and phrases specific to your application (command and control). First, the application creates an ISpRecoGrammar using ISpRecoContext::CreateGrammar. Then, the application loads the grammar, either by calling ISpRecoGrammar::LoadDictation for dictation, or one of the ISpRecoGrammar::LoadCmdxxx methods for command and control. To activate these grammars so that recognition can start, the application calls ISpRecoGrammar::SetDictationState for dictation or ISpRecoGrammar::SetRuleState or ISpRecoGrammar::SetRuleIdState for command and control.

When recognition results come back to the application by means of the requested notification mechanism, the lParam member of the SPEVENT structure will be an ISpRecoResult, from which the application can determine what was recognized and for which ISpRecoGrammar of the ISpRecoContext.

An ISpRecognizer, whether shared or InProc, can have multiple ISpRecoContexts associated with it, and each one can be notified in its own way of events pertaining to it. An ISpRecoContext can have multiple ISpRecoGrammars created from it, each one for recognizing different types of utterances.

return to the top of this page Back to top


Developer Support (Microsoft Speech Platform)

 Microsoft Speech Platform

Developer Support

Microsoft Support Center

The Microsoft Support Center site maintains a wealth of resources to help you get the most from your product. Here you can search the entire Knowledge Base, view all the troubleshooting wizards, and access all the downloadable files. You can also view the extensive online glossary of computer terms, and find phone numbers and support options for all Microsoft products.

Speech newsgroups

For assistance with specific problems, check first with the following newsgroups.

  • microsoft.public.speech_tech
  • microsoft.public.speech_tech.sdk
  • microsoft.public.speech_tech.desktop
Microsoft Speech.NET Technologies Feedback

If you have feedback on the Microsoft Speech API (SAPI) or other Microsoft Speech-related questions, please send an e-mail message to the following address. This e-mail address is monitored regularly, but questions will receive only limited response. Please use the newsgroup forum above for most questions and inquiries.

  • sapi5@microsoft.com
Known Issues
Information on known issues in SAPI 5 can be found in the Knowledge Base articles in the Microsoft Speech Server support home page.


Application-Level Interfaces (Microsoft Speech Platform)

 Microsoft Speech Platform

Application-Level Interfaces

This section describes the interfaces and methods for incorporating speech into applications.

  • Audio interfaces
  • Eventing interfaces
  • Grammar Compiler interfaces
  • Lexicon interfaces
  • Resource interfaces
  • Speech Recognition interfaces
  • Text-to-Speech interfaces


Audio interfaces (Microsoft Speech Platform)

 Microsoft Speech Platform

Audio interfaces

This section provides SAPI 5 audio interfaces.

Audio inherits from the standard COM IStream interface. See the MSDN documentation for a complete discussion of IStream and associated methods. However, since the audio devices represent hardware, ::Clone may be not be used and will return E_NOTIMPL.

  • ISpAudio
  • ISpMMSysAudio
  • ISpStream
  • ISpStreamFormat
  • ISpStreamFormatConverter

The following interface does not inherit from IStream:

  • ISpTranscript

Development Helpers

Helper Enumerations, Functions and Classes | Description
SPSTREAMFORMAT | SAPI supported stream formats.
CSpEvent | Class for decoding event structures.
CSpDynamicString | Class for managing dynamically sized WCHAR strings.
SpBindToFile | Function converts the specified stream format into a wave format structure.
CSpStreamFormat | Class for managing SAPI supported stream formats and WAVEFORMATEX structures.


ISpAudio (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpAudio

Objects implementing this interface are real-time audio streams, such as those connected to a live microphone or telephone line. ISpAudio methods support of control of real-time audio streams. IStream Read and Write methods transfer data to or from an object.

When to Implement

This interface should be implemented when the audio input or output source is not a standard windows Multimedia device. It is expected to supply an infinite amount of data and hence its state should not change externally to SAPI. For the majority of users, it will not be necessary to implement an object providing this interface. An example of where this might be needed would be to provide a telephony audio device or to perform echo cancellation of audio output on the input.

Telephone application programming interface (TAPI) provides a mechanism to treat a telephony device as a Windows multimedia device allowing the use of the SAPI provided multimedia audio objects.

If this implements a real time audio input or output object and runs in a desktop or graphical environment, support may be needed for volume and audio properties UI. This will enable applications (including Speech properties in Control Panel) to display the UI in a simple and consistent manner.

In order to prevent multiple TTS voices or engines from speaking simultaneously, SAPI serializes output to objects which implement the ISpAudio interface. To disable serialization of outputs to an ISpAudio object, place an attribute called "NoSerializeAccess" in the Attributes folder of its object token.

Implemented By
  • SpMMAudioIn
  • SpMMAudioOut

Methods in Vtable Order

Value | Description
ISpStreamFormat interface | Inherits from ISpStreamFormat and all those methods are accessible from an ISpAudio object.
SetState | Sets the state of the audio device.
SetFormat | Sets the format of the audio device.
GetStatus | Passes back the status of the audio device.
SetBufferInfo | Sets the audio stream buffer information.
GetBufferInfo | Passes back the audio stream buffer information.
GetDefaultFormat | Passes back the default audio format.
EventHandle | Returns a Win32 event handle that applications can use to wait for status changes in the I/O stream.
GetVolumeLevel | Passes back the current volume level.
SetVolumeLevel | Sets the current volume level.
GetBufferNotifySize | Retrieves the audio stream buffer size information.
SetBufferNotifySize | Sets the audio stream buffer size information.

Development Helpers

Helper Enumerations, Functions and Classes | Description
SPSTREAMFORMAT | SAPI supported stream formats.
CSpStreamFormat | Class for managing SAPI supported stream formats and WAVEFORMATEX structures.


ISpAudio::SetState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpAudio::SetState

ISpAudio::SetState sets the state of the audio device.

HRESULT SetState(
   SPAUDIOSTATE   NewState,
   ULONGLONG      ullReserved
);

Parameters

NewState
[in] The flag of type SPAUDIOSTATE for the new state of the audio device.
ullReserved
[in] Reserved, do not use. This value must be zero.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | ullReserved is not zero.
SPERR_DEVICE_BUSY | Hardware device is in use by another thread or process.
SPERR_UNSUPPORTED_FORMAT | Current format set by ISpAudio::SetFormat is not supported by the hardware device.
SPERR_INVALID_AUDIO_STATE | NewState is not set to a valid value.

Remarks

When transitioning from the SPAS_CLOSED state to any other state, the caller should be ready to handle various error conditions, specifically, SPERR_UNSUPPORTED_FORMAT and SPERR_DEVICE_BUSY. Many multi-media devices do not correctly report their capabilities for handling different audio formats and fail only when an attempt is made to open the device.

Also, in many older systems, audio output devices can be opened only by a single process. In versions of Windows previous to Windows XP, only a single process can open an audio input device. Therefore, SPERR_DEVICE_BUSY will return if an attempt is made to open a device that is being used by a different process or thread. In Windows XP (and higher), multiple processes can open the same audio device.

On some older sound cards, recording and playback are not possible simultaneously or only possible at the same frequency. An application making use of the input and output audio should be aware of this and in particular attempt to gracefully degrade from higher quality frequencies to the same frequency for both if the sound card makes this necessary.

In general, applications need not change the state of the audio device directly. With the shared recognizer in particular, this will often cause unexpected results. SAPI will automatically manage the state of the audio device based on the state of all the grammars, recognition contexts and the recognizer instance.


ISpAudio::SetFormat (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpAudio::SetFormat

ISpAudio::SetFormat sets the format of the audio device.

HRESULT SetFormat(
   REFGUID                rguidFmtId,
   const  WAVEFORMATEX   *pWaveFormatEx
);

Parameters

rguidFmtId
[in] The REFGUID for the format to set. Typically this will be SPDFID_WaveFormatEx. This is required for the SAPI multimedia objects.
pWaveFormatEx
[in] Address of the WAVEFORMATEX structure containing the wave file format information.

Return values

Value | Description
S_OK | Function completed successfully. See note about supported formats.
E_INVALIDARG | pWaveFormatEx is invalid or bad.
SPERR_DEVICE_BUSY | Device is not in the SPAS_CLOSED state.
SPERR_UNINITIALIZED | Audio stream not initialized.
SPERR_UNSUPPORTED_FORMAT | Specified format is not supported.
FAILED(hr) | Appropriate error message.

Remarks

This method can be called only when the audio device is in the SPAS_CLOSED state. Note that successfully setting the format on an audio device does not necessarily mean that the format is supported. An attempt must be made to place the device into a non-closed state (SPAS_STOP, SPAS_PAUSE or SPAS_RUN) to be sure that the device can handle the format.

The format can be retrieved by calling the ISpStreamFormat::GetFormat method.

The helper class CSpStreamFormat and the SPSTREAMFORMAT enumeration can be used to avoid the possibility of typos or mistakes when filling in the WAVEFORMATEX structure.


ISpAudio::GetStatus (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpAudio::GetStatus

ISpAudio::GetStatus passes back the status of the audio device.

This method determines whether the device is running, stopped, closed, or paused. It also includes various parameters about the audio object, including how much data is buffered.

HRESULT GetStatus(
  SPAUDIOSTATUS  *pStatus
);

Parameters

pStatus
[out] Pointer to an SPAUDIOSTATUS buffer to be filled with the status details.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pStatus is invalid.


ISpAudio::SetBufferInfo (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpAudio::SetBufferInfo

ISpAudio::SetBufferInfo sets the audio stream buffer information.

HRESULT SetBufferInfo(
   const SPAUDIOBUFFERINFO  *pBuffInfo
);

Parameters

pBuffInfo
[in] Pointer to the SPAUDIOBUFFERINFO buffer providing the requested settings.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_UNINITIALIZED | Audio stream not initialized.
E_INVALIDARG | pBuffInfo is invalid or the parameters do not meet the criteria described above.
SPERR_DEVICE_BUSY | Audio device is not in the SPAS_CLOSED state.
FAILED(hr) | Appropriate error message.

Remarks

This method can be called only when the audio device is in the SPAS_CLOSED state. The SPAUDIOBUFFERINFO members must conform to the following restrictions:

SPAudioBufferInfo.ulMsMinNotification cannot be larger than one quarter the size of SPAudioBufferInfo.ulMsBufferSize and must not be zero.
SPAudioBufferInfo.ulMsEventBias cannot be larger than SPAudioBufferInfo.ulMsBufferSize.
SPAudioBufferInfo.ulMsBufferSize must be greater than or equal to 200 milliseconds.


ISpAudio::GetBufferInfo (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpAudio::GetBufferInfo

ISpAudio::GetBufferInfo passes back the audio stream buffer information.

HRESULT GetBufferInfo(
  SPAUDIOBUFFERINFO   *pBuffInfo
);

Parameters

pBuffInfo
[out] Pointer to the SPAUDIOBUFFERINFO buffer.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pBuffInfo is invalid.


ISpAudio::GetDefaultFormat (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpAudio::GetDefaultFormat

ISpAudio::GetDefaultFormat passes back the default audio format.

HRESULT GetDefaultFormat(
   GUID            *pFormatId,
   WAVEFORMATEX   **ppCoMemWaveFormatEx
);

Parameters

pFormatId
[out] Pointer to the GUID of the default format.
ppCoMemWaveFormatEx
[out] Address of a pointer to the WAVEFORMATEX structure that receives the wave file format information. SAPI allocates the memory for the WAVEFORMATEX data structure using CoTaskMemAlloc, but it is the caller's responsibility to call CoTaskMemFree on the returned WAVEFORMATEX pointer.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_UNINITIALIZED | Stream is uninitialized.
E_POINTER | pFormatId is invalid.

Remarks

Other formats may be supported by the audio device; however, this format is guaranteed to work. Older sound cards can potentially fail when attempting to use this format if they are not fully duplex or do not support full duplex operation at different frequencies. An application should attempt to degrade gracefully when this occurs.


ISpAudio::EventHandle (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpAudio::EventHandle

ISpAudio::EventHandle returns a Win32 event handle that applications can use to wait for status changes in the I/O stream.

HANDLE  EventHandle( void );

Parameters

None

Return values

Value | Description
HANDLE | Returns valid event handle.

Remarks

The handle may use one of the various Win32 wait functions, such as WaitForSingleObject or WaitForMultipleObjects.

For read streams, set the event when there is data available to read and reset it whenever there is no available data. For write streams, set the event when all of the data has been written to the device, and reset it at any time when there is still data available to be played.

The caller should not close the returned handle, nor should the caller ever use the event handle after calling Release() on the audio object. The audio device will close the handle on the final release of the object.


ISpAudio::GetVolumeLevel (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpAudio::GetVolumeLevel

ISpAudio::GetVolumeLevel passes back the current volume level.

The volume level is on a linear scale from zero to 10000.

HRESULT GetVolumeLevel(
   ULONG   *pLevel
);

Parameters

pLevel
[out] Pointer to the returned volume level.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_UNINITIALIZED | Audio interface is not initialized.
SPERR_DEVICE_NOT_SUPPORTED | The device is not valid or does not support volumes.
E_POINTER | pLevel is invalid or bad.
FAILED(hr) | Appropriate error message.

Remarks

For input devices with a boost control for the microphone, SAPI will split the volume range into two to allow automated use of the boost. The boost will be off from zero to 4999 and on from 5000 to 10,000. In each range, the full volume range of the device will be used independently. This can lead to discontinuity in the input energy level for a constant volume sound source. On some sound cards, the boost is applied to the input volume, but on others, the boost is applied to the playback volume resulting in the two ranges behaving identically because the input level is unaffected.

Microphone wizards determining the best volume input level should take into consideration the potential discontinuity and ensure that the algorithm used to adjust the input volume level can handle the various possible forms of discontinuity at 5,000

For devices without a boost, there is no discontinuity at 5000.


ISpAudio::SetVolumeLevel (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpAudio::SetVolumeLevel

ISpAudio::SetVolumeLevel sets the current volume level. It is on a linear scale from zero to 10000.

HRESULT SetVolumeLevel(
   ULONG   Level
);

Parameters

Level
[in] The new volume level.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Level is greater than 10,000.
SPERR_DEVICE_NOT_SUPPORTED | The device is not valid or does not support volumes.
FAILED(hr) | Appropriate error message.

Remarks

For input devices with a boost control for the microphone, SAPI will split the volume range into two to allow automated use of the boost. The boost will be off from zero to 4,999 and on from 5,000 to 10,000. In each range, the full volume range of the device will be used independently. This can lead to discontinuity in the input energy level for a constant volume sound source. On some sound cards, the boost is applied to the input volume, but on others, the boost is applied to the playback volume resulting in the two ranges performing identically because the input level is unaffected.

Microphone wizards determining the best volume input level should take into consideration the potential discontinuity and ensure that the algorithm used to adjust the input volume level can handle the various possible forms of discontinuity at 5,000

For devices without a boost, there is no discontinuity at 5,000.


ISpAudio::GetBufferNotifySize (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpAudio::GetBufferNotifySize

ISpAudio::GetBufferNotifySize retrieves the audio stream buffer size information. This information is used to determine when the event returned by ISpAudio::EventHandle is set or reset.

HRESULT GetBufferNotifySize(
   ULONG   *pcbSize
);

Parameters

pcbSize
[out] Address of the size information, specified in bytes, that is associated with the audio stream buffer.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Invalid pointer.

Remarks

For read streams, the event is set if the audio buffered is greater than or equal to the value set in pcbSize, otherwise the event information is reset.

For write streams, the event is set if the audio buffered is less than the value set in pcbSize, otherwise the event information is reset.


ISpAudio::SetBufferNotifySize (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpAudio::SetBufferNotifySize

ISpAudio::SetBufferNotifySize sets the audio stream buffer size information. This information is used to determine when the event returned by ISpAudio::EventHandle is set or reset.

HRESULT SetBufferNotifySize(
   ULONG   cbSize
);

Parameters

cbSize
[in] The size, specified in bytes, of the information associated with the audio stream buffer.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED(hr) | Appropriate error message.

Remarks

For read streams, the event is set if the audio buffered is greater than or equal to the value set in cbSize, otherwise the event information is reset.

For write streams, the event is set if the audio buffered is less than the value set in cbSize, otherwise the event information is reset.


ISpMMSysAudio (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpMMSysAudio

This is the interface to the audio implementation for the standard Windows multimedia layer (wave in and wave out). Audio objects created through an object token do not allow ISpMMSysAudio::SetDeviceId to work because the token specifies which audio device ID to use. If an application wants to associate an audio object with a specific multimedia wave in or wave out device ID, it should use CoCreateInstance with CLSID_SpMMAudioOut or CLSID_SpMMAudioIn and then use the ISpMMSysAudio::SetDeviceId method to select the device. In normal application development, this will not be necessary for two reasons:

  • Desktop applications will generally use the shared recognizer instance which automatically uses the default audio device. This cannot be changed.
  • For the InProc recognizer instance, the audio device will attempt to use the default device id automatically.

For input devices, SAPI will attempt to automatically identify the microphone line on the input device. On non-English versions of Windows and on a small number of English systems, it may not be possible for SAPI to automatically detect the correct microphone line. In this case, no error will be detected or returned. In such cases, if speech input is not correctly detected, the user must set the microphone input line directly using Speech properties in Control Panel-->Speech Recognition tab-->Audio Input Settings-->Properties. In particular, it may be necessary to adjust the microphone input line used on devices with multiple microphone inputs such as the SoundBlaster Live Platinum because the default input line may not be the input preferred by the user.

Implemented By
  • SpMMAudioIn
  • SpMMAudioOut

Methods in Vtable Order

ISpMMSysAudio Methods | Description
ISpStreamFormat interface | Inherits from ISpStreamFormat and all methods are accessible from an ISpMMSysAudio object.
ISpAudio interface | Inherits from ISpAudio and all methods are accessible from an ISpMMSysAudio object.
GetDeviceId | Passes back the multimedia device ID being used by the audio object.
SetDeviceId | Sets the multimedia device ID.
GetMMHandle | Passes back a multimedia audio stream handle.
GetLineId | Retrieves the line identifier associated with the multimedia device.
SetLineId | Sets the line identifier associated with the multimedia device.

IStream functions as inherited from ISpAudio

Please see the MSDN IStream interface topic for a complete description of the IStream interface.

IStream Methods | Description
Seek | Retrieves only the current device position because multimedia devices represent hardware.
SetSize | Not used because multimedia devices represent hardware.
CopyTo | Copies a specified number of bytes from the current seek pointer in the stream to the current seek pointer in another stream.
Commit | Updates device state and commit buffered data. SAPI will automatically manage device state and buffered data, so that the developer is not expected to call this method.
Revert | Returns E_NOTIMPL because multimedia devices represent hardware.
LockRegion | Returns E_NOTIMPL because multimedia devices represent hardware.
UnlockRegion | Returns E_NOTIMPL because multimedia devices represent hardware.
Stat | Retrieves the current device position.
Clone | Returns E_NOTIMPL because multimedia devices represent hardware.


ISpMMSysAudio::GetDeviceId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpMMSysAudio::GetDeviceId

ISpMMSysAudio::GetDeviceId passes back the multimedia device ID being used by the audio object.

HRESULT GetDeviceId(
   UINT  *puDeviceId
);

Parameters

puDeviceId
[out] Pointer receiving the device ID.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | puDeviceId is a bad pointer.

Remarks

The default device ID for SpMMSysAudio objects that are created using CoCreateInstance is the WAVE_MAPPER. For audio objects created using an object token, the ID will always be a specific wave in or wave out device ID.

Example

The following code snippet illustrates the use of ISpMMSysAudio::GetDeviceId using CoCreateInstance.

// Declare local identifiers:
HRESULT                   hr = S_OK;
CComPtr<ISpMMSysAudio>    cpMMSysAudio;
UINT                      uiDeviceId;

// Create the multimedia input object.
hr = cpMMSysAudio.CoCreateInstance(CLSID_SpMMAudioIn);

if (SUCCEEDED(hr))
{
   // Get the default device Id (that
   // is, uiDeviceId == WAVE_MAPPER).
   hr = cpMMSysAudio->GetDeviceId(&uiDeviceId);
}

if (SUCCEEDED(hr))
{
   // Do something here.
}

The following code snippet illustrates the use of ISpMMSysAudio::GetDeviceId using an ISpObjectToken

// Declare local identifiers:
HRESULT                       hr = S_OK;
CComPtr<ISpMMSysAudio>        cpMMSysAudio;
CComPtr<ISpObjectWithToken>   cpObjectWithToken;
CComPtr<ISpObjectToken>       cpObjectToken;
UINT                          uiDeviceId;

// Create the multimedia input object.
hr = cpMMSysAudio.CoCreateInstance(CLSID_SpMMAudioIn);

if (SUCCEEDED(hr))
{
   // Get the current multimedia object's object token.
   hr = cpMMSysAudio.QueryInterface(&cpObjectWithToken);
}

if (SUCCEEDED(hr))
{
   // Find the preferred multimedia object token.
   hr = SpFindBestToken(SPCAT_AUDIOIN, L"Technology=MMSys", NULL, &cpObjectToken);
}

if (SUCCEEDED(hr))
{
   // Set the current multimedia object to the preferred multimedia object token.
   hr = cpObjectWithToken->SetObjectToken(cpObjectToken);
}

if (SUCCEEDED(hr))
{
   // Get the device id for the object (that
   // is, uiDeviceId != WAVE_MAPPER).
   hr = cpMMSysAudio->GetDeviceId(&uiDeviceId);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpMMSysAudio::SetDeviceId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpMMSysAudio::SetDeviceId

ISpMMSysAudio::SetDeviceId sets the multimedia device ID.

HRESULT SetDeviceId(
   UINT   uDeviceId
);

Parameters

uDeviceId
[in] The device ID of the device to set.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_DEVICE_BUSY | Object is not in the SPAS_CLOSED state.
SPERR_ALREADY_INITIALIZED | Object was created using an object token.
E_INVALIDARG | uDeviceId is invalid. It is not set to WAVE_MAPPER or device does not exist.

Remarks

This method works only on audio objects that were not created using an object token, and only when the object is in the SPAS_CLOSED state. This method should not be used in normal application development. SAPI provides tokens for all the available sound devices in a computer and these can be used to create an initialized SpMMSysAudio object. This method is available for non-standard multimedia audio devices.

Example

The following code snippet illustrates the use of ISpMMSysAudio::SetDeviceId.

// Declare local identifiers:
HRESULT                   hr = S_OK;
CComPtr<ISpMMSysAudio>    cpMMSysAudio;
UINT                      ALTERNATE_MM_DEVICE = 1;

// Create the multimedia output object.
hr = cpMMSysAudio.CoCreateInstance(CLSID_SpMMAudioOut);

if (SUCCEEDED (hr))
{
   // Set the output device to an alternate multimedia
   // device (for example, the modem).
   hr = cpMMSysAudio->SetDeviceId(ALTERNATE_MM_DEVICE);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpMMSysAudio::GetMMHandle (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpMMSysAudio::GetMMHandle

ISpMMSysAudio::GetMMHandle passes back a multimedia audio device stream handle.

HRESULT GetMMHandle(
   void   **pHandle
);

Parameters

pHandle
The wave in or wave out device handle.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pHandle is invalid.
SPERR_UNINITIALIZED | Audio object is in the SPAS_CLOSED state.

Remarks

The audio object must not be in the SPAS_CLOSED state or this call will fail because the multimedia device will not have been opened yet. The caller must not close the passed back handle. The caller must not use the handle either after changing the state of the audio object to SPAS_CLOSED or after releasing the object.


ISpMMSysAudio::GetLineId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpMMSysAudio::GetLineId

ISpMMSysAudio::GetLineId retrieves the current line identifier associated with the multimedia device. Mixer lines are not supported for output devices.

HRESULT GetLineId(
   UINT   *puLineId
);

Parameters

puLineId
[out] Address of the structure that receives the line identifier information.

Return values

Value | Description
S_OK | Function completed successfully.
E_NOTIMPL | Not implemented for output devices.
E_POINTER | puLineId is invalid.
SPERR_NOT_FOUND | The audio device must have been created from a token.
FAILED(hr) | Appropriate error message.

Remarks

For more information on the uses of device lines, please see the Win32 multimedia mixer API (e.g., mixerOpen, mixerGetId, mixerGetLineInfo, etc.)

For input devices, SAPI will attempt to automatically identify the microphone line on the input device. On non-English versions of Windows and on a small number of English systems, it may not be possible for SAPI to automatically detect the correct microphone line. In this case, no error will be detected or returned. In such cases, if speech input is not correctly detected, the user must set the microphone input line directly using Control Panel-->Speech properties-->Speech Recognition tab-->Audio Settings-->Properties. In particular, this may be necessary to adjust the microphone input line used on devices with multiple microphone inputs such as the SoundBlaster Live Platinum as the automatically chosen line may not be the input preferred by the user.


ISpMMSysAudio::SetLineId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpMMSysAudio::SetLineId

ISpMMSysAudio::SetLineId sets the line identifier associated with the multimedia device. Mixer lines are not supported for output devices.

HRESULT SetLineId(
   UINT   uLineId
);

Parameters

uLineId
[in] Value specifying the line identifier information.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | The specified uLineId is not supported on the current device.
SPERR_NOT_FOUND | The audio device must have been created from a token.
E_NOTIMPL | Not implemented for output devices.
FAILED(hr) | Appropriate error message.

Remarks

For more information on the uses of device lines, please see the Win32 multimedia mixer API (e.g., mixerOpen, mixerGetId, mixerGetLineInfo, etc.)

For input devices, SAPI attempts to automatically identify the microphone line on the input device. On non-English versions of Windows and on a few English systems, it may not be possible for SAPI to automatically detect the correct microphone line. In this case, no error will be detected or returned. If speech input is not correctly detected, the user must set the microphone input line directly using Control Panel-->Speech properties-->Speech Recognition tab-->Audio Settings-->Properties. It may be necessary to adjust the microphone input line used on devices with multiple microphone inputs such as the SoundBlaster Live Platinum. In these cases, the automatically chosen line may not be the input preferred by the user.


ISpStream (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStream

This interface provides two distinct functions:

  • The application developer can wrap an existing stream up by providing both an IStream and its format so that the underlying ISpStreamFormat can provide this data to SAPI when required. The new ISpStream object can be used as an input for SAPI wherever SAPI requires an ISpStreamFormat.
  • ISpStream creates an object from a file suitable for SAPI usage using BindToFile. The helper function SPBindToFile may also be used to simplify this process even further.
Implemented By
  • SpStream

Methods in Vtable Order

ISpStream Methods | Description
SetBaseStream | Sets the base address of the audio stream.
GetBaseStream | Retrieves the base address of the audio stream.
BindToFile | Binds the audio stream to the file that it identifies.
Close | Closes the audio stream.

Development Helpers

Helper Enumerations, Functions and Classes | Description
SPSTREAMFORMAT | SAPI supported stream formats
CSpStreamFormat | Class for managing SAPI supported stream formats and WAVEFORMATEX structures


ISpStream::SetBaseStream (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStream::SetBaseStream

ISpStream::SetBaseStream initializes the ISpStream object with the format of the IStream and an object to encapsulate.

HRESULT SetBaseStream(
    IStream                *pStream,
    REFGUID                 rguidFormat,
    const WAVEFORMATEX     *pWaveFormatEx
);

Parameters

pStream
Address of the IStream containing the base stream data.
rguidFormat
The data format identifier associated with the stream.
pWaveFormatEx
Address of the WAVEFORMATEX structure that contains the wave file format information. If guidFormatId is SPDFID_WaveFormatEx, this must point to a valid WAVEFORMATEX structure. For other formats, it should be NULL.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
SPERR_ALREADY_INITIALIZED | The object has already been initialized.
FAILED (hr) | Appropriate error message.

Remarks

The helper class CSpStreamFormat and the SPSTREAMFORMAT enumeration can be used to avoid the possibility of typos or mistakes when filling in the WAVEFORMATEX structure.


ISpStream::GetBaseStream (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStream::GetBaseStream

ISpStream::GetBaseStream retrieves the encapsulated IStream object for an instance of the ISpStream object.

HRESULT GetBaseStream(
   IStream   **ppStream
);

Parameters

ppStream
Address of a pointer to the encapsulated IStream that contains an audio stream or text stream.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | The ppStream pointer is invalid or bad.
SPERR_STREAM_CLOSED | The stream is closed or unavailable.
S_FALSE | The ISpStream instance has not been initialized with an IStream.


ISpStream::BindToFile (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStream::BindToFile

ISpStream::BindToFile binds the input stream to the file that it identifies.

HRESULT BindToFile(
   LPCWSTR              *pszFileName,
   SPFILEMODE            eMode,
   const GUID           *pguidFormatId,
   const WAVEFORMATEX	*pWaveFormatEx,
   ULONGLONG             ullEventInterest
);

Parameters

pszFileName
Address of a null-terminated string containing the file name of the file to bind the stream to.
eMode
Flag of the type SPFILEMODE to define the file opening mode. When opening an audio wave file, eMode must be SPFM_OPEN_READONLY or SPFM_CREATE_ALWAYS, otherwise the call will fail.
pguidFormatId
The data format identifier associated with the stream. This can be NULL and the format will be determined from the supplied wave file, if the file has the wav extension. If it does not, the file is assumed to be a text file.
pWaveFormatEx
Address of the WAVEFORMATEX structure that contains the wave file format information. If guidFormatId is SPDFID_WaveFormatEx, this must point to a valid WAVEFORMATEX structure. For other formats, it should be NULL.
ullEventInterest
Flags of type SPEVENTENUM (that is, the possible events raised by SAPI) for the format converter to watch. Typical events are those to be serialized into the audio stream (for audio output) or those to be deserialized out of the audio stream and fed to SAPI (for audio input).

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | At least one of the following was encountered. pszFileName or pguidFormatId is invalid or bad; eMode exceeds SPFM_CREATE_ALWAYS; an operation could not be completed.
E_OUTOFMEMORY | Exceeded available memory.
STG_E_FILENOTFOUND | File pszFileName does not exist.
SPERR_ALREADY_INITIALIZED | The object has already been initialized.
FAILED (hr) | Appropriate error message.

Remarks

In speech recognition, ::BindToFile supports only wave audio files. It passes SAPI an audio file to pass to the engine. In text-to-speech, ::BindToFile supports both audio and text files. See ISpVoice::SpeakStream for more information.

The helper class CSpStreamFormat and the SPSTREAMFORMAT enumeration can be used to avoid the possibility of typos or mistakes when filling in the WAVEFORMATEX structure.

Example

The following code snippet illustrates the use of ISpStream::BindToFile for creating a writable wave file

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpStream>         cpSpStream;
CSpStreamFormat            Fmt;
WCHAR                      *WAVE_DATA_CHUNK = L"#$%^&*";
ULONG                      SIZEOF_WAVE_DATA_CHUNK = 12;
ULONG                      cbWritten;

// Create the stream object.
hr = cpSpStream.CoCreateInstance(CLSID_SpStream);

if (SUCCEEDED(hr))
{
   // Create a stream format helper for 22khzm 16-bit, mono wave stream.
   CSpStreamFormat Fmt(SPSF_22kHz16BitMono, &hr);
}

if (SUCCEEDED(hr))
{
   // Create new stream and its corresponding file on hard
   // disk (specify the file format when creating the file).
   hr = cpSpStream->BindToFile(L"C:\\Test.wav", SPFM_CREATE_ALWAYS, &Fmt.FormatId(), Fmt.WaveFormatExPtr(), NULL);
}

if (SUCCEEDED(hr))
{
   // Write some data to the stream.
   hr = cpSpStream->Write(WAVE_DATA_CHUNK, SIZEOF_WAVE_DATA_CHUNK, &cbWritten);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}

The following code snippet illustrates the use of ISpStream::BindToFile for creating a read-only wave file

// Declare local identifiers:
HRESULT                 hr = S_OK;
CComPtr<ISpStream>      cpSpStream;
ULONG                   bData;
ULONG                   cbWritten;
ULONG                   SIZEOF_WAVE_DATA_CHUNK = 100;

// Create the stream object.
hr = cpSpStream.CoCreateInstance(CLSID_SpStream);

if (SUCCEEDED(hr))
{
   // Create new stream and its corresponding file on hard
   // disk (specify the file format when creating the file).
   hr = cpSpStream->BindToFile(L"C:\\Test.wav", SPFM_CREATE_ALWAYS, &Fmt.FormatId(), Fmt.WaveFormatExPtr(), NULL);
}

if (SUCCEEDED(hr))
{
   // Create a stream format helper for 22khzm 16-bit, mono wave stream.
   CSpStreamFormat Fmt(SPSF_22kHz16BitMono, &hr);
}

if (SUCCEEDED(hr))
{
   // Write some data to the stream.
   hr = cpSpStream->Write(WAVE_DATA_CHUNK, SIZEOF_WAVE_DATA_CHUNK, &cbWritten);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpStream::Close (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStream::Close

ISpStream::Close closes the audio stream or file and validates the close operation.

HRESULT  Close  ( void );

Parameters

None.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_STREAM_CLOSED | The stream is closed or unavailable.
FAILED (hr) | Appropriate error message.

Remarks

Releasing the ISpStream object will automatically call this method. However, any errors encountered will not be sent as notifications to the application. Hence the application can explicitly call this method first to check that no errors occurred during the close operation.


ISpStreamFormat (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStreamFormat

ISpStreamFormat inherits from IStream.

This is the minimum extra interface required by SAPI in addition to the IStream interface. Using this interface, SAPI can query the stream to determine the format of the stream data. Almost all SAPI functions requiring or returning a stream will require or return an ISpStreamFormat.

When to Implement

This interface should be implemented when implementing a stream from scratch. If an IStream already exists, SAPI can use it with the provided ISpStream object. In normal usage, this interface does not need to be implemented.

Implemented By
  • SpMMAudioIn
  • SpMMAudioOut
  • SpStreamFormatConverter
  • SpStream

Methods in Vtable Order

ISpStreamFormat Methods | Description
GetFormat | Passes back the cached format of the stream.

Development Helpers

Helper Enumerations, Functions and Classes | Description
SPSTREAMFORMAT | SAPI supported stream formats
CSpStreamFormat | Class for managing SAPI supported stream formats and WAVEFORMATEX structures


ISpStreamFormat::GetFormat (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStreamFormat::GetFormat

ISpStreamFormat::GetFormat passes back the cached format of the stream.

SAPI uses this data to determine how to handle the stream data present in the underlying IStream.

HRESULT GetFormat(
   GUID           *pguidFormatId,
   WAVEFORMATEX  **ppCoMemWaveFormatEx
);

Parameters

pguidFormatId
Address of a pointer to GUID data object that receives the format of the stream being used. This is typically either SPDFID_Text or SPDFID_WaveFormatEx.
ppCoMemWaveFormatEx
Address of a pointer to a WAVEFORMATEX data structure that receives the wave file format information. This is only applicable when the return GUID is SPDFID_WaveFormatEx. The implementer of this interface allocates the memory for the WAVEFORMATEX data structure using CoTaskMemAlloc, but it is the caller's responsibility to call CoTaskMemFree on the returned WAVEFORMATEX pointer.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Pointer is locating a memory block that is NULL or either too small or is not writable.
SPERR_UNINITIALIZED | The object has not been properly initialized.
SPERR_STREAM_CLOSED | The stream is closed or unavailable.


ISpStreamFormatConverter (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStreamFormatConverter

ISpStreamFormatConverter is the primary interface implemented by the SAPI audio data format converter. SAPI uses the format converter to compensate for differences between supported SR and TTS engine formats, and the I/O formats requested by the application. Typically applications and engines do not use this object directly. The format converter is a wrapper object that encapsulates the specified base stream. It performs conversion on the fly during read/write operations. The Windows ACM (Audio Compression Manager) layer performs the conversion.

Several methods are included in addition to the ISpStreamFormat interface to allow data conversion.

Implemented By
  • SpStreamFormatConverter

Remarks

SAPI utilizes the host system's installed audio codecs to perform the conversion. SAPI currently supports 1-stage and 2-stage stream conversions, but does not support 3-or-more-stage conversions.

An example of a 1-stage stream format conversion is the conversion of a PCM format to another PCM format (e.g., 8kHz 16-bit Stereo PCM [SPSF_8kHz16BitStereo] -> 44kHz 8-bit Mono [SPSF_44kHz8BitMono]). This requires only one codec (e.g., "Microsoft PCM Converter").

An example of a 2-stage stream conversion is the conversion of a compressed format to a PCM format (e.g., TrueSpeech 8kHz 1-Bit Mono [SPSF_TrueSpeech_8kHz1BitMono] -> 8kHz 8-bit Mono PCM [SPSF_8kHz8BitMono] -> 44kHz 16-bit Stereo [SPSF_44kHz16BitStereo]). This requires two codecs (e.g., "DSP Group TrueSpeech(TM) Audio" and "Microsoft PCM Converter"). Note that one of the formats must be a PCM format.

An example of an unsupported 3-stage stream conversion is the conversion of a compressed format to another compressed format (e.g., TrueSpeech 8kHz 1-Bit Mono [SPSF_TrueSpeech_8kHz1BitMono] -> 8kHz 8-bit Mono PCM [SPSF_8kHz8BitMono] -> 8kHz 8-bit Stereo PCM [SPSF_8kHz8BitStereo] -> ALaw 8kHz Stereo [SPSF_CCITT_ALaw_8kHzStereo]). This would require three codecs (e.g., "DSP Group TrueSpeech(TM) Audio", "Microsoft PCM Converter", and "Microsoft CCITT G.771 Audio"). Note that SAPI is capable of converting between two compressed non-PCM formats if a single codec can do the entire conversion.

Methods in Vtable Order

ISpStreamFormatConverter Methods | Description
ISpStreamFormat interface | Inherits from ISpStreamFormat and all those methods are accessible from an ISpStreamFormatConverter object.
SetBaseStream | Sets audio stream to be wrapped by the format converter.
GetBaseStream | Gets the base audio stream that is being wrapped.
SetFormat | Sets the conversion (output) format.
ResetSeekPosition | Resets the format converter's stream seek position to the start of the stream.
ScaleConvertedToBaseOffset | Maps an offset in the converted stream into an offset in the base stream.
ScaleBaseToConvertedOffset | Maps an offset in the base stream into an offset in the converted stream.

Development Helpers

Helper Enumerations, Functions and Classes | Description
SPSTREAMFORMAT | SAPI supported stream formats
CSpStreamFormat | Class for managing SAPI supported stream formats and WAVEFORMATEX structures


ISpStreamFormatConverter::SetBaseStream (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStreamFormatConverter::SetBaseStream

ISpStreamFormatConverter::SetBaseStream sets an audio stream to be wrapped by the format converter. The format converter is a stream object that encapsulates the base stream and performs format conversion on the fly during read/write operations.

HRESULT SetBaseStream(
   ISpStreamFormat   *pStream,
   BOOL               fSetFormatToBaseStreamFormat,
   BOOL               fWriteToBaseStream
);

Parameters

pStream
[in] The stream to be wrapped. If NULL, the current base stream is released and any associated resources are released.
fSetFormatToBaseStreamFormat
[in] Flag specifies that the converter's stream format will be set to the same format as the base stream (set up as a pass through).

If pStream == NULL and this is set to TRUE, the format converter's stream format is reset to be undefined.

fWriteToBaseStream
[in] If TRUE, data will be written to the base stream. If FALSE, data will be read from the base stream. The format converter can only be in one I/O mode or the other at a time.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pStream was invalid.


ISpStreamFormatConverter::GetBaseStream (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStreamFormatConverter::GetBaseStream

ISpStreamFormatConverter::GetBaseStream gets the base audio stream that is being wrapped.

HRESULT GetBaseStream(
   ISpStreamFormat  **ppStream
);

Parameters

ppStream
[out] This parameter can be NULL to simply test if there is an associated base stream.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | No base stream is present.
E_POINTER | Pointer is bad or invalid.


ISpStreamFormatConverter::SetFormat (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStreamFormatConverter::SetFormat

ISpStreamFormatConverter::SetFormat sets the output format of the converter.

The ISpStreamFormat::GetFormat method returns the format of the output (converted) stream.

HRESULT SetFormat(
   REFGUID               rguidFormatIdOfConvertedStream,
   const WAVEFORMATEX   *pWaveFormatExOfConvertedStream
);

Parameters

rguidFormatIdOfConvertedStream
[in] Address of the data format identifier associated with the requested output stream. Can be GUID_NULL or SPDFID_WaveFormatEx.
pWaveFormatExOfConvertedStream
[in] Address of the WAVEFORMATEX structure containing the wave file format information of the converted stream. Must be NULL with GUID_NULL. Must be a valid WAVEFORMATEX with SPDFID_WaveFormatEx.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One of the following was encountered: rguidFormatIdOfConvertedStream is neither GUID_NULL or SPDFID_WaveFormatEx; pWaveFormatExOfConvertedStream is not valid for the supplied REFGUID.

Remarks

The helper class CSpStreamFormat and the SPSTREAMFORMAT enumeration can be used to avoid the possibility of typos or mistakes when filling in the WAVEFORMATEX structure.


ISpStreamFormatConverter::ResetSeekPosition (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStreamFormatConverter::ResetSeekPosition

ISpStreamFormatConverter::ResetSeekPosition resets the format converter's stream seek position to the start of the stream. This method changes the seek position of the base stream to zero.

HRESULT ResetSeekPosition( void );

Parameters

None.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_UNINITIALIZED | Current stream base is uninitialized.


ISpStreamFormatConverter::ScaleConvertedToBaseOffset (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStreamFormatConverter::ScaleConvertedToBaseOffset

ISpStreamFormatConverter::ScaleConvertedToBaseOffset maps a stream offset from the converted stream to the equivalent offset in the base stream.

HRESULT ScaleConvertedToBaseOffset(
   ULONGLONG    ullOffsetConvertedStream,
   ULONGLONG   *pullOffsetBaseStream
);

Parameters

ullOffsetConvertedStream
The offset of the output (converted) stream.
pullOffsetBaseStream
The equivalent offset in the base (unconverted) stream.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pullOffsetBaseStream is invalid.
SPERR_UNINITIALIZED | The base stream has not been initialized.

Remarks

When performing a mapping with a compressed format, it is possible to introduce small rounding errors, since the content of the audio is not used to perform the conversion.


ISpStreamFormatConverter::ScaleBaseToConvertedOffset (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpStreamFormatConverter::ScaleBaseToConvertedOffset

ISpStreamFormatConverter::ScaleBaseToConvertedOffset converts an offset in the base stream into the equivalent offset in the converted stream. This method is primarily used internally to map event offsets.

HRESULT ScaleBaseToConvertedOffset(
   ULONGLONG   ullOffsetBaseStream,
   ULONGLONG  *pullOffsetConvertedStream
);

Parameters

ullOffsetBaseStream
The current offset in the base (unconverted) stream.
pullOffsetConvertedStream
The new offset in the output (converted) stream.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pullOffsetConvertedStream is bad or invalid.
SPERR_UNINITIALIZED | The base stream is not initialized.
E_INVALIDARG | ullOffsetBaseStream is less than the initial seek position of the current steam.

Remarks

When performing a mapping with a compressed format, it is possible to introduce small rounding errors, since the content of the audio is not used to perform the conversion.


ISpTranscript (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpTranscript

A transcript is a text string associated with a piece of audio data. The SAPI SpStream object supports the ISpTranscript interface for wav audio files.

Associated Class IDs

The following class IDs (CLSID) may be used with this interface. A complete CLSID listing for all interfaces is in the Class IDs section.

    CLSID_SpStream

Methods in Vtable Order

ISpTranscript Methods | Description
GetTranscript | Gets the current transcript.
AppendTranscript | Adds the current text to the transcript.

Development Helpers

Helper Enumerations, Functions and Classes | Description
CSpDynamicString | Class for managing dynamically sized Unicode strings


ISpTranscript::GetTranscript (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpTranscript::GetTranscript

ISpTranscript::GetTranscript gets the current transcript. The string returned will be allocated by CoTaskMemAlloc and applications implementing this method must call CoTaskMemFree() to free memory associated with this string.

HRESULT GetTranscript(
   LPWSTR    **ppszTranscript
);

Parameters

ppszTranscript
[out, string] A pointer to the null-terminated transcription string.

Return values

Value | Description
S_OK | Function completed successfully. ppszTranscript contains a CoTaskMemAllocated string.
E_OUTOFMEMORY | Exceeded available memory.
SPERR_UNINITIALIZED | Object has not been initialized.
E_POINTER | ppszTranscript is bad or invalid.
S_FALSE | No transcript is present and ppszTranscript will be NULL.
FAILED (hr) | Appropriate error message.

Example

The following code snippet illustrates the use of ISpTranscript::GetTranscript.

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpStream>         cpStream;
CComPtr<ISpTranscript>     cpTranscript;
PWCHAR                     pwszTranscript;

// Bind a stream to an existing wavefile (assumes
// existence of the file "C:\VoiceToFile.wav").
hr = SPBindToFile(L"C:\\VoiceToFile.wav", SPFM_CREATE_ALWAYS, &cpStream);

if (SUCCEEDED(hr))
{
   hr = cpStream.QueryInterface(&cpTranscript);
}

if (SUCCEEDED(hr))
{
   hr = cpTranscript->GetTranscript(&pwszTranscript);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}

// Release system resources.
::CoTaskMemFree(&pwszTranscript);


ISpTranscript::AppendTranscript (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpTranscript::AppendTranscript

ISpTranscript::AppendTranscript adds the current text to the transcript.

HRESULT AppendTranscript(
   LPCWSTR    *pszTranscript
);

Parameters

pszTranscript
[in, string] The text of the transcript. If pszTranscript is NULL, the current transcript is deleted. Otherwise, the text is appended to the current transcript.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszTranscript is bad or invalid.
E_OUTOFMEMORY | Exceeded available memory.
FAILED (hr) | Appropriate error message.

Example

The following code snippet illustrates the use of ISpTranscript::AppendTranscript.

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpStream>         cpStream;
CComPtr<ISpTranscript>     cpTranscript;

// Bind a stream to an existing wavefile (assumes
// existence of the file "C:\VoiceToFile.wav").
hr = SPBindToFile(L"C:\\VoiceToFile.wav", SPFM_CREATE_ALWAYS, &cpStream);

if (SUCCEEDED(hr))
{
   hr = cpStream.QueryInterface(&cpTranscript);
}

if (SUCCEEDED(hr))
{
   hr = cpTranscript->AppendTranscript(L"this is a test");
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


Eventing interfaces (Microsoft Speech Platform)

 Microsoft Speech Platform

Eventing interfaces

This section provides SAPI 5 event information.

  • ISpNotifySource
  • ISpNotifySink
  • ISpNotifyTranslator
  • ISpEventSink
  • ISpEventSource
  • ISpEventSource2
  • ISpNotifyCallback


ISpNotifySource (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifySource

In both speech synthesis and speech recognition, applications receive notifications when words have been spoken or when phrases have been recognized. SAPI components that generate notifications implement an ISpNotifySource.

The ISpNotifySource and ISpNotifySink interfaces alone only provide a mechanism for a notification but no information on the events that caused the notification. With an ISpEventSource object, an application can retrieve information about the events that caused the notification.

Applications will not typically use the free-threaded ISpNotifySink mechanism for receiving SAPI event notifications. They will use one of the simplified methods of either a window message, callback or Win32 event.

Note that both variations of callbacks as well as the window message notification require a window message pump to run on the thread that initialized the notification source. Callback will only be called as the result of window message processing, and will always be called on the same thread that initialized the notify source. However, using Win32 events for SAPI event notification does not require a window message pump.

Implemented By
  • SpRecoContext
  • SpSharedRecoContext
  • SpVoice
  • SpMMAudioIn
  • SpMMAudioOut
  • SpRecPlayAudio
  • SpStreamFormatConverter

Methods in Vtable Order

ISpNotifySource Methods | Description
SetNotifySink | Sets up the instance to make free-threaded calls through ISpNotifySink::Notify. This method can also be used to unregister an existing notification.
SetNotifyWindowMessage | Sets a window handle to receive notifications as window messages.
SetNotifyCallbackFunction | Sets a callback function to receive notifications.
SetNotifyCallbackInterface | Sets an object to receive notifications.
SetNotifyWin32Event | Sets up a Win32 event object to be used by this instance for notifications.
WaitForNotifyEvent | A blocking call which waits for a notification.
GetNotifyEventHandle | Retrieves Win32 event handle associated with this notify source.


ISpNotifySource::SetNotifySink (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifySource::SetNotifySink

ISpNotifySource::SetNotifySink sets up the instance to make free-threaded notification calls through ISpNotifySink::Notify.

HRESULT SetNotifySink(
   ISpNotifySink  *pNotifySink
);

Parameters

pNotifySink
[in] Pointer to the notification interface. If pNotifySink is NULL, any current notification mechanism (notify sink, window message, callback, or Win32 event) is removed.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Interface pointer is invalid.
FAILED (hr) | Appropriate error message.

Remarks

If pNotifySink is NULL, any notification mechanism currently associated with this notify source is removed.

Because free-threaded notifications can occur on any thread, at any point during execution, they are extremely prone to deadlocks and re-entrance problems. See the documentation for ISpNotifySink for more details. Most applications will find one of the other notification mechanisms much easier to use.


ISpNotifySource::SetNotifyWindowMessage (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifySource::SetNotifyWindowMessage

ISpNotifySource::SetNotifyWindowMessage sets up the instance to send window messages to a specified window.

HRESULT SetNotifyWindowMessage(
   HWND     hWnd,
   UINT     Msg,
   WPARAM   wParam,
   LPARAM   lParam
);

Parameters

hWnd
[in] Handle to the window whose message handler function will receive SAPI notifications.
Msg
[in] Message number which will be passed into the message handler function of the window hWnd.
wParam
[in] wParam that will be passed into the message handler function of the window hWnd.
lParam
[in] lParam that will be passed into the message handler function of the window hWnd.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | hWnd is an invalid window handle.
FAILED (hr) | Appropriate error message.


ISpNotifySource::SetNotifyCallbackFunction (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifySource::SetNotifyCallbackFunction

ISpNotifySource::SetNotifyCallbackFunction sets up this instance to send notifications using a standard C-style callback function.

HRESULT SetNotifyCallbackFunction(
   SPNOTIFYCALLBACK   *pfnCallback,
   WPARAM              wParam,
   LPARAM              lParam
);

Parameters

pfnCallback
[in] The notification callback function to be used.
wParam
[in] Constant WPARAM value that will be passed to the pfnCallback function when it is called.
lParam
[in] Constant LPARAM value that will be passed to the pfnCallback function when it is called.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Callback function is invalid.
FAILED (hr) | Appropriate error message.

Remarks

It is the responsibility of the client code to control the lifetime of a notification. To remove an installed notify callback, call ISpEventSource::SetNotifySink (NULL). The final release of an object that supports ISpEventSource will automatically remove an installed notify callback.

The SAPI implementation uses a hidden window to call back the client on the same thread that was used to initialize the event source. Notification callbacks are the result of processing a window message. When this notification mechanism is used:

  1. The SPNOTIFYCALLBACK method will always be called on the thread that initialized the event source or notify translator object.
  2. The thread must have a window message pump.

The SPNOTIFYCALLBACK function is declared as follows:

typedef void __stdcall SPNOTIFYCALLBACK(WPARAM wParam, LPARAM lParam);


ISpNotifySource::SetNotifyCallbackInterface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifySource::SetNotifyCallbackInterface

ISpNotifySource::SetNotifyCallbackInterface sets up this instance to call the virtual method ISpNotifyCallback::NotifyCallback for notifications.

HRESULT SetNotifyCallbackInterface(
   ISpNotifyCallback   *pSpCallback,
   WPARAM               wParam,
   LPARAM               lParam
);

Parameters

pSpCallback
[in] A pointer to an application-defined implementation of the ISpNotifyCallback interface.
wParam
[in] Constant WPARAM value that will be passed to the ISpNotifyCallback::NotifyCallback method when it is called.
lParam
[in] Constant LPARAM value that will be passed to the ISpNotifyCallback::NotifyCallback method when it is called.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pSpCallback is invalid.
FAILED (hr) | Appropriate error message.

Remarks

The application will be called back on the same thread that calls this method. The callback will be called as a result of window message processing, so the thread must have a message pump. For more details, see the documentation for ISpNotifyCallback.


ISpNotifySource::SetNotifyWin32Event (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifySource::SetNotifyWin32Event

ISpNotifySource::SetNotifyWin32Event sets up a Win32 event object to be used by this instance for notifications. The event handle can be retrieved through GetNotifyEventHandle.

HRESULT   SetNotifyWin32Event  ( void );

Parameters

None

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.

Remarks

Once an event object has been initialized for this instance, use either WaitForNotifyEvent or use GetNotfyEventHandle and wait using one of the various Win32 synchronization functions. Note that Win32 event objects and SAPI events are different objects.


ISpNotifySource::WaitForNotifyEvent (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifySource::WaitForNotifyEvent

ISpNotifySource::WaitForNotifyEvent is a blocking call that waits on a Win32 event handle for a SAPI notification.

HRESULT WaitForNotifyEvent(
   DWORD   dwMilliseconds
);

Parameters

dwMilliseconds
[in] Number of milliseconds for the timeout on a blocking call. If set to INFINITE, there is no timeout.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | The operation timed-out.
SPERR_ALREADY_INITIALIZED | This event source has been initialized to use a notification mechanism other than a Win32 event. It was unable to re-initialize the notification.
FAILED (hr) | Appropriate error message.

Remarks

A blocking call returns when a SAPI notification has fired, a timeout has passed, or the initialized Win32 event object has signaled. Calling this method will automatically initialize the event source to use an event handle if no other notification mechanism has been initialized.


ISpNotifySource::GetNotifyEventHandle (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifySource::GetNotifyEventHandle

ISpNotifySource::GetNotifyEventHandle retrieves the Win32 event object handle. This event can be used in any of the Win32 WaitForxxx methods.

HANDLE   GetNotifyEventHandle  ( void );

Parameters

None

Return values

Value | Description
Win32 event handle | Initialized by SetNotifyWin32Event on this instance.
INVALID_HANDLE_VALUE | Interface not initialized.

Remarks

Do not close the returned handle, as it is owned by the event source object. Calling this method will automatically initialize the event source to use an event handle if no other notification mechanism has been initialized.


ISpNotifySink (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifySink

In both speech synthesis and speech recognition, applications receive notifications when words have been spoken or when phrases have been recognized. SAPI components that generate notifications implement an ISpNotifySource.

The ISpNotifySource and ISpNotifySink interfaces alone only provide a mechanism for a notification but no information on the events that caused the notification. With an ISpEventSource object, an application can retrieve information about the events that caused the notification. An ISpEventSource also provides the mechanism to filter and queue events. By default, an application (really an ISpNotifySink) receives no notifications from ISpEventSource until SetInterests has been called to specify on which events to notify or queue.

When an application is notified of an event that is not queued, an application will take measures based on which event sink is receiving the notification. From context an application might know exactly what it needs to do, or it may need to interact with the components which sent the notifications. If an application is notified of an event that is queued, the application will call ISpEventSource::GetEvents to retrieve the actual events that caused a notification.

When to Implement

Implement this interface only if the application can take advantage of the slightly reduced latency of a free-threaded notification. Most applications should use one of the simplified notification mechanisms in ISpEventSource instead of implementing this interface directly. Free-threaded notifications are difficult to implement without deadlocking the system. Furthermore, other notification mechanisms require less code on the part of the developer. The application needs to handle free-threaded notifications and implement the ISpNotifySink interface when an ISpNotifySink object is to be notified.

Because free-threaded notifications can occur on any thread, at any point during execution, they are extremely prone to deadlocks and re-entrance problems. The only interface that can be called on an event source object is ISpEventSource::GetEvents. If the ISpNotifySink interface is implemented directly, the code should only use some mechanism to signal another thread to process the notification (for example, a Win32 event or an I/O completion port), and, if needed, call ISpEventSource::GetEvents. Do not call any other methods.

Methods in Vtable Order

ISpNotifySink Methods | Description
Notify | Called by an ISpNotifySource object to notify the sink when the state of the notify source has changed.


ISpNotifySink::Notify (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifySink::Notify

ISpNotifySink::Notify is called by an ISpNotifySource object to notify the sink when the state of the notify source has changed.

HRESULT   Notify  ( void );

Parameters

None

Return values

Value | Description
S_OK | Function completed successfully.
FAILED(hr) | Object failed notification.

Remarks

The only interface that can be called on an event source object is ISpEventSource::GetEvents. The Notify() method should only signal another thread to process the notification (for example, a Win32 event or an I/O completion port), and if needed, call ISpEventSource::GetEvents. Do not call any other methods.


ISpNotifyTranslator (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifyTranslator

Once the SpNotifyTranslator object has been initialized, the ISpNotifySource::SetNotifySink method can be called, passing the translator object interface as the parameter. The translator will then convert the call to ISpNotifySink::Notify into the appropriate notification.

Because ISpNotifySource supports most of the functionality of this interface, application writers will not normally use either this interface or the SpNotifyTranslator object. In fact, SAPI uses this object to implement the various methods of ISpNotifySource. The method InitWin32Event supports the ability to initialize the translator with a specific event object, and so could be used for that purpose.

Implemented By
  • SpNotifyTranslator

Methods in Vtable Order

ISpNotifyTranslator Methods | Description
ISpNotifySink interface | Inherits from ISpNotifySink and those methods are accessible from an ISpNotifyTranslator object.
InitWindowMessage | Sets up the instance to send window messages to a specified window.
InitCallback | Sets up this instance to send notifications using a standard C-style callback function.
InitSpNotifyCallback | Enables an object derived from ISpNotifyCallback to receive notifications.
InitWin32Event | Sets up a Win32 event object to be used by this instance.
Wait | A blocking call that returns when a SAPI notification has fired and the associated Win32 event object has been signaled or a timeout has passed.
GetEventHandle | Returns the Win32 event handle associated with the translator.


ISpNotifyTranslator::InitWindowMessage (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifyTranslator::InitWindowMessage

ISpNotifyTranslator::InitWindowMessage sets up the instance to send window messages to a specified window.

HRESULT InitWindowMessage(
   HWND      hWnd,
   UINT      Msg,
   WPARAM    wParam,
   LPARAM    lParam
);

Parameters

hWnd
[in] Handle to the window whose message handler function will receive SAPI notifications.
Msg
[in] Message number which will be passed into the message handler function of the window hWnd.
wParam
[in] wParam that will be passed into the message handler function of the window hWnd.
lParam
[in] lParam that will be passed into the message handler function of the window hWnd

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_ALREADY_INITIALIZED | SpTranslator object already initialized.
E_INVALIDARG | hWnd is invalid or bad.
FAILED(hr) | Appropriate error message.


ISpNotifyTranslator::InitCallback (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifyTranslator::InitCallback

ISpNotifyTranslator::InitCallback sets up this instance to send notifications using a standard C-style callback function.

HRESULT InitCallback(
   SPNOTIFYCALLBACK   *pfnCallback,
   WPARAM              wParam,
   LPARAM              lParam
);

Parameters

pfnCallback
[in] The notification callback function to be used.
wParam
[in] Constant WPARAM value that will be passed to the pfnCallback function when it is called.
lParam
[in] Constant LPARAM value that will be passed to the pfnCallback function when it is called.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_ALREADY_INITIALIZED | SpTranslator object is already initialized.
E_INVALIDARG | pfnCallback is invalid or bad.
FAILED(hr) | Appropriate error message.

Remarks

The translator implementation uses a hidden window to call back the client on the same thread that was used to initialize the event source. Notify callbacks are the result of processing a window message. When this notification mechanism is used:

  1. The SPNOTIFYCALLBACK method will always be called on the thread that initialized the event source or notify translator object.
  2. The thread must have a window message pump.

The SPNOTIFYCALLBACK function is declared as follows:

typedef void __stdcall SPNOTIFYCALLBACK(WPARAM wParam, LPARAM lParam);


ISpNotifyTranslator::InitSpNotifyCallback (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifyTranslator::InitSpNotifyCallback

ISpNotifyTranslator::InitSpNotifyCallback sets up this instance to call the virtual method ISpNotifyCallback::NotifyCallback for notifications.

HRESULT InitSpNotifyCallback(
   ISpNotifyCallback   *pSpCallback,
   WPARAM               wParam,
   LPARAM               lParam
);

Parameters

pSpCallback
[in] A pointer to an application-defined implementation of the ISpNotifyCallback interface.
wParam
[in] Constant WPARAM value that will be passed to the ISpNotifyCallback::NotifyCallback method when it is called.
lParam
[in] Constant LPARAM value that will be passed to the ISpNotifyCallback::NotifyCallback method when it is called.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_ALREADY_INITIALIZED | Translator object is already initialized.
E_INVALIDARG | pSpNotifyCallback is invalid or bad.
FAILED(hr) | Appropriate error message.

Remarks

The application will be called back on the same thread that calls this method. The callback will be called as a result of window message processing, so the thread must have a message pump. For more details, see the documentation for ISpNotifyCallback.


ISpNotifyTranslator::InitWin32Event (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifyTranslator::InitWin32Event

ISpNotifyTranslator::InitWin32Event sets up a Win32 event object to be used by this instance.

HRESULT InitWin32Event(
    HANDLE   hEvent,
    BOOL     fCloseHandleOnRelease
);

Parameters

hEvent
Handle of an existing Win32 event object for the application to use with ISpNotifyTranslator. If this parameter is NULL, a new event will be created.
fCloseHandleOnRelease
Specifies whether the hEvent handle should be closed when the object is released. If hEvent is NULL, this parameter is ignored and the handle will always be closed upon release of the object.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_ALREADY_INITIALIZED | Interface is already initialized.
FAILED(hr) | Appropriate error message.

Remarks

The translator will call the Win32 method ::SetEvent() whenever the translator's Notify() method is called.

Initialize an event object for this instance, and then use either the WaitForNotifyEvent or GetNotfyEventHandle method. Win32 event objects and SAPI events are different. This method is similar to ISpNotifySource::SetNotifyWin32Event.


ISpNotifyTranslator::Wait (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifyTranslator::Wait

ISpNotifyTranslator::Wait is a blocking call that returns when a SAPI notification has fired and the associated Win32 event object has been signaled or a timeout has passed. This method is applicable only with objects using Win32 events.

HRESULT Wait(
   DWORD   dwMilliseconds
);

Parameters

dwMilliseconds
[in] Number of milliseconds for the timeout on a blocking call. If set to INFINITE, there is no timeout.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | The event was not set and the call was timed out.
SPERR_UNINITIALIZED | InitWin32Event did not return successfully or has not been called.


ISpNotifyTranslator::GetEventHandle (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifyTranslator::GetEventHandle

ISpNotifyTranslator::GetEventHandle returns the Win32 event handle associated with the translator.
Returns the Win32 event object handle initialized by InitWin32Event on this ISpNotifyTranslator instance. This method is applicable only with objects using Win32 events.

The handle is not a duplicated handle and should not be closed by the caller.

HANDLE   GetEventHandle   ( void );

Parameters

None

Return values

Value | Description
handle | The handle to the event
INVALID_HANDLE_VALUE | Translator has not been properly initialized by calling InitWin32Event().


ISpEventSink (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpEventSink

This interface allows event sources to send events directly to an event sink through a free-threaded call.

Associated Class IDs

The following class IDs (CLSID) may be used with this interface. A complete CLSID listing for all interfaces is in the Class IDs section.

    CLSID_SpStreamFormatConverter
    CLSID_SpStream

Methods in Vtable Order

ISpEventSink Methods | Description
AddEvents | Adds events directly to an event sink.
GetEventInterest | Passes back the event interest for the voice.


ISpEventSink::AddEvents (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpEventSink::AddEvents

ISpEventSink::AddEvents adds events directly to an event sink.

HRESULT AddEvents(
   const SPEVENT    *pEventArray,
   ULONG             ulCount
);

Parameters

pEventArray
Pointer to an array of SPEVENT event structures.
ulCount
Number of event structures being passed in.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pEventArray is bad or invalid
FAILED(hr) | Appropriate error message.


ISpEventSink::GetEventInterest (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpEventSink::GetEventInterest

ISpEventSink::GetEventInterest passes back the event interest for the voice.

HRESULT GetEventInterest(
   ULONGLONG   *pullEventInterest
);

Parameters

pullEventInterest
[out] Set of flags of type SPEVENTENUM defining the event interest.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Pointer bad or invalid.
FAILED(hr) | Appropriate error message.


ISpEventSource (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpEventSource

The ISpEventSource inherits from the ISpNotifySource interface. Using the methods on ISpNotifySource an application can specify the mechanism by which they receive notifications. Applications can configure which events should trigger notifications and which events retrieve queued events.

An ISpEventSource provides the mechanism to filter and queue events. By default, an application (really an ISpNotifySink) receives no notifications from the SpVoice object, until SetInterest has been called to specify on which events to notify or queue. For the SpRecoContext object, the default event interest is set to queue only recognition events.

When an application is notified of an event that is not queued, it will proceed based on which event sink receives the notification. From context, an application might know exactly what it needs to do, or it may need to interact with the components that sent the notifications. If an application is notified of a queued event, the application will call ISpEventSource::GetEvents to retrieve the actual events that caused a notification.

Implemented By
  • SpRecoContext
  • SpSharedRecoContext
  • SpVoice
  • SpMMAudioIn
  • SpMMAudioOut
  • SpRecPlayAudio
  • SpStreamFormatConverter

Methods in Vtable Order

ISpEventSource Methods | Description
ISpNotifySource inherited methods | All methods of ISpNotifySource are accessible from this interface
SetInterest | Sets the type of events the client is interested in.
GetEvents | Retrieves and removes the queued events.
GetInfo | Retrieves information about the event queue.


ISpEventSource::SetInterest (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpEventSource::SetInterest

ISpEventSource::SetInterest sets the type of events the client is interested in.

Sets the type of events which will invoke a notification and become queued.

HRESULT SetInterest(
   ULONGLONG   ullEventInterest,
   ULONGLONG   ullQueuedInterest
);

Parameters

ullEventInterest
[in] Event ID flags indicating which events should invoke a notification to the event sink that this event source uses. Must be of type SPEVENTENUM.
ullQueuedInterest
[in] Event ID flags indicating which events should be queued. The event flags set here must also be set in dwEventInterest. Must be of type SPEVENTENUM.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Invalid flags passed in one or more fields.
FAILED(hr) | Appropriate error message.

Remarks

If SetInterest is never called, the SR engine defaults to SPEI_RECOGNITION as the only event and queued interest. A TTS engine defaults to zero for both event and queued interest. With either engine, no events will be passed through if both parameters are set to zero.

Note that the SPFEI() macro will be used to convert an event enumeration into the appropriate flags to pass to this method. For example, to receive the SPEI_RECOGNITION and SPEI_HYPOTHESIS events, call this function as follows:

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpEventSource>    cpEventSource;
ULONGLONG                  ullMyEvents = SPFEI(SPEI_RECOGNITION) | SPFEI(SPEI_HYPOTHESIS);

// Set type of events the client is interested in.
hr = cpEventSource->SetInterest(ullMyEvents, ullMyEvents);

if (SUCCEEDED(hr))
{
   // Do stuff here.
}

Events specified in ullEventInterest must be a superset of those specified in the ullQueuedInterest. Therefore it is possible to have notifications of events but not actually queue them. This can be useful for polling the GetStatus method, especially for TTS.


ISpEventSource::GetEvents (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpEventSource::GetEvents

ISpEventSource::GetEvents retrieves and removes the queued events. Clients will want to use the helper class CSpEvent to retrieve and manipulate these events.

HRESULT GetEvents(
   ULONG     ulCount,
   SPEVENT  *pEventArray,
   ULONG    *pulFetched
);

Parameters

ulCount
[in] Maximum number of events that SPEVENT structures can return.
pEventArray
[out] Pointer to array of SPEVENT structures. Each returned event is written to one of these SPEVENT structures.
pulFetched
[out] Pointer to the number of events returned. If ulCount is one, this parameter is not required.

The events are then removed from the queue. The events not returned are left for a future call to GetEvents. It is possible that by the time an application calls GetEvents, another thread has processed the events and there are no events to be returned. This may be the result of subsequent Notify calls.

Return values

Value | Description
S_OK | Function completed successfully and all requested events were returned.
S_FALSE | Success, but less than the requested amount of events were returned.
E_POINTER | pEventArray is invalid.
FAILED(hr) | Appropriate error message.


ISpEventSource::GetInfo (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpEventSource::GetInfo

ISpEventSource::GetInfo retrieves information about the event queue.

HRESULT GetInfo(
  SPEVENTSOURCEINFO  *pInfo
);

Parameters

pInfo
[out] Pointer to an SPEVENTSOURCEINFO structure about the event.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pInfo is invalid.
FAILED(hr) | Appropriate error message.


ISpEventSource2 (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpEventSource2

New in SAPI 5.3

Extends the ISpEventSource interface by providing a function that retrieves extended event information.

Methods in Vtable Order

ISpEventSource2 Methods | Description
GetEventsEx | Exists to return the SPEVENTEX extended event information.


ISpEventSource2::GetEventsEx (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpEventSource2::GetEventsEx

ISpEventSource2::GetEventsEx exists to return the SPEVENTEX extended event information.

HRESULT GetEventsEx(
   ULONG         ulCount,
   SPEVENTEX    *pEventArray,
   ULONG        *pulFetched
);

Parameters

ulCount
[in] Maximum number of events that SPEVENTEX structures can return.
pEventArray
[out] Pointer to an array of SPEVENTEX structures. Each returned event is written to one of these SPEVENTEX structures.
pulFetched
[out] Pointer to the number of events returned. If ulCount is one, this parameter is not required.

The events are then removed from the queue. The events not returned are left for a future call to GetEventsEx. It is possible that by the time an application calls GetEventsEx, another thread has processed the events and there are no events to be returned. This may be the result of subsequent Notify calls.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | Success, but less than the requested amount of events were returned.
E_POINTER | pEventArray is invalid.
FAILED(hr) | Appropriate error message.


ISpNotifyCallback (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifyCallback

This is not a COM interface. This is a C++ virtual interface that can be implemented by a SAPI client application to receive notifications. Since it is not a COM interface, the application does not need to implement QueryInterface, AddRef, or Release. It is the responsibility of the client code to control the lifetime of an ISpNotifyCallback-style notification. To remove an installed notify callback, call ISpEventSource::SetNotifySink( NULL ). The final release of an object that supports ISpEventSource will automatically remove an installed notify callback.

The SAPI implementation uses a hidden window to call the client back on the same thread that was used to initialize the event source. Notification callbacks are the result of processing a window message. This means that when the notification mechanism is used:

  1. The NoitifyCallback method will always be called on the thread that initialized the event source or notify translator object.
  2. The thread must have a window message pump.

Methods in Vtable Order

ISpNotifySource Methods | Description
NotifyCallback | Client implemented method is called by an object that supports ISpEventSource when an event occurs.


ISpNotifyCallback::NotifyCallback (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpNotifyCallback::NotifyCallback

ISpNotifyCallback::NotifyCallback is implemented by the client of the SpEventSource object. When this method is called, the wParam and lParam parameters are set to the values specified by the client when it called ISpNotifySource::SetNotifyCallbackInterface. The client should examine the appropriate event source object for events.

HRESULT NotifyCallback(
   WPARAM   wParam,
   LPARAM   lParam
);

Parameters

wParam
[in] wParam parameter is specified by the client when it called the ISpEventSource::SetNotifyCallback interface.
lParam
[in] lParam parameter is specified by the client when it called the ISpEventSource::SetNotifyCallback interface.

Return values

Clients should return S_OK. Other values may be used for debugging purposes, but will be ignored by SpEventSource objects.


Grammar Compiler interfaces (Microsoft Speech Platform)

 Microsoft Speech Platform

Grammar Compiler Interfaces (API-level)

Many speech recognition applications are built on voice commands, or command and control (C&C). For example, users playing Solitaire using a graphical application, may want to add C&C. This enables the user to speak "new game" or "play the ace of spades" into their computer microphone instead of using menu options or keyboard accelerators. Microsoft Office XP has a C&C mode, which enables user to speak voice commands mapped to virtually every menu command and many parts of the user interface (e.g., "File New", "Tools Options", "Outlook Today", etc.).

Applications can use SAPI 5's C&C features to implement functionality similar to a voice-command enabled Solitaire, Office XP, and other innovative applications. The C&C features of SAPI 5 are implemented as context-free grammars (CFGs). A CFG is a structure that defines a specific set of words, and the combinations of these words that can be used. In basic terms, a CFG defines the sentences that are valid, and in SAPI 5, defines the sentences that are valid for recognition by a speech recognition (SR) engine.

The CFG format in SAPI 5 defines the structure of grammars and grammar rules using Extensible Markup Language (XML). The CFG/Grammar compiler transforms the XML tags defining the grammar elements into a binary format used by SAPI 5-compliant SR engines. This compiling process can be performed either before or during application run time.

SAPI 5 also enables applications to create CFG structures programmatically using the ISpGrammarBuilder interface, which is inherited by ISpRecoGrammar. The application can use the ISpGrammarBuilder API to dynamically update an already loaded SAPI 5 XML grammar, create an in-memory SAPI 5 grammar, and/or save an in-memory SAPI 5 grammar to a memory stream (e.g., for saving grammars to the hard disk).

The following section covers:

  • Text Grammar Format: SAPI 5-defined XML grammar format for defining a CFG with plain text.
  • ISpGrammarBuilder: SAPI 5 API for programmatically creating, editing, or saving in-memory and binary CFGs.

Applications that do not need to modify a grammar at run time, or applications that want to increase performance of their CFG-based application should load the compiled binary form statically (not dynamically). If loading the backend grammar compiler at application run time, note that SAPI must allow for modification and validation of complicated state/transition graphs.


Text grammar format (Microsoft Speech Platform)

 Microsoft Speech Platform

Text Grammar Format

The context-free grammar (CFG) format in SAPI 5 defines the structure of grammars and grammar rules using the Extensible Markup Language (XML) tagging language. The CFG compiler transforms the XML tags defining the grammar elements into a binary format used by speech engines. This compiling process can be performed either before or during application run time. Speech recognition engines use CFGs to constrain the user's words to words that it will recognize.

Text Grammar Format Section Topics:

Name | Description
Text Grammar Format Overview | Describes grammar terminology and basic structure.
Grammar Rules and State Graphs | Describes rule state graphs with examples.
Designing Grammar Rules | General and advanced guidelines for command & control grammars.
Grammar Format Tags | Describes the entire set of XML Grammar tags with examples.
Grammar Format Tags: Special Characters | Describes tags which use special characters.
SAPI Grammar Example: Solitaire | Sample XML grammar covering basic grammar structure.


Text grammar format overview (Microsoft Speech Platform)

 Microsoft Speech Platform

Text Grammar Format Overview

The Extensible Markup Language (XML) format inside a GRAMMAR XML element (block), is an "expert–only–readable" declaration of a grammar that a speech application uses to accomplish the following:

  • Improve recognition accuracy by restricting and indicating to an engine what words it should expect.
  • Improve maintainability of textual grammars, by providing constructs for reusable text components (internal and external rule references), phrase lists, and string and numeric identifiers.
  • Improve translation of recognized speech into application actions. This is made easier by providing "semantic tags," (property name, and value associations) to words/phrases declared inside the grammar.

A GRAMMAR XML element (block) appears in a XML source code file. The XML source is compiled into a binary grammar format and is the format used by SAPI during application run time.

The following section covers:

  • Extensible Markup Language (XML)
  • Attributes
  • Contents
  • Comments
  • How SAPI utilizes XML information
  • Frequently used definitions
  • Non–empty concatenated recognition contents

Extensible Markup Language

The textual grammar format is an application of the XML. Every XML element consists of a start tag (<SOME_TAG>) and an end tag (</SOME_TAG>) with a case-insensitive tag name and contents between these tags. The start tag and the end tag are the same if the element is empty. For example, the tag (<SOME_TAG/>). More information about XML and the XML specification is available at: http://www.w3.org/TR/REC-xml.

For example, all grammars contain the opening tag <GRAMMAR> as follows:

<GRAMMAR>

... grammar content

</GRAMMAR>

Note that the contents of the grammar is contained between an opening tag and a trailing, closing tag.

return to the top of this page Back to top

Attributes

Attributes of an XML element appear inside the start tag. Each attribute is in the form of a name followed by an equal sign followed by a string which must be surrounded by either single or double quotation marks. An attribute of a given name may only appear once in a start tag.

In summary, the literal string cannot contain either < or ', if the string is surrounded by single quotation marks. It may not contain ", if the string is surrounded by double quotation marks. Furthermore, use all ampersand (&) characters only in an entity reference such as &amp; and &gt;. When a literal string is parsed, the resulting replacement text will resolve all entity references such as &gt; into its corresponding text, such as >. In this specification, only the resulting replacement text needs to be defined for attribute value strings. More information about XML and the XML specification is available at: http://www.w3.org/TR/REC-xml.

For example, the grammar author can specify the language (id) of the grammar as follows.

<GRAMMAR LANGID="409">
... grammar content
</GRAMMAR>

The grammar element (<GRAMMAR>) has an attribute, called LANGID which must be a numeric value. The grammar author specifies the language attribute by placing the attribute inside the brackets of the opening tag, and enclosing the attribute value (e.g. 409) in quotation marks.

return to the top of this page Back to top

Contents

The contents of an element consists of text or subelements. Formal definitions of valid contents in this specification are provided as regular and "multi-set" expressions. The pseudo-element name "Text" indicates untagged text. With these definitions, the XML specification defines the exact file syntax details.

For example, the grammar author can place either text or sub-elements inside a phrase tag as follows.

<PHRASE>
   hello
</PHRASE>

<PHRASE>
   <OPT>world</OPT>
</PHRASE>

return to the top of this page Back to top

Comments

The SAPI 5 XML parser treats HTML comment tags as unknown XML tag elements. The engine should provide support for comments and other unknown XML elements.

It is recommended that grammar authors place comments in their XML files (e.g. mygrammar.xml), similar to commenting source code, since the XML parser will safely parse the comments without affecting the grammar itself. Similarly, there is increase in size of the binary form of the grammar (e.g. mygrammar.cfg) since the SAPI 5 grammar compiler strips out the comments.

An example of a comment in an XML grammar is as follows.

   <!-- the 'travel' rule is the main voice command for our app, so it active by default -->
   <RULE ID="RID_Travel" TOPLEVEL="ACTIVE">
      <PHRASE>travel from</PHRASE>

      <!-- include location grammar component, so we can change the location list at runtime -->
      <RULEREF REFID="RID_Location" PROPID="PID_FromDestination"/>
      <PHRASE>to</PHRASE>

      <!-- include location grammar component, so we can change the location list at runtime -->
      <RULEREF REFID="RID_Location" PROPID="PID_ToDestination"/>
   </RULE>

Note that the comment blocks always begin with <!-- and end with -->.

return to the top of this page Back to top

How SAPI utilizes XML information

SAPI uses XML content in the following two methods.

  1. The SAPI context-free grammar compiler, compiles the XML grammar into a binary grammar format. The compiled binary grammar is loaded into the SAPI run-time environment from a file, memory, or object (.DLL) resource.
  2. The speech recognition (SR) engine queries the run-time environment for available grammar information.

return to the top of this page Back to top

Frequently used definitions

Untagged text declaring a sequence of words that the recognition engine will recognize. Tentatively this text is only the not-necessarily-phonetic representation of words used for reading words whose pronunciation is unknown to the user (for example, for Japanese, kana, not kanji); this form will be called the spelling form. In further definitions in this section, Text will be referenced as though it were a pseudo-element.

return to the top of this page Back to top

Non–empty concatenated recognition contents

The contents of a number of XML elements in this specification such as, the P element, contain a sequence of grammar constructs which are concatenated together (one grammar construct after another). These grammar elements must be recognized in order for the contents defined to be recognized.

The contents must be one of the following (and not both):

Text and any number of L, P, O, or RULEREF elements in any order with at least one L, P, or RULEREF.

return to the top of this page Back to top


Grammar Rules and State Graphs (Microsoft Speech Platform)

 Microsoft Speech Platform

Grammar Rules and State Graphs

Grammar rules are elements that SAPI 5-compliant speech recognition (SR) engines use to restrict the possible word or sentence choices during the SR process. SR engines employ grammar rules to control the elements of sentence construction using the predetermined list of recognized word or phrase choices. This list of recognized words or phrase choices contained in the grammar rules forms the basis of the SR engine vocabulary.

The phrase or sentence uses each grammar rule element to determine the recognition path. For example, examine the phrase describing travel plans, "I would like to drive from Seattle to New York," and note that there are elements that determine the resulting information. In this example, a person is planning to drive to New York from Seattle. This is a very simple illustration of what could be a very complex problem. Determining the same travel plans without limiting the method, direction, and travel destination would result in an infinite number of travel options.

The resulting information can be determined by restricting the available choices for a given sentence. Using this method, the resulting information can be composed only from certain choices, thus eliminating the possibility of an infinite number of travel plan combinations.

 I would like to drive from Seattle to New York.
                  |      |     |     |     |
               [Method]  |     |     |     |
               /    \    |     |     |     |
            Fly   Drive  |     |     |     |
                         |     |     |     |
                  [Direction]  |     |     |
                    /     \    |     |     |
                  From    To   |     |     |
                               |     |     |
                            [City]   |     |
                           Seattle   |     |
                          New York   |     |
                       Los Angeles   |     |
                       Albuquerque   |     |
                                     |     |
                              [Direction]  |
                                 /    \    |
                                To   From  |
                                           |
                                        [City]
                                        Seattle
                                        New York
                                        Los Angeles
                                        Albuquerque

The elements of interest in the example phrase are as follows:

  • Method of travel (fly or drive), specifically "drive"
  • Travel direction (from or to), specifically "from"
  • The city of origin for the travel plan (from), specifically "Seattle"
  • Travel direction compliment (from or to), specifically "to"
  • The city of destination for the travel plan (to), specifically "New York"

The information can also be displayed as a graph of states and arcs, where each arc can have text (or semantic tags/properties) attached. The valid phrases are the unique paths through the graph, starting at the root and ending at a terminal state. Each state is denoted by the term (root node, interim node, and null) for the terminal node. The spoken text is denoted by words surrounded by quotation marks. The semantic property names are denoted by bold, block quoted words.

             (root node)
                  |
                  |"I would like to"
                  |
                  |
           (interim node)
                  /\
                 /  \
         "drive"/    \"fly" [METHOD]
                \    /
                 \  /
                  \/
           (interim node)
                  /\
           "from"/  \"to"   [DIRECTION]
                 \  /
                  \/
           (interim node)
                  /\
            _____/  \_____
           /   \       /  \
          /     \     /    \  [CITY_1]
         /       |   /      \
         |       |  |        \
"Seattle"|   "New|  |"Los     |"Albuquerque"
         |  York"|  |Angeles" |
         |       |  |         /
         |       |  |        /
          \      /  \       /
           \    /    \     /
            \___\     \___/
                 \    /
                  \  /
                   \/
           (interim node)
                   /\
            "from"/  \"to"   [DIRECTION]
                  \  /
                   \/
           (interim node)
                   /\
             _____/  \_____
            /   \       /  \
           /     \     /    \
          /       |   /      \
          |       |  |        \
 "Seattle"|   "New|  |"Los     |"Albuquerque"
          |  York"|  |Angeles" |
          |       |  |         /
          |       |  |        /  [CITY_2]
           \      /  \       /
            \    /    \     /
             \___\     \___/
                  \    /
                   \  /
                    \/
                  (NULL)

If the user speaks the following phrase:
I would like to travel from Seattle to New York.

Grammar rules become concatenated phrase elements. These phrase elements are limited to the defined set of grammars. Control can be significantly improved over the resulting information by restricting the input choice to a limited set of possibilities. Otherwise, obtaining the travel plan information from the same sample phrase, "I would like to travel from Seattle to New York," would be considerably more ambiguous.

The complexity of parsing the same sentence increases exponentially without using a defined set of choices. Imagine the possible number of combinations in a sentence that is not restricted to a finite list of combinations. For example, examine the possible choice combinations by moving the mouse over the following sentence.

To display the available choice selections in the example phrase, move the mouse over the underlined text below:

"I want to—(unknown travel method)—(unknown travel direction)—(unknown city)—(unknown travel direction) (unknown city)." The amount of predictable information is significantly reduced without the ability to constrain the available choices within a sentence.

The semantic structure (using name/value pairs) is:
[METHOD="drive"], [DIRECTION="from"], [CITY_1="Seattle"], [DIRECTION="to"], [CITY_2="New York"]

By parsing the semantic structure, the application can easily and accurately analyze the content of the original phrase, without parsing or analyzing individual words. The application developer can then write application logic to perform specific actions based on the previously mentioned semantic names, and specialize the action based on the values of each semantic property. The grammar author can add to or delete from the lists of words, without breaking the application logic.

Grammar rules apply to the following:

TOPLEVEL versus non-TOPLEVEL
A grammar tagged as TOPLEVEL can be in an active or inactive state. The rules that import a grammar can override the activation state of a rule. This conditional state can be configured dynamically at run time. If an inactive grammar is included in another grammar or grammar rule, ignore the inactive state. When a rule is activated, an SR engine will accept only speech satisfying at least one of the active rules contained in the loaded grammar. If a rule is not marked TOPLEVEL, then it is a component rule, and not directly accessible (i.e., the user can only speak TOPLEVEL rules for valid recognition).
Non-terminal
A grammar node is considered to be non-terminal if it is the beginning of a choice selection or a group of choice selections. For example, the grammar node Dog is non-terminal when the subsequent choice selections are types of dogs. This type of grammar node is defined as non-terminal because of its choice selections.
Terminal
A grammar node is considered to be terminal if it's the only word in the recognized vocabulary which can be spoken. Using the Dog example above, terminal grammar nodes are the type of dogs.
                      --------------------+
               Animal                     +--- Non-terminal node
                 |    --------------------+
                 |
              /--+--\          -----------+
  Cat--------/       \------Dog           +--- Non-terminal node
   |                       |   -----------+
   |                       |
   |                       |   -----------+
   +-- Burmese             +-- Airedale   |
   +-- Himalayan           +-- Poodle     +--- Terminal nodes
   +-- Persian             +-- Schnauzer  |
   +-- Siamese             +-- Whippet    |
                               -----------+

The text format grammar XML tags follow block scope methods that are similar to HTML tags. That is, each tag has an opening tag and a corresponding closing tag.

XML tag syntax | Contents
<sometag NAME="some_name" VAL="some_value"> | Start of "sometag" tag scope which includes the name and value information.
</sometag> | End of the "sometag" scope.

return to the top of this page Back to top


Designing grammar rules (Microsoft Speech Platform)

 Microsoft Speech Platform

Designing Grammar Rules

Speech applications often use context-free grammars (CFG) to parse the recognizer output and in some instances, to act as the recognizer's language model. Speech recognition engines use CFGs to constrain the user's words to words that it will recognize. If the CFG is augmented with semantic information (property names and property values as explained below), a SAPI component converts the recognized word string into a name/value-meaning representation. The application then uses the meaning representation to control its part of the conversation with the user.

The following section covers:

  • Semantic Properties or Tags
  • Separation of Dynamic and Static Content
  • Use Dynamic Rules for Language Flexibility
  • Retrieving Semantic Tags or Properties from Recognition Results
  • Using Semantic Properties, Hypotheses, and "Property Pushing"

Semantic properties or tags

For example, the phrase "Please schedule a meeting with Amy Anderson," could be annotated as follows:

Phrase element             Grammar element            Contents
-------------------------------------------------------------------------
"schedule a meeting"      "request: meeting"       // attribute and value
"with"                    "participants:"          // only attribute
"Amy Anderson"            "<e-mail alias>"          // value type

Defining the different grammar element components could result in the following:

Please schedule a meeting with Amy Anderson.
         |         |       |       |
         |         |       |       |
         |         |       |       |
     request: meeting      |       |
                           |       |
                   participants: AmyAnd

The example sentence "Please schedule a meeting with Amy Anderson," generates the following SAPI 5 grammar:

<RULE TOPLEVEL=ACTIVE>
        <P PROPNAME="request" VAL="meeting">schedule a meeting</P>
        <P>with</P>
        <L PROPNAME="participants">
            <P VAL="AmyAnd">Amy Anderson</P>
            <P VAL="tbremer">Ted Bremer</P>
            <P VAL="fralee">Frank Lee</P>
            <P VAL="crandall">Cynthia Randall</P>
            <P VAL="swhite">Suki White</P>
            <P VAL="kyoshida">Kim Yoshida</P>
        </L>
   </RULE>

The result of saying the example sentence "Please schedule a meeting with Amy Anderson," would be as follows:

request:meeting

participants:AmyAnd

return to the top of this page Back to top

Separation of dynamic and static content

Applications should separate dynamic rule content from static rule content to implement good grammar design and to improve initial SAPI grammar compiler performance. For example, using the above grammar that uses a list of names, the application could create a separate rule (isolated in its own grammar) that contained only the names. The list of names, based on an address book or past user data, can be updated at run time. The static grammar would then contain a rule reference (e.g., RULEREF) to the dynamic content. When the application starts up, it can quickly load the static content, without loading the SAPI grammar compiler, to prevent delay in the startup sequence. Then, the application could load the dynamic content, which requires SAPI to initialize the backend grammar compiler.

return to the top of this page Back to top

Use dynamic rules for language flexibility

Suppose an application needs to support a phrase such as "send new e-mail to NAME." The phrase "send new e-mail to" is static, and known by the application at design time, well before run time. The application could use the following static XML grammar to support these phrases.

<GRAMMAR LANGID="409"><!-- american english grammar -->
   <RULE NAME="E-MAIL" TOPLEVEL="INACTIVE"><!-- inactive by default, to prevent premature recognitions -->
      <PHRASE>send new e-mail to</P>
      <RULEREF NAME="ADDRESS_BOOK" PROPNAME="NAME"/><!-- add TRACK_PROP semantic property tag for easy information retrieval -->
   </RULE>
   <RULE NAME="ADDRESS_BOOK" DYNAMIC="TRUE">
      <PHRASE>placeholder</PHRASE><!-- we'll stick placeholder text here that we'll replace immediately at runtime -->
   </RULE>
</GRAMMAR>

The source code to manipulate the dynamic rule, "ADDRESS_BOOK" follows:

     HRESULT hr = S_OK;

    // create a new grammar object
    hr = cpRecoContext->CreateGrammar(GRAM_ID, &cpRecoGrammar);
    // Check hr

    // deactivate the grammar to prevent premature recognitions to an "under-construction" grammar
    hr = cpRecoGrammar->SetGrammarState(SPGS_DISABLED);
    // Check hr

    // load the email grammar dynamically, so changes can be made at runtime
    hr = cpRecoGrammar->LoadCmdFromFile(L"email.xml", SPLO_DYNAMIC);
    // Check hr

    SPSTATEHANDLE hRule;

    // first retrieve the dynamic rule ADDRESS_BOOK
    hr = cpRecoGrammar->GetRule(L"ADDRESS_BOOK", NULL, SPRAF_Dynamic, FALSE, &hRule);
    // Check hr

    // clear the placeholder text, and everything else in the dynamic ADDRESS_BOOK rule
    hr = cpRecoGrammar->ClearRule(hRule);
    // Check hr

    // add the real address book (e.g. "Frank Lee", "self", "SAPI beta", etc.).
    // Note that ISpRecoGrammar inherits from ISpGrammarBuilder,
    // so application gets the grammar compiler and ::AddWordTransition for free!

    hr = cpRecoGrammar->AddWordTransition(hRule, NULL, L"Frank Lee", NULL, SPWT_LEXICAL, 1, NULL);
    // Check hr
    hr = cpRecoGrammar->AddWordTransition(hRule, NULL, L"self", NULL, SPWT_LEXICAL, 1, NULL);
    // Check hr
    hr = cpRecoGrammar->AddWordTransition(hRule, NULL, L"SAPI beta", NULL, SPWT_LEXICAL, 1, NULL);
    // Check hr
    // ... add rest of address book

    // commit the grammar changes, which updates the grammar inside SAPI,
    //    and notifies the SR Engine about the rule change (i.e. "ADDRESS_BOOK"
    hr = cpRecoGrammar->Commit(NULL);
    // Check hr

    // activate the grammar since "construction" is finished,
    //    and ready for receiving recognitions
    hr = cpRecoGrammar->SetGrammarState(SPGS_ENABLED);
    // Check hr

return to the top of this page Back to top

Retrieving semantic tags or properties from recognition results

Note the XML grammar used a semantic property tag, NAME, in the static grammar. The property will enable the application to retrieve the dynamic phrase very easily at run time. Whenever recognition is received with rule name, "E-MAIL," search the property tree (see SPPHRASE.pProperties) for the property named "NAME." Then call ISpRecoResult::GetPhrase with (SPPHRASEPROPERTY)pNameProp.ulFirstElement and (SPPHRASEPROPERTY)pNameProp.ulFirstElement, and the application can retrieve the exact text that the user spoke into the dynamic rule (e.g., user says "send new e-mail to Frank Lee," and you retrieve "Frank Lee," user says "send new e-mail to self," and you retrieve "self," etc.).

    // activate the e-mail rule to begin receiving recognitions
    hr = cpRecoGrammar->SetRuleState(L"EMAIL", NULL, SPRS_ACTIVE);
    // Check hr

    PWCHAR pwszEmailName = NULL;

    // default event interest is recognition, so wait for recognition event
    // NOTE: this could be placed in a loop to process multiple recognitions
    hr = cpRecoContext->WaitForNotifyEvent(MY_REASONABLE_TIMEOUT);
    // Check hr

    // event notification fired
    if (S_OK == hr) {

     CSpEvent spEvent;
         // if event retrieved and it is a recognition
    if (S_OK == spEvent.GetFrom(cpRecoContext) && SPEI_RECOGNITION == spEvent.eEventId) {

             // get the recognition result
        CComPtr<ISpRecoResult> cpRecoResult = spEvent.RecoResult();

             if (cpRecoResult) {
                 SPPHRASE* pPhrase = NULL;

                 // get the phrase object from the recognition result
                 hr = cpRecoResult->GetPhrase(&pPhrase);
                 if (SUCCEEDED(hr) && pPhrase) {

                     // if "EMAIL" rule was recognized ...
                     if (0 == wcscmp(L"EMAIL", pPhrase->Rule.pszName) {

                         // ... ensure that first property is "NAME"
                         if (0 == wcscmp(L"NAME", pPhrase->pProperties->pszName)) {

                             // store the user's spoken "send-to" name
                             //    in a variable for later processing
                             hr = pPhrase->GetText(pPhrase->pProperties->ulFirstElement,
                                                   pPhrase->pProperties->ulCountOfElements,
                                                   FALSE,
                                                   &pwszEmailName,
                                                   NULL);
                             // Check hr

                          }
                     }
                     // free the phrase object
                     if (pPhrase) ::CoTaskMemFree(pPhrase);

                 }
             }
    }
   }

return to the top of this page Back to top

Using semantic properties, hypotheses, and "property pushing"

SAPI supports a feature called "semantic property pushing" which enables applications to detect the semantic property structure more accurately at recognition time. "Property pushing" is done by SAPI at compile time, whereby the compiler moves semantic properties to the last terminal node within a rule that remains unambiguous.

For example, the phrases "a b c d" and "a b e f g" both have prefixes of "a b". The compiler will automatically split the phrases into three separate phrases, "a b", "c d", and "e f g", where the first phrase is the common prefix to both recognizable phrases.

The purpose of this feature is to enable applications that place properties on the phrases to detect which branch is being hypothesized as soon as the first unambiguous (non-common) portion of the phrase is spoken. When the user speaks "a b" it is not clear if the user will say "a b c d" or "a b e f g". If the user then says "e", the application can obviously eliminate the "a b c d" option. If the grammar author attached properties to the end of both phrases, the semantic property would be returned as soon as the user spoke the first unambiguous portion of the text (e.g., "c" or "e").

Note that the compiler will report an error ("Ambiguous Semantic Property") if multiple properties are pushed to the same node and two phrases are not unique. For example, the following grammar will fail with "ambiguous semantic property" because both phrases are the same and the compiler cannot determine which property to assign to phrases.

    <RULE NAME="AmbiguousProperty" TOPLEVEL="ACTIVE">
        <L>
            <P PROPID="42">this is a test</P>
            <P PROPID="3">different sentence</P>
            <P PROPID="75">this is a test</P>
        </L>
    </RULE>

The first and third phrases are the same. Note that these results are by design and are meant to prevent creating grammars that have multiple phrases with conflicting semantic properties.

There are a number of scenarios where property pushing can be helpful for an application.

One possibility is an application that wants to detect failures more intelligently. When a false recognition occurs, the application can detect the last semantic property returned and display an error message relevant to the attempted voice command.

Another scenario might be that of high-performance applications that wish to increase responsiveness of the user interface when a long voice command is spoken. The application can wait for the first unambiguous semantic property to be received (using hypothesis) and then fire the response action without waiting for the voice command to complete. This has the added benefit of allowing users to speak partial voice commands (e.g., instead of "go to website w w w Microsoft com" the user can say the slightly shorter "go to website w w w Microsoft"). The drawback is that the application must guard against performing critical, unrecoverable actions before completing the phrase (e.g., "delete hard drive" might fire after only "delete" if there are no other "delete" commands). Careful application design should enable the application to appear quicker and easier to use, without sacrificing robustness. By performing user studies, the application designer can decide which commands are capable of short circuiting and which are more critical.

return to the top of this page Back to top


Grammar Format Tags (Microsoft Speech Platform)

 Microsoft Speech Platform

Grammar Format Tags

The SAPI text grammar format is composed of XML tags, which can be structured to define the phrases that the speech recognition engine recognizes. The following document explains each tag in more detail, including sample source code, sample XML grammar snippets, and relevant application scenarios.

The XML tags descriptions are organized by XML element, where each element description contains information for relevant attributes.

XML Tags: Elements

<DEFINE>
    Summary: The DEFINE tag is used for declaring a set of string identifiers for numeric values.
    XML Attributes:
    None
    XML Parent Elements:
    GRAMMAR: The container for the entire XML grammar.
    XML Child Elements:
    ID (1 or more required): The DEFINE tag can contain one or more ID tags, each
            of which defines one string identifier.
    Detailed Description:
    None
    XML Grammar Sample(s):
    <GRAMMAR>
        <DEFINE>
            <ID NAME="TheNumberFive" VAL="5"/>
        </DEFINE>

        <!-- Note that the ID takes a number, which is actually "5" -->
        <RULE ID="TheNumberFive" TOPLEVEL="ACTIVE">
            <P>five</P>
        </RULE>
    </GRAMMAR>
    Programmatic Equivalent:
    See the ID tag.

    return to the top of this page Back to top

<DICTATION>
    Summary: The DICTATION tag is used in rules or phrases that need basic dictation support.
    XML Attributes:
    MAX (optional, type=VT_I4, default=MIN): Specifies the maximum number of dictation
        words that can be recognized.
        The application must specify a MAX value that is greater than or equal to
            the MIN value. The application can specify a pseudo-infinite maximum
            by specifying INF as the MAX. The pseudo-infinite is actually 255
            dictation words.
        An application that needs free-form dictation, such as the subject line of
            an email should use a large MAX. Alternatively, an application that
            needs to recognize a person's name may want a much smaller value,
            such as 5 words.
    MIN (optional, type=VT_I4, default=1): Specifies the minimum number of dictation
            words that must be recognized.
        If the grammar author specifies the MIN value, and the recognizer does not
            meet the minimum, the rule will fail to be recognized.
        A Scenario where it may make sense to set a value greater than one would be
            an application that is asking for a first and last name.
    PROPID (optional, type=VT_I4): Specifies the semantic property's numeric identifier.
    PROPNAME (optional): Specifies the semantic property's string identifier.
    XML Parent Elements:
    LIST, L: List of phrases which can be recognized.
    PHRASE, P: Phrase that must be recognized for the containing rule to be recognized.
    OPT, O: Optional phrase that may be recognized.
    RULE: Rule that contains phrases or text to be recognized.
    XML Element Children:
    None.
    Detailed Description:
    The DICTATION tag is designed for applications that need to integrate command &
        control and dictation support into a CFG. For example, an application may
        allow the user to speak free-form dictation into a command (e.g. "save document
        as our family's budget" where "our family's budget is free-form dictation).
    The application may also create a CFG which supports a set of specific phrases or words,
        and also includes a single DICTATION tag in case of an unexpected user-phrase.
        For example, a CFG may include a set of address book names which are known, and
        if the user speaks another name, then the application prompts the user for
        validation of the dictated result. Note that the SR engine's accuracy may
        suffer by mixing dictation and CFG phrases together, since many words sound
        similar, and a CFG is generally preferred for application development with known
        words.
    The grammar author can also use a special character, asterisk (*) instead of the entire
        XML tag. See XML Grammar Format: Special Dictation Tag.
    By using semantic properties, the application can easily retrieve the exact text that
        was dictated by the speaker. To specify a semantic property for the DICTATION tag
        the grammar author should specify the PROPID and/or PROPNAME attributes. The
        SAPI run time will automatically set the semantic tag's starting phrase element,
        allowing the application to search for the specific semantic property in the
        properties hierarchy (see SPPHRASEPROPERTY.ulFirstElement). If multiple dictation
        words are recognized by the SR engine (e.g. DICTATION MAX > 1),	then the SAPI
        run time will generate multiple semantic properties, one for each word, where
        all of the properties will have the same numeric ID and/or string NAME.
    If the speech recognition engine supports multiple dictation topics (e.g. spelling,
        general, legal, medical, etc.), the DICTATION tag in the grammar will refer to
        topic that was selected when ISpRecoGrammar::LoadDictation was called. If the
        topic was not explicitly selected, then the default SR engine dictation topic
        will be loaded. Currently, it is not possible to load multiple dictation topics
        inside of a single command & control grammars. Application should create multiple
        grammar objects to implement the latter scenario.
    If there is ambiguity between a dictation phrase and a CFG phrase, the speech
        recognition engine will typically choose the CFG phrase. Preferring CFGs over
        dictation prevents dictation from automatically consuming all CFG phrases.
    The speech recognition engine must support dictation inside of a CFG for the grammar
        to load and activate successfully. The application can determine if an engine
        supports the DICTATION tag by retrieving the SR engine's object token (see
        ISpRecognizer::GetRecognizer), and then checking for the existence of the
        engine attribute "DictationInCFG" (see ISpObjectToken::MatchesAttributes).
        The engine can specify support for the DICTATION tag to be anywhere in the
        CFG phrase (attribute value="Anywhere"), or only at the end (attribute
        value="Trailing").
    XML Grammar Sample(s):
    <GRAMMAR>
        <!-- basic command to create a self-note for the user with free-form text -->
        <RULE ID="SelfNote" TOPLEVEL="ACTIVE">
            <P>note to self</P>
            <DICTATION MAX="INF"/>
        </RULE>

        <!-- command to query a name from an address book -->
        <RULE ID="QueryName" TOPLEVEL="ACTIVE">
            <P>list first names of all persons with last name</P>
            <!-- Store only one word for the last name, more will fail command -->
            <DICTATION MAX="1">
        </RULE>

        <!-- command to handle first and last names with semantic properties -->
        <!-- By using semantic properties, the application can ignore all of
            the text returned, except for the text associated with the dictation
            tags' semantic properties "PID_FirstName" and "PID_LastName" -->
        <RULE ID="SubmitName" TOPLEVEL="ACTIVE">
            <P>
                my first name is
                <!-- Note the implicit maximum is only one word -->
                <DICTATION PROPID="PID_FirstName"/>
                and my last name is
                <!-- Note the implicit maximum is two words -->
                <DICTATION PROPID="PID_LastName" MAX="2"/>
            </P>
        </RULE>
    </GRAMMAR>
    Programmatic Equivalent:
    To programmatically create a dictation transition (i.e. DICTATION tag) in a CFG, the application developer
        can use the ISpGrammarBuilder::AddRuleTransition with a special rule handle,
        called SPRULETRANS_DICTATION. For example, the following code creates a simple
        command called "SendMail" which recognizes the command "send mail to DICTATION".
                SPSTATEHANDLE hsSendMail;
            // Create new top-level rule called "SendMail"
            hr = cpRecoGrammar->GetRule(L"SendMail", NULL,
                            SPRAF_TopLevel | SPRAF_Active, TRUE,
                            &hsSendMail);
            // Check hr

            // Create an interim state before the dictation transition
            SPSTATEHANDLE hsBeforeDictation;
            hr = cpRecoGrammar->CreateNewState(hsSendMail, &hsBeforeDictation);
            // Check hr

            // Add the command words "send mail to"
            hr = cpRecoGrammar->AddWordTransition(hsSendMail, hsBeforeDictation,
                    L"send mail to", L" ", SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // Add trailing dictation transition
            hr = cpRecoGrammar->AddRuleTransition(hsBeforeDictation, NULL,
                                SPRULETRANS_DICTATION, NULL, NULL);
            // Check hr

            // save/commit changes
            hr = cpRecoGrammar->Commit(NULL);
            // Check hr
        Note that the previous sample code only supports one dictation word. To support
        more than one word, the code would need to build more dictation transition
        states, each of which begins at the previous dictation state - effectively,
        a series of consecutive single-word dictation transitions.

    return to the top of this page Back to top

<GRAMMAR>
    Summary: The GRAMMAR tag is the outermost container for the XML grammar definition.
    XML Attributes:
    LANGID (optional, type=numeric): The language identifier of the grammar.
        The identifier will be compared against the
            the supported languages of the Speech Recognition engine. If the language is
            not supported, the grammar load call will fail (e.g. ISpRecoGrammar::LoadCmdFromFile).
        It is recommended that all XML grammars include the LANGID attribute to avoid the scenario
            where the SR engine tries to load a grammar with an unspecified language ID, and fails due
                    to confusing words.
                SAPI supports fuzzy language ID matching, in that the SR engine can
                    report that is supports the major portion of the Language ID (e.g. 0x009 in 0x409),
                    which means the SR engine will try to load and recognize any grammar that matches the
                    major portion of the language ID.
    LEXDELIMITER (optional): The LEXDELIMITER attribute specifies the delimiter for explicit
            lexicon entries specified in the grammar.
        Grammar authors are able to specify the lexicon information by using a special
            sequence of characters. The sequence of characters is:
            LEXDELIMITERDisplayFormLEXDELIMITERLexicalFormLEXDELIMITERPronunciation;
        The default delimiter is the backslash character "/".
        See also PHRASE.
    WORDTYPE (optional): The WORDTYPE attribute specifies the type of the word(s) when they are added to the
                    grammar.
        The default value is "LEXICAL".
        The value must be "LEXICAL".
    XML Parent Elements:
    None
    XML Child Elements:
    DEFINE (optional): Specifies the constant definitions for the grammar.
    RULE (1 or more required): Specifies the rules, including top-level and non-top-level.
    Detailed Description:
    Every XML grammar must have the container tag, GRAMMAR.
    XML Grammar Sample(s):
    <!-- Language ID = British English -->
    <GRAMMAR LANGID="413" LEXDELIMITER="|" WORDTYPE="LEXICAL">
        <RULE NAME="HelloWorld" TOPLEVEL="ACTIVE">
                        <!-- when the user says the following pronunciation, "Hiya" will be displayed -->
            <P>|Hiya|Hello|h eh l ow;</P>
        </RULE>
    </GRAMMAR>
    Programmatic Equivalent:
    To programmatically set the language ID of a new grammar, the application developer should
             call ISpGrammarBuilder::ResetGrammar.
    The application developer does not need to change the LEXDELIMITER or the WORDTYPE, since the ISpLexicon
         interface can be used to modify the lexicon.

    return to the top of this page Back to top

<ID>
    Summary: The ID tag is used for declaring a string identifier for numeric
values.
    XML Attributes:
    NAME (required): The NAME attribute defines the string identifier that will be associated
                             with the constant value.
    VAL (required, type=VT_UI4,VT_I4,VT_R4,VT_R8): The VAL attribute defines the constant
                value that will be associated with the string identifier.
    XML Parent Elements:
    DEFINE: The container for the constant definitions.
    XML Child Elements:
    None
    Detailed Description:
    The ID tag should be used by grammar author to make the grammar easier to read and
             maintain. The grammar author can use string identifiers which succinctly explain
             the use of the identifier (e.g. RID_FileNew, PVAL_MAIN_WINDOW, etc.). The grammar
             compiler stores the identifiers in the binary format, and string identifiers are
             typically much larger than numeric identifiers. Also, the application developer
             can use a simple numeric comparison to handle rule and semantic property logic,
             rather than performing a more complex string comparison.
    XML Grammar Sample(s):
        <GRAMMAR>
        <DEFINE>
            <ID NAME="RuleId_A" VAL="1"/>
            <ID NAME="PropId_B" VAL="2"/>
            <ID NAME="PropVal_AB" VAL="3"/>
        </DEFINE>

        <!-- Note that Rule ID, Phrase PROPID and VAL take a numeric values. -->
        <RULE ID="RuleId_A" TOPLEVEL="ACTIVE">
            <P PROPID="PropId_B" VAL="PropVal_AB">five</P>
        </RULE>
    </GRAMMAR>
    Programmatic Equivalent:
    The Grammar Compiler that ships in the Microsoft Speech SDK includes a command line
              argument to generate a C-style header (see "-h"), which includes the programmatic
              constant definitions for all of the IDs defined in the XML grammar. The application
              developer can include the header file and easily use the same identifiers inside
              the application logic, without needing to redefine and maintain the numeric values.
    The XML Grammar Sample above would create the following C-style header file:
        #define RuleId_A 1
        #define PropId_B 2
        #define PropVal_AB 3

    return to the top of this page Back to top

<LIST>, <L>
    Summary: The LIST tag is used for specifying a list of phrases or transitions.
    XML Attributes:
    PROPID (optional, type=VT_I4): The numeric identifier that will be inherited by all
            semantic properties in the child elements (e.g. phrases).
    PROPNAME (optional): The string identifier that will be inherited by all semantic
            properties in the child elements (e.g. phrases).
    XML Parent Elements:
    LIST, L: List of phrases or rules which can be recognized.
    PHRASE, P: Phrase that must be recognized for the containing rule to be recognized.
    OPT, O: Optional phrase causing the rule reference to be implicitly optional.
    RULE: Rule that contains phrases or text to be recognized.
    XML Child Elements:
    RULEREF: Import, or reference, another rules contents
    PHRASE, P: Specifies text or leaf nodes.
    LIST, L: Specifies a list of phrases or transitions for recognition.
    TEXTBUFFER: Specifies a reference to the run-time application maintained
        text-buffer.
    WILDCARD: Specifies a garbage word; one or more non-silence, ignorable words
    DICTATION: Specifies a piece of text recognized by the loaded dictation topic.
    Detailed Description:
    The LIST tag is a quick and efficient way to support lists of phrases or text. Instead
        of creating separate rules for each piece of text, the LIST tag can be used
        where its children are the phrase, rule reference, or other tags.
    The grammar author can use the shorthand version of the LIST tag, the L tag.
    The LIST tag is more of a virtual tag, since it does not affect the semantic property
        hierarchy (LIST children are not child properties). While it allows the grammar
        author to specify a string or numeric identifier, the identifier is only used
        to pass on to the child element as a default property identifier.
    XML Grammar Sample(s):
    <GRAMMAR>
        <!-- Note that rule is not top-level and is only used as a reusable component rule -->
        <RULE NAME="Numbers">
            <!-- The list tag includes a semantic property Id, "PID_Value" which
                is inherited by all child phrase elements -->
            <LIST PROPID="PID_Value">
                <!-- If the user says "one" then the semantic property returned will
                    be the name/value pair "PID_Value"/"1" -->
                <P VAL="1">one</P>
                <P VAL="2">two</P>
                <P VAL="3">three</P>
                <P VAL="4">four</P>
                <P VAL="5">five</P>
            </LIST>
        </RULE>

        <!-- The rule contains a list of various types of transitions -->
        <RULE NAME="Sampler" TOPLEVEL="ACTIVE">
            <!-- the list property specifies a default property name of "TYPE_NUMBER",
                which will overridden by specific list children -->
            <LIST PROPNAME="TYPE_NUMBER">
                <P VAL="1">one</P>
                <P VAL="2">two</P>
                <P VAL="3">three</P>
                <P PROPNAME="TYPE_STRING" VALSTR="FOUR">four</P>
                <P PROPNAME="TYPE_NONE">five</P>
                <RULEREF NAME="Numbers" PROPNAME="TYPE_RULEREF"/>
                <TEXTBUFFER PROPNAME="TYPE_TEXTBUFFER"/>
                <DICTATION PROPNAME="TYPE_DICTATION"/>
            </LIST>
        </RULE>
    </GRAMMAR>
    Programmatic Equivalent:
    To programmatically create a list, or a set of sibling/parallel transitions, the application
        needs to create a start state, then create multiple transitions out of the state. For
        example, the following sample code shows how to make a list of phrases (e.g. "one",
        "two", "three").

            SPSTATEHANDLE hsList;
            // Create new top-level rule called "List"
            hr = cpRecoGrammar->GetRule(L"List", NULL,
                            SPRAF_TopLevel | SPRAF_Active, TRUE,
                            &hsList);
            // Check hr

            // Add the word "one" to the list
            hr = cpRecoGrammar->AddWordTransition(hsList, NULL,
                    L"one", L" ",
                    SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // Add the word "two" to the list
            hr = cpRecoGrammar->AddWordTransition(hsList, NULL,
                    L"two", L" ",
                    SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // Add the word "three" to the list
            hr = cpRecoGrammar->AddWordTransition(hsList, NULL,
                    L"three", L" ",
                    SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // save/commit changes
            hr = cpRecoGrammar->Commit(NULL);
            // Check hr

        The application developer can use similar code to create a list of rule references,
            dictation, or text buffer transitions. To change the type of list item, change
            the ::AddWordTransition call to ::AddRuleTransition.

    return to the top of this page Back to top

<OPT>, <O>
    Summary: The OPT tag is used for specifying optional text in a command phrase.
    XML Attributes:
    DISP (optional): Specifies the display form of the phrase text.
    MAX (optional, type=VT_I4, default=MIN): Specifies the maximum number of times the user
        can repeat the phrase and still be successfully recognized.
    MIN (optional, type=VT_I4, default=1): Specifies the minimum number of times the user
        must repeat the phrase and still be successfully recognized.
    PRON (optional): Specifies the pronunciation to be used by the recognizer when listening
        for the text.
    PROPID (optional, type=VT_I4): Specifies the numeric identifier to associate with the phrase
        tag's semantic property.
    PROPNAME (optional): Specifies the string identifier to associate with the phrase tag's
        semantic property.
    VAL (optional, type=VT_I4): Specifies the semantic property's numeric value.
    VALSTR (optional): Specifies the semantic property's string value.
    WEIGHT (type=VT_UI4,VT_I4,VT_R4,VT_R8, default=1/n_sibling_transitions): The probability
            that the user will speak the contents of the PHRASE tag, versus another
            sibling transition or phrase.
    XML Parent Elements:
    RULEREF: Import, or reference, another rules contents
    PHRASE, P: Specifies text or leaf nodes.
    OPT, O: Optional phrase causing the rule reference to be implicitly optional.
    LIST, L: Specifies a list of phrases or transitions for recognition.
    TEXTBUFFER: Specifies a reference to the run-time application maintained
        text-buffer.
    WILDCARD: Specifies a garbage word; one or more non-silence, ignorable words
    DICTATION: Specifies a piece of text recognized by the loaded dictation topic.
    XML Child Elements:
    RULEREF: Import, or reference, another rules contents
    PHRASE, P: Specifies text or leaf nodes.
    OPT, O: Optional phrase causing the rule reference to be implicitly optional.
    LIST, L: Specifies a list of phrases or transitions for recognition.
    TEXTBUFFER: Specifies a reference to the run-time application maintained
        text-buffer.
    WILDCARD: Specifies a garbage word; one or more non-silence, ignorable words
    DICTATION: Specifies a piece of text recognized by the loaded dictation topic.
    Detailed Description:
    The OPT tag along with the OPT tag are the only tags that can directly
        contain recognizable text.
    The grammar author can use the shorthand version of the OPT tag, the O tag.
    The grammar author can also specify custom word pronunciations and display
        text by using the PRON and DISP attributes. For example, a grammar
        might contain application or domain specific text, which has a custom
        pronunciation. The author can specify the pronunciation on a specific
        OPT tag to avoid the need for updating the user or application
        lexicon (especially if the pronunciation is command specific).
    The grammar author can also use special shorthand characters inside of the
        content section of the PHRASE tag (e.g. dictation, wildcard, etc.). See
        the XML Special Characters.
    XML Grammar Sample(s):
    <GRAMMAR>
        <!-- Create a simple "hello world" rule -->
        <!-- the second word is optional -->
        <RULE NAME="HelloWorld" TOPLEVEL="ACTIVE">
            <P>hello</P>
            <OPT>world</OPT>
        </RULE>

        <!-- Create a rule that changes the pronunciation and the display
            form of the phrase. When the user says "eh" the display
            text will be "I don't understand?". Note the user didn't
            say "huh". The pronunciation for "what" is specific to this
            phrase tag and is not changed for the user or application
            lexicon, or even other instances of "what" in the grammar -->
        <RULE NAME="Question_Pron" TOPLEVEL="ACTIVE">
            <P DISP="I don't understand" PRON="eh">what</P>
        </RULE>

        <!-- Create a phrase with an attached semantic property -->
        <!-- Speaking "one two three" will return three different unique
            semantic properties, with different names, and different
            values -->
        <!-- Speaking "one three" will return two different unique
            semantic properties, with different names, and different
            values -->
        <!-- Speaking "one two" will return two different unique
            semantic properties, with different names, and different
            values -->
        <!-- Speaking "one" will return two different unique
            semantic properties, with different names, and different
            values -->
        <!-- Note that the number of semantic properties returned is
            variable, and that the application should be designed to
            handle all of the variations -->
        <RULE NAME="UseProps" TOPLEVEL="ACTIVE">
            <!-- named property, without value -->
            <P PROPNAME="NOVALUE">one</P>

            <!-- named property, with numeric value -->
            <O PROPNAME="NUMBER" VAL="2">two</O>

            <!-- named property, with string value -->
            <O PROPNAME="STRING" VALSTR="three">three</O>
        </RULE>

        <!-- Create a rule for optional command prefix -->
        <!-- Note that entire rule reference is optional. In cases where
            there are properties associated with the rule reference, the
            semantic property tree may change -->
        <!-- the rule supports the phrases "play cards", "please play cards", and
            "please play cards" -->
        <RULE NAME="PlayCard" TOPLEVEL="ACTIVE">
            <O><RULEREF NAME="PLEASE"/></O>
            <P>play cards</P>
        </RULE>

        <!-- The first word "pretty" is optional, while the second is required -->
        <RULE NAME="PLEASE">
            <O>pretty</O>
            <P>please</P>
        </RULE>
    </GRAMMAR>
    Programmatic Equivalent:
    To add an optional phrase to a rule, SAPI provides an API called
        ISpGrammarBuilder::AddWordTransition. The application developer can add
        the optional structure as follows:

            SPSTATEHANDLE hsHelloWorld;
            // Create new top-level rule called "HelloWorld"
            hr = cpRecoGrammar->GetRule(L"HelloWorld", NULL,
                            SPRAF_TopLevel | SPRAF_Active, TRUE,
                            &hsHelloWorld);
            // Check hr

            // create an interim state
            SPSTATEHANDLE hInterim;
            hr = cpRecoGrammar->CreateNewState(hsHelloWorld, &hInterim);
            // Check hr

            // Add the command word "hello" which terminates at the interim
            //	state
            hr = cpRecoGrammar->AddWordTransition(hsHelloWorld, hInterim,
                    L"hello", NULL,
                    SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // Add the optional command word "world"
            hr = cpRecoGrammar->AddWordTransition(hInterim, NULL,
                    L"hello", NULL,
                    SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // Add the epsilon transition, which means no word need be spoken
            hr = cpRecoGrammar->AddWordTransition(hInterim, NULL,
                    NULL, NULL,
                    SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // save/commit changes
            hr = cpRecoGrammar->Commit(NULL);
            // Check hr

    return to the top of this page Back to top

<PHRASE>, <P>
    Summary: The PHRASE tag and the OPT tags are the sole methods of explicitly specifying text to be
        recognized by the speech recognition engine.
    XML Attributes:
    DISP (optional): Specifies the display form of the phrase text.
    MAX (optional, type=VT_I4, default=MIN): Specifies the maximum number of times the user
        can repeat the phrase and still be successfully recognized.
    MIN (optional, type=VT_I4, default=1): Specifies the minimum number of times the user
        must repeat the phrase and still be successfully recognized.
    PRON (optional): Specifies the pronunciation to be used by the recognizer when listening
        for the text.
    PROPID (optional, type=VT_I4): Specifies the numeric identifier to associate with the phrase
        tag's semantic property.
    PROPNAME (optional): Specifies the string identifier to associate with the phrase tag's
        semantic property.
    VAL (optional, type=VT_I4): Specifies the semantic property's numeric value.
    VALSTR (optional): Specifies the semantic property's string value.
    WEIGHT (type=VT_UI4,VT_I4,VT_R4,VT_R8, default=1/n_sibling_transitions): The probability
            that the user will speak the contents of the PHRASE tag, versus another
            sibling transition or phrase.
    XML Parent Elements:
    RULEREF: Import, or reference, another rules contents
    PHRASE, P: Specifies text or leaf nodes.
    OPT, O: Optional phrase causing the rule reference to be implicitly optional.
    LIST, L: Specifies a list of phrases or transitions for recognition.
    TEXTBUFFER: Specifies a reference to the run-time application maintained
        text-buffer.
    WILDCARD: Specifies a garbage word; one or more non-silence, ignorable words
    DICTATION: Specifies a piece of text recognized by the loaded dictation topic.
    XML Child Elements:
    RULEREF: Import, or reference, another rules contents
    PHRASE, P: Specifies text or leaf nodes.
    OPT, O: Optional phrase causing the rule reference to be implicitly optional.
    LIST, L: Specifies a list of phrases or transitions for recognition.
    TEXTBUFFER: Specifies a reference to the run-time application maintained
        text-buffer.
    WILDCARD: Specifies a garbage word; one or more non-silence, ignorable words
    DICTATION: Specifies a piece of text recognized by the loaded dictation topic.
    Detailed Description:
    The PHRASE tag along with the OPT tag are the only tags that can directly
        contain recognizable text. Except for grammars that contain rule
        references, every grammar must have at least one PHRASE tag.
    The grammar author can use the shorthand version of the PHRASE tag, the P tag.
    The grammar author can also specify custom word pronunciations and display
        text by using the PRON and DISP attributes. For example, a grammar
        might contain application or domain specific text, which has a custom
        pronunciation. The author can specify the pronunciation on a specific
        PHRASE tag to avoid the need for updating the user or application
        lexicon (especially if the pronunciation is command specific).
    The grammar author can also use special shorthand characters inside of the
        content section of the PHRASE tag (e.g. dictation, wildcard, etc.). See
        the XML Special Characters.
    XML Grammar Sample(s):
    <GRAMMAR>
        <!-- Create a simple "hello world" rule -->
        <RULE NAME="HelloWorld" TOPLEVEL="ACTIVE">
            <P>hello world</P>
        </RULE>

        <!-- Create a more advanced "hello world" rule that changes the
            display form. When the user says "hello world" the display
            text will be "Hiya there!" -->
        <RULE NAME="HelloWorld_Disp" TOPLEVEL="ACTIVE">
            <P DISP="Hiya there!">hello world</P>
        </RULE>

        <!-- Create a rule that changes the pronunciation and the display
            form of the phrase. When the user says "eh" the display
            text will be "I don't understand?". Note the user didn't
            say "huh". The pronunciation for "what" is specific to this
            phrase tag and is not changed for the user or application
            lexicon, or even other instances of "what" in the grammar -->
        <RULE NAME="Question_Pron" TOPLEVEL="ACTIVE">
            <P DISP="I don't understand" PRON="eh">what</P>
        </RULE>

        <!-- Create a rule demonstrating repetition -->
        <!-- the rule will only be recognized if the user says "hey diddle
            diddle" -->
        <RULE NAME="NurseryRhyme" TOPLEVEL="ACTIVE">
            <P>hey</P>
            <P MIN="2" MAX="2">diddle</P>
        </RULE>

        <!-- Create a list with variable phrase weights -->
        <!-- If the user says similar phrases, the recognizer will use
            the weights to pick a match -->
        <RULE NAME="UseWeights" TOPLEVEL="ACTIVE">
            <LIST>
                <!-- Note the higher likelihood that the user is
                    expected to say "recognizer speech" -->
                <P WEIGHT=".95">recognize speech</P>
                <P WEIGHT=".05">wreck a nice beach</P>
            </LIST>
        </RULE>

        <!-- Create a phrase with an attached semantic property -->
        <!-- Speaking "one two three" will return three different unique
            semantic properties, with different names, and different
            values -->
        <RULE NAME="UseProps" TOPLEVEL="ACTIVE">
            <!-- named property, without value -->
            <P PROPNAME="NOVALUE">one</P>

            <!-- named property, with numeric value -->
            <P PROPNAME="NUMBER" VAL="2">two</P>

            <!-- named property, with string value -->
            <P PROPNAME="STRING" VALSTR="three">three</P>
        </RULE>
    </GRAMMAR>
    Programmatic Equivalent:
    To add a phrase to a rule, SAPI provides an API called
        ISpGrammarBuilder::AddWordTransition. The application developer can add
        the sentences as follows:

            SPSTATEHANDLE hsHelloWorld;
            // Create new top-level rule called "HelloWorld"
            hr = cpRecoGrammar->GetRule(L"HelloWorld", NULL,
                            SPRAF_TopLevel | SPRAF_Active, TRUE,
                            &hsHelloWorld);
            // Check hr

            // Add the command words "hello world"
            // Note that the lexical delimiter is " ", a space character.
            //	By using a space delimiter, the entire phrase can be added
            // 	in one method call
            hr = cpRecoGrammar->AddWordTransition(hsHelloWorld, NULL,
                    L"hello world", L" ",
                    SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // Add the command words "hiya there"
            // Note that the lexical delimiter is "|", a pipe character.
            //	By using a pipe delimiter, the entire phrase can be added
            // 	in one method call
            hr = cpRecoGrammar->AddWordTransition(hsHelloWorld, NULL,
                    L"hiya|there", L"|",
                    SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // save/commit changes
            hr = cpRecoGrammar->Commit(NULL);
            // Check hr

    return to the top of this page Back to top

<RESOURCE>
    Summary: The RESOURCE tag is used by grammar authors who want to store arbitrary string
    data on rules (e.g. for use by a CFG, or an SR engine aware of the
    the resources).
    XML Attributes:
    NAME: specifies the name of the resource to attach to the rule.
    XML Parent Elements:
    RULE: The rule that contains the resource reference.
    XML Child Elements:
    [CDATA] (required): The resource value is specified by a CDATA section.
    For example,
        <![CDATA[This is a test string]]>
    The RESOURCE tag contains the CDATA element, which itself contains the string.
    Detailed Description:
    The RESOURCE tag is a facility allowing the grammar author to communicate
        information [attached to rules] to a CFG Interpreter or a
        speech recognition engine that is aware of the resource information.
    XML Grammar Sample(s):
    <GRAMMAR>
        <!-- Note resource value can be any string -->
        <RULE ID="RID_TestResource" TOPLEVEL="ACTIVE">
            <RESOURCE NAME="AResource">
                <![CDATA[AResource's Value: String]]>
            </RESOURCE>
            <P>test an embedded resource</P>
        </RULE>
    </GRAMMAR>
    Programmatic Equivalent:
    To add a resource to a rule, SAPI provides an API called
        ISpGrammarBuilder::AddResource. The application developer can add
        the aforementioned resource (see XML Grammar Sample) with the following
        code:

            SPSTATEHANDLE hsTestResource;
            // Create new top-level rule called "TestResource"
            hr = cpRecoGrammar->GetRule(NULL, RID_TestResource,
                            SPRAF_TopLevel | SPRAF_Active, TRUE,
                            &hsTestResource);
            // Check hr

            // Add the command words "test an embedded resource"
            hr = cpRecoGrammar->AddWordTransition(hsTestResource, NULL,
                    L"test an embedded resource", L" ",
                    SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // Add the resource named "AResource"
            hr = cpRecoGrammar->AddResource(hsTestResource,
                            L"AResource",
                            L"AResource's Value: String");
            // Check hr

            // save/commit changes
            hr = cpRecoGrammar->Commit(NULL);
            // Check hr

        Then, the SR-Engine can retrieve the resource value when it is processing
            the rule updates or CFG-recognition by making the following call:

                // set hRule to handle with resource

                hr = cpSREngineSite->GetResource(hRule,
                    L"AResource",
                    &pwszResValue);
                if (S_OK == hr)
                {
                    // pwszResValue contains the value
                    // perform value-sensitive processing

                    // release value memory
                    ::CoTaskMemFree(pwszResValue);
                }

    return to the top of this page Back to top

<RULE>
    Summary: The RULE tag is the core tag for defining which commands are available for
        recognition. Every grammar must have at least one top-level rule, and
        every rule must have at least one rule reference or recognizable text.
    XML Attributes:
    DYNAMIC (optional, default is FALSE): Specifies whether the rule supports dynamic
        modifications at run time. By default, an application cannot modify rules
        in an XML grammar. To modify a rule, the rule must be marked DYNAMIC, and
        the grammar must be loaded with the dynamic flag (see ISpRecoGrammar and
        SPLOADOPTIONS). Dynamic rules cannot be marked EXPORT.
    EXPORT (optional, default is FALSE): Specifies whether the rule allows external
        grammar to reference it. For example, a grammar author that wants to allow
        other grammar author's to reuse her rules must mark each of the reusable
        rules with EXPORT="TRUE"). Exported rules cannot be marked DYNAMIC.
    ID (required, type=VT_I4): Specifies the numeric identifier of the rule. The ID
        or the NAME must be specified, or both. The identifier must be unique in
        the rule namespace, which is the entire grammar (see GRAMMAR).
    INTERPRETER (optional, default is FALSE): Specifies if the rule should use the
        CFG interpreter when it is recognized. For example,
        a rule might contain semantic properties or text that should be modified
        at run time (e.g. replace value of the semantic property named "TODAY" with
        the system's current date and time).
    NAME (required): Specifies the string identifier of the rule. The NAME
        or the ID must be specified, or both. The identifier must be unique in
        the rule namespace, which is the entire grammar (see GRAMMAR).
    TOPLEVEL (optional): Specifies that the rule is directly recognizable by a user.
        If the TOPLEVEL tag is not specified, then the rule is not recognizable
        unless it is referenced by another top-level rule structure. For example,
        component rules (see RULEREF) do not need to specify the TOPLEVEL attribute.
        When a grammar author specifies a rule as TOPLEVEL, she must also specify
        if the rule is to be enabled by default. If the rule is enabled by default
        (e.g. TOPLEVEL="ACTIVE"), then when the application activates the default
        set of rules (e.g. ISpRecoGrammar::SetRuleState(NULL, NULL, SPRS_ACTIVE)),
        then the rule will be activated. If a rule is specified as
        TOPLEVEL="INACTIVE", then it will only be activated when explicitly set to
        active (see ISpRecoGrammar::SetRuleState and
        ISpRecoGrammar::SetRuleIdState).
    XML Parent Elements:
    GRAMMAR: The container for the entire XML grammar.
    XML Child Elements:
    RULEREF: Import, or reference, another rules contents
    PHRASE, P: Specifies text or leaf nodes.
    LIST, L: Specifies a list of phrases for recognition.
    OPT, O: Specifies an optional piece of text that can be spoken.
    TEXTBUFFER: Specifies a reference to the run-time application maintained
        text-buffer.
    WILDCARD: Specifies a garbage word; one or more non-silence, ignorable words
    DICTATION: Specifies a piece of text recognized by the loaded dictation topic.
    RESOURCE: Specifies a labeled piece of arbitrary string data which can be
        accessed by a special SR engine, or a CFG interpreter.
    Detailed Description:
    The RULE tag is the core of the XML grammar text format. The purpose of creating
        a CFG is to define a specific set of words and phrases that can be
        spoken by the user and recognized by the speech recognition engine. The
        rules can be written by the grammar author in a way that makes them
        reusable, textually maintainable, and conducive to application logic
        that is based on semantic properties or actions (not on phrase text).
    Each rule must contain at least one piece of text, or a rule reference (which
        has the same requirements). Effectively, every rule will eventually end
        with a piece of text (i.e. leaf or terminal node).
    The rule can be identified by either a numeric identifier (ID) or a string identifier
        (NAME). The grammar author can use the DEFINE tag to define constant string
        identifiers for numeric values. By using the constant string identifiers,
        the grammar author can avoid magic numbers (i.e. hard-coded numbers that can
        cause maintenance problems when updating code/grammar). See the ID tag for
        more information on constant identifiers.
    By using rule importing (references) and rule exporting, grammar authors can
        leverage reusable grammar components (e.g. numbers or date grammars).
        Similarly, grammar authors can abstract certain portions of the grammar
        text away from the semantic content by using semantic properties, or
        tags. Semantic properties are name/value pairs which are associated
        with rule nodes in the rule hierarchy, and can even contain relevant
        information from the recognized text (see SPPHRASEPROPERTY.ulStartingElement
        and SPPHRASEPROPERTY.ulCountOfElements).
    The grammar author can also use a CFG interpreter, which is a COM object that can
        re-process the semantic property tree and phrase text to modify the content
        at run time. For example, an application may load a grammar which includes
        a "days of the week" rule. By integrating a CFG interpreter with the grammar,
        the interpreter could replace the "days of the week" properties (e.g. Sunday,
        Monday, Tuesday, etc.) with the actual calendar dates relative to the
        application's host system (e.g. GetSystemTime).
    SAPI supports a feature called "semantic property pushing" which enables
        applications to detect the semantic property structure more accurately at
        recognition time. "Property pushing" is done by SAPI at compile-
        time, whereby the compiler moves semantic properties to the last terminal
        node within a rule which remains unambiguous. For example, the phrases "a b
        c d" and "a b e f g" both have prefixes of "a b". The compiler will
        automatically split the phrases into three separate phrases, "a b", "c d",
        and "e f g", where the first phrase is the common prefix to both recognizable
        phrases. The purpose of this feature is to enable applications that place
        properties on the phrases, will be able to detect which branch is being
        hypothesized as soon as the first unambiguous (non-common) portion of the
        phrase is spoken. When the user speaks "a b" it is not clear if the user will
        say "a b c d" or "a b e f g". If the user then says "e", the application
        can obviously eliminate the "a b c d" option. If the grammar author attached
        properties to the end of both phrases, the semantic property would be
        returned as soon as the user spoke the first unambiguous portion of the text
        (e.g. "c" or "e"). See Semantic Properties, Hypotheses, and "Property Pushing."
    XML Grammar Sample(s):
    <GRAMMAR>
        <DEFINE>
            <ID NAME="RID_Hello" VAL="1"/>
            <ID NAME="RID_World" VAL="2"/>
            <ID NAME="RID_AddNumbers" VAL="3"/>
            <ID NAME="RID_Numbers" VAL="4"/>
            <ID NAME="RID_Numbers_Exportable" VAL="5"/>
            <ID NAME="RID_Names" VAL="6"/>
        </DEFINE>
        <!-- create a simple top-level rule that uses a constant defined identifier -->
        <RULE ID="RID_Hello" TOPLEVEL="ACTIVE">
            <P>hello</P>
        </RULE>

        <!-- Create a simple top-level rule that is inactive by default -->
        <RULE NAME="Hiya" TOPLEVEL="INACTIVE">
            <P>hiya</P>
        </RULE>

        <!-- Create a rule, which a CFG-interpreter can re-process to modify the semantic
            properties -->
        <RULE NAME="InterpretedRule" TOPLEVEL="ACTIVE" INTERPRETER="TRUE">
            <P PROPNAME="TODAY">what is today's date</P>
        </RULE>

        <!-- Create a simple top-level rule that references another non top-level rule -->
        <RULE ID="RID_AddNumbers" TOPLEVEL="ACTIVE">
            <P>add</P>
            <RULEREF REFID="RID_Numbers"/>
            <P>to</P>
            <RULEREF REFID="RID_Numbers"/>
        </RULE>

        <!-- Note that rule is not top-level and is only used as a reusable component rule -->
        <RULE ID="RID_Numbers">
            <LIST PROPID="PID_Value">
                <P VAL="1">one</P>
                <P VAL="2">two</P>
                <P VAL="3">three</P>
                <P VAL="4">four</P>
                <P VAL="5">five</P>
            </LIST>
        </RULE>

        <!-- mark the rule as dynamic so the application can update the list of names
            at runtime -->
        <RULE ID="RID_Names" DYNAMIC="TRUE">
            <LIST>
                <P>bob</P>
                <P>jane</P>
                <P>kate</P>
                <P>tom</P>
            </LIST>
        </RULE>

        <!-- Mark the rule as exportable, so other external grammars can access it -->
        <RULE ID="RID_Numbers_Exportable" EXPORT="TRUE">
            <LIST PROPID="PID_Value">
                <P VAL="6">six</P>
                <P VAL="7">seven</P>
                <P VAL="8">eight</P>
                <P VAL="9">nine</P>
                <P VAL="10">ten</P>
            </LIST>
        </RULE>
    </GRAMMAR>
    Programmatic Equivalent:
    Application developers can programmatically add rules to a grammar by using the
        ISpGrammarBuilder interface inherited by ISpRecoGrammar. The following sample code
        shows how to add a rule to a grammar. To choose the rule attributes, see the
        ISpGrammarBuilder::GetRule method and SPCFGRULEATTRIBUTES.

        SPSTATEHANDLE hHelloWorld;
        // Create new rule called "HelloWorld"
        // Note that the second parameter is the ID, which can also be specified
        // Note also that the rule is marked as top-level and active
        hr = cpRecoGrammar->GetRule(L"SpeakNumber", NULL, SPRAF_TopLevel | SPRAF_Active,
                                TRUE, &hHelloWorld);
        // Check hr

        // add the text "hello world"
        hr = cpRecoGrammar->AddWordTransition(hHelloWorld, NULL, L"hello world",
                            L" ", SPWT_LEXICAL, 1.0f, NULL);
        // Check hr

        // save the grammar changes
        hr = cpRecoGrammar->Commit(NULL);
        // Check hr

    The following sample code shows how to modify a rule in an existing grammar. Specifically,
        the code will update the list of names rule shown in the XML Sample Grammar
        section. By updating the names rule, all rules that reference the names will
        automatically be able to recognize the updated names (after calling ::Commit).

        SPSTATEHANDLE hNames;

        // Get a handle to the existing rule
        // Note the use of the constant identifier RID_Names, which was defined in the
        //	XML sample. See the ID tag for information on generating a C-style header
        hr = cpRecoGrammar->GetRule(NULL, RID_Names, NULL, TRUE, &hNames);
        // Check hr

        // clear the rule to update the entire list
        hr = cpRecoGrammar->ClearRule(hNames);
        // Check hr

        // add name "sally"
        hr = cpRecoGrammar->AddWordTransition(hNames, NULL, L"sally", NULL,
                            SPWT_LEXICAL, 1.0f, NULL);
        // Check hr

        // add name "jim"
        hr = cpRecoGrammar->AddWordTransition(hNames, NULL, L"jim", NULL,
                            SPWT_LEXICAL, 1.0f, NULL);
        // Check hr
        // add name "diane"
        hr = cpRecoGrammar->AddWordTransition(hNames, NULL, L"diane", NULL,
                            SPWT_LEXICAL, 1.0f, NULL);
        // Check hr

        // save grammar changes
        hr = cpRecoGrammar->Commit(NULL);
        // Check hr

    return to the top of this page Back to top

<RULEREF>
    Summary: The RULEREF tag is used for importing rules from the same grammar, or another
        grammar. The RULEREF tag is especially useful for reusing component or
        off-the-shelf rules and grammars.
    XML Attributes:
    NAME (required): Specifies the string identifier of the rule to reference. The NAME
        or the REFID must be specified. If both are specified, they must refer to the
        same rule.
    OBJECT (optional): Specifies the programmatic identifier (ProgId) of the COM
        object which contains the compiled grammar.
    PROPID (optional, type=VT_I4): Specifies the numeric identifier of the semantic property
        attached to the rule reference.
    PROPNAME (optional): Specifies the string identifier of the semantic property attached
        to the rule reference.
    REFID (required, type=VT_I4): Specifies the numeric identifier of the rule to reference.
        The NAME or the REFID must be specified. If both are specified, they must refer
        to the same rule.
    URL (optional): Specifies the uniform resource locator (URL) of the rule to reference.
        The URL can be prefixed by "http://", "file://", or no prefix for a relative
        address. The URL can reference either a compiled grammar (e.g. *.cfg) or an
        uncompiled XML grammar (e.g. *.xml) which will be compiled by SAPI on demand.
    VAL (optional): Specifies the numeric value that will be associated with the semantic
        property attached to the rule reference.
    VALSTR (optional): Specifies the string value that will be associated with the semantic
        property attached to the rule reference.
    WEIGHT (optional, type=VT_UI4,VT_I4,VT_R4,VT_R8, default=1/n_sibling_transitions): The
        probability of the contents of the rule (which is referenced) being spoken by
        the user.
    XML Parent Elements:
    LIST, L: List of phrases or rules which can be recognized.
    PHRASE, P: Phrase that must be recognized for the containing rule to be recognized.
    OPT, O: Optional phrase causing the rule reference to be implicitly optional.
    RULE: Rule that contains phrases or text to be recognized.
    XML Child Elements:
    None
    Detailed Description:
    The RULEREF tag is provided to grammar authors to allow for grammar reusability, and for
        structuring semantic properties into a hierarchy.
    Grammar reusability is provided by allowing rules to reference other rules. For example,
        an independent software vendor (ISV) could developer a series of grammars that
        supported mathematic operations and easy to speak numbers. They could redistribute
        their grammars via either a web site (URL, http), a COM object (ProgId), or a
        compiled grammar. Grammar authors who want to use the ISV's grammars would only
        need to add a RULEREF tag into their grammar which referenced the appropriate
        file or resource location. Similarly, grammar authors can build basic rule
        components into their grammars (e.g. spelling, numbers, or proper names), then
        build complex commands by reusing the basic rule components (local rule reference).
    Structured, hierarchal semantic properties are built on top of RULEs and RULEREFs. All of
        the semantic properties specified inside of a rule are siblings (ordered by
        order of declaration in the recognized transition path). The semantic properties
        that are in rules referenced by another rule are child properties of the
        rule that made the reference. For example, examine the following grammar:
            <RULE NAME="A" TOPLEVEL="ACTIVE">
                <P PROPNAME="ROOT">
                    <RULEREF NAME="B" PROPNAME="ROOT_SIBLING"/>
                </P>
            </RULE>
            <RULE NAME="B">
                <P PROPNAME="CHILD">hello</P>
                <P PROPNAME="LEAF">world</P>
            </RULE>
        The grammar contains two rules, one top-level rule which references another rule.
        The top-level rule contains two semantic properties, one attached to a phrase tag
        (e.g. "ROOT"), and the other attached to the rule reference tag (e.g.
        "ROOT_SIBLING"). The second rule also contains two semantic properties, one
        attached to a phrase tag (e.g. "CHILD), and the other attached to the phrase tag
        (e.g. "LEAF"). If the recognized phrase is "hello world", the semantic property
        structure is as follows:
            SPPHRASE->pProperties.pszName == "ROOT"
            SPPHRASE->pProperties->pNextSibling.pszName == "ROOT_SIBLING"
            SPPHRASE->pProperties->pFirstChild.pszName == "CHILD"
            SPPHRASE->pProperties->pFirstChild->pNextSibling.pszName == "LEAF"
        Note that no matter how many phrases or semantic properties are contained in a
        single RULE, all of the properties are siblings. Child semantic properties are only
        created by using rule references. See also the Whitepaper, Designing Grammar Rules:
        Retrieving Semantic Properties.
    XML Grammar Sample(s):
    <GRAMMAR>
        <DEFINE>
            <ID NAME="RID_Numbers" VAL="1"/>
            <ID NAME="RID_AddNumbers" VAL="2"/>
            <ID NAME="PID_Value" VAL="1"/>
        </DEFINE>
        <!-- create a simple rule that reuses the local numbers rule component -->
        <RULE ID="RID_AddNumbers" TOPLEVEL="ACTIVE">
            <P>add</P>
            <!-- the first operand will be a number from the numbers rule-->
            <!-- the application can retrieve the child property of this property "operand_1"
                which has a value of 1-5 -->
            <RULEREF REFID="RID_Numbers" PROPNAME="operand_1"/>
            <P>to</P>
            <!-- the second operand will be a number from the numbers rule-->
            <!-- the application can retrieve the child property of this property "operand_2"
                which has a value of 1-5 -->
            <RULEREF REFID="RID_Numbers" PROPNAME="operand_2"/>
        </RULE>

        <!-- Note that rule is not top-level and is only used as a reusable component rule -->
        <RULE ID="RID_Numbers">
            <LIST PROPID="PID_Value">
                <P VAL="1">one</P>
                <P VAL="2">two</P>
                <P VAL="3">three</P>
                <P VAL="4">four</P>
                <P VAL="5">five</P>
            </LIST>
        </RULE>

        <RULE NAME="SearchWeb" TOPLEVEL="ACTIVE">
            <P>search web for site named</P>
            <!-- Reference a fictitious rule located on the web which contains a daily updated
                list of SR-friendly web site names -->
            <RULEREF NAME="SiteNames" URL="http://www.msn.com/WebServices/SpeechObjects.cfg"/>
        </RULE>

        <RULE NAME="SearchAddressBook" TOPLEVEL="ACTIVE">
            <P>find address of</P>
            <!-- Reference a fictitious rule located in a registered COM object, which contains
                a dynamic list of Exchange server address book names -->
            <RULEREF NAME="FullNames" OBJECT="Exchange.SpeechGrammars"/>
        </RULE>
    </GRAMMAR>
    Programmatic Equivalent:
    Application developers can programmatically import rules from URLs by using the following format:
        Rule Name = "URL:" + FILENAME + "\\" RULENAME
    For example, to import a rule called "Numbers" from the file "A.cfg", use the following sample code:

        SPSTATEHANDLE hSpeakNumber;
        SPSTATEHANDLE hsBeforeImport;
        SPSTATEHANDLE hsRuleImport;
        // Create new rule called "SpeakNumber"
        hr = cpRecoGrammar->GetRule(L"SpeakNumber", NULL, NULL, TRUE, &hSpeakNumber);
        // Check hr

        // Create new state for the beginning text
        hr = cpRecoGrammar->CreateNewState(hSpeakNumber, &hsBeforeImport);
        // Check hr

        // add the beginning text "speak the number"
        hr = cpRecoGrammar->AddWordTransition(hSpeakNumber, hsBeforeImport, L"speak the number",
                            L" ", SPWT_LEXICAL, 1.0f, NULL);
        // Check hr

        // Import the rule "Numbers" from A.cfg
        hr = cpRecoGrammar->GetRule(L"URL:file://A.cfg\\Numbers", 0, SPRAF_Import, TRUE, &hsRuleImport);
        // Check hr

        // reference the "Numbers" rule after the beginning text
        hr = cpRecoGrammar->AddRuleTransition(hsBeforeImport, NULL, hsRuleImport, 1, NULL);
        // Check hr

        hr = cpRecoGrammar->Commit(NULL);
        // Check hr

    return to the top of this page Back to top

<TEXTBUFFER>
    Summary: The TEXTBUFFER tag is used for applications needing to integrate a dynamic
text box or text selection with a voice command.
    XML Attributes:
    PROPID (optional, type=VT_I4): Specifies the semantic property's numeric identifier.
    PROPNAME (optional): Specifies the semantic property's string identifier.
    WEIGHT (optional, type=VT_UI4,VT_I4,VT_R4,VT_R8, default=1/n_sibling_transitions): Specifies
        the probability of the TEXTBUFFER-based phrase being spoken by the user.
    XML Parent Elements:
    LIST, L: List of phrases which can be recognized.
    PHRASE, P: Phrase that must be recognized for the containing rule to be recognized.
    OPT, O: Optional phrase that may be recognized.
    RULE: Rule that contains phrases or text to be recognized.
    XML Child Elements:
    None
    Detailed Description:
    The TEXTBUFFER tag is useful for applications that have a dynamic buffer of text,
        and want to allow the user to speak portions of the text. The most obvious
        example is likely the text selection user interface. The application offers
        a buffer of text, and allows the user to select any contiguous subset of
        the buffer. For example, when the text is "a b c d e", the user can select
        "a b c" and "c d e", but not "b e" since it is not a contiguous subset of
        the text buffer.
    The TEXTBUFFER tag allows the grammar author to define a command, and reference the
        dynamic text buffer which will be set and maintained at application run time.
        For example, the grammar might contain the command "select TEXTBUFFER_PORTION",
        which, when using the previous text sample, would allow the phrases "select a
        b c", "select "c d e", but not "select b e". The grammar author should focus
        her efforts on building commands to operate on the text buffer, while the
        application developer need only focus on maintaining the text buffer (see
        ISpRecoGrammar::SetWordSequenceData and ISpRecoGrammar::SetTextSelection) and
        responding to the TEXTBUFFER-based commands.
    The TEXTBUFFER has three main components, the complete text buffer, the text allowed
        text subsets in the buffer, and the active selection. The complete text buffer
        is a string of text characters, which is double-NULL terminated. The reason
        for using a double-NULL to allow for multiple exclusive subsets of the buffer
        to be active (e.g. each subset is a paragraph). The recognition engine will
        not recognize phrases which span the exclusive subsets (delimited by a single
        NULL character). The third component is the active selection, or current
        portion of the buffer that should be recognizable (e.g. the application can
        update the selection to include on the text visible on the screen, or only
        the text selected by the user). Note that any portion of the buffer that is
        not included in the TEXTBUFFER's active selection is not recognizable.
    The TEXTBUFFER tag is shared across all of the commands associated with a single
        grammar object. For applications that need to support multiple text buffers,
        the application has three options. If the text buffers use the same commands,
        but do not need to be active simultaneously, the application can use the active
        selection feature (of the TEXTBUFFER) to switch between buffers. If the text
        buffers are unique, but the buffers need to be active simultaneously, the
        application can use the single-NULL terminated subsets of the TEXTBUFFER
        (noting that each set is exclusive and non-contiguous). Finally, if the
        application has multiple text buffers, requires the buffers to be active
        simultaneously, and uses different commands for each buffer, the application
        can use a single grammar object for each buffer.
    The application should use semantic properties (see attributes PROPNAME and PROPID)
        to quickly and easily parse the TEXTBUFFER-related text out of the command.
        SAPI will automatically set the semantic property's phrase
        element range to match the elements taken from the TEXTBUFFER.
    The speech recognition engine must support text-buffers inside of a CFG for the
        grammar to load and activate successfully. The application can determine if
        an engine supports the TEXTBUFFER tag by retrieving the SR engine's object
        token (see ISpRecognizer::GetRecognizer), and then checking for the existence
        of the engine attribute "WordSequences" (see ISpObjectToken::MatchesAttributes).
    XML Grammar Sample(s):
    <GRAMMAR>
        <!-- basic command to perform text selection -->
        <RULE ID="SelectText" TOPLEVEL="ACTIVE">
            <P>select the words</P>
            <TEXTBUFFER PROPID="PID_SelectedText"/>
        </RULE>
    </GRAMMAR>
    Programmatic Equivalent:
    To programmatically create a text-buffer transition in a CFG, the application developer
        can use the ISpGrammarBuilder::AddRuleTransition with a special rule handle,
        called SPRULETRANS_TEXTBUFFER. For example, the following code creates a simple
        command called "SelectText" which recognizes the command "select TEXTBUFFER".

            SPSTATEHANDLE hsSelectText;
            // Create new top-level rule called "SelectText"
            hr = cpRecoGrammar->GetRule(L"SelectText", NULL,
                            SPRAF_TopLevel | SPRAF_Active, TRUE,
                            &hsSelectText);
            // Check hr

            // Create an interim state before the text-buffer transition
            SPSTATEHANDLE hsBeforeTextBuffer;
            hr = cpRecoGrammar->CreateNewState(hsPlayCard, &hsBeforeTextBuffer);
            // Check hr

            // Add the command word "select"
            hr = cpRecoGrammar->AddWordTransition(hsSelectText, hsBeforeTextBuffer,
                    L"select", L" ", SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // Add text-buffer transition
            hr = cpRecoGrammar->AddRuleTransition(hsBeforeTextBuffer, NULL,
                                SPRULETRANS_TEXTBUFFER, 1.0f, NULL);
            // Check hr

            // save/commit changes
            hr = cpRecoGrammar->Commit(NULL);
            // Check hr

            // ... perform other processing/setup

            // Setup text-buffer

            // Place the contents of text buffer into pwszCoMem and
            //	the length of the text in cch
            SPTEXTSELECTIONINFO tsi;
            tsi.ulStartActiveOffset = 0;
            tsi.cchActiveChars = cch;
            tsi.ulStartSelection = 0;
            tsi.cchSelection = cch;
            pwszCoMem2 = (WCHAR *)CoTaskMemAlloc(sizeof(WCHAR) * (cch + 2));
            if (pwszCoMem2)
            {
                // SetWordSequenceData requires double NULL terminator.
                memcpy(pwszCoMem2, pwszCoMem, sizeof(WCHAR) * cch);
                pwszCoMem2[cch] = L'\0';
                pwszCoMem2[cch+1] = L'\0';

                // set the text buffer data
                hr = cpRecoGrammar->SetWordSequenceData(pwszCoMem2, cch + 2, NULL);
                // Check hr

                // set the text selection information independently
                hr = cpRecoGrammar->SetTextSelection(&tsi);
                // Check hr
                CoTaskMemFree(pwszCoMem2);
            }
            CoTaskMemFree(pwszCoMem);

            // the SR engine is now capable of recognizing the contents of the text buffer

    return to the top of this page Back to top

<WILDCARD>
    Summary: The WILDCARD tag is used in rules or phrases that need added robustness and
    flexibility for the speaker's phrasing.
    XML Attributes:
    None
    XML Parent Elements:
    LIST, L: List of phrases which can be recognized.
    PHRASE, P: Phrase that must be recognized for the containing rule to be recognized.
    OPT, O: Optional phrase that may be recognized.
    RULE: Rule that contains phrases or text to be recognized.
    XML Element Children:
    None.
    Detailed Description:
    The WILDCARD tag is designed for applications that would like to recognize
        some phrases without failing due to irrelevant, or ignorable words. For
        example, an application may have a command with the phrase "save document".
        Many users may trivially modify the phrase by saying "save my document",
        "save the document", "save this document", etc.. With a pure CFG, the latter
        phrases would all fail to be recognized due to the extra words. The grammar
        author can add a wildcard, or garbage field, which will consume the extra
        words, and allow the application to successfully handle all of the phrases.
        In the aforementioned case, the grammar would need a wildcard before the word
        "document".
    The WILDCARD is different from DICTATION in that the application will never see the
        recognized garbage words, even though they were recognized. Consequently, the
        application and grammar author should not place wildcards in places which may
        affect the intended user action (e.g. "cancel save" is not the same as "please
        save".
    The grammar author can also use a special character, ellipsis (...) instead of the entire
        XML tag. See XML Grammar Format: Special Wildcard Tag.
    The speech recognition engine must support wildcards inside of a CFG for the grammar
        to load and activate successfully. The application can determine if an engine
        supports the WILDCARD tag by retrieving the SR engine's object token (see
        ISpRecognizer::GetRecognizer), and then checking for the existence of the
        engine attribute "WildcardInCFG" (see ISpObjectToken::MatchesAttributes).
        The engine can specify support for the WILDCARD tag to be anywhere in the
        CFG phrase (attribute value="Anywhere"), or only at the end (attribute
        value="Trailing").
    XML Grammar Sample(s):
    <GRAMMAR>
        <!-- basic command to play the queen of hearts -->
        <RULE ID="PlayCard" TOPLEVEL="ACTIVE">
            <P>play <WILDCARD/> queen of hearts</P>
        </RULE>

        <!-- basic command to play the queen of hearts, using special ellipsis -->
        <RULE ID="PlayCard_Ellipsis" TOPLEVEL="ACTIVE">
            <P>play ... queen of hearts</P>
        </RULE>
    </GRAMMAR>
    Programmatic Equivalent:
    To programmatically create a wildcard transition in a CFG, the application developer
        can use the ISpGrammarBuilder::AddRuleTransition with a special rule handle,
        called SPRULETRANS_WILDCARD. For example, the following code creates a simple
        command called "PlayCard" which recognizes the command "play WILDCARD queen of hearts".
                SPSTATEHANDLE hsPlayCard;
            // Create new top-level rule called "PlayCard"
            hr = cpRecoGrammar->GetRule(L"PlayCard", NULL,
                            SPRAF_TopLevel | SPRAF_Active, TRUE,
                            &hsPlayCard);
            // Check hr

            // Create an interim state before the wildcard transition
            SPSTATEHANDLE hsBeforeWildcard;
            hr = cpRecoGrammar->CreateNewState(hsPlayCard, &hsBeforeWildcard);
            // Check hr

            // Add the command word "play"
            hr = cpRecoGrammar->AddWordTransition(hsSendMail, hsBeforeWildcard,
                    L"play", L" ", SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // Create an interim state after the wildcard transition
            SPSTATEHANDLE hsAfterWildcard;
            hr = cpRecoGrammar->CreateNewState(hsPlayCard, &hsAfterWildcard);
            // Check hr

            // Add interim wildcard transition
            hr = cpRecoGrammar->AddRuleTransition(hsBeforeWildcard, hsAfterWildcard,
                                SPRULETRANS_WILDCARD, NULL, NULL);
            // Check hr

            // Add the command words "queen of hearts"
            hr = cpRecoGrammar->AddWordTransition(hsAfterWildcard, NULL,
                    L"queen of hearts", L" ", SPWT_LEXICAL, 1.0f, NULL);
            // Check hr

            // save/commit changes
            hr = cpRecoGrammar->Commit(NULL);
            // Check hr
        The previous sample code will support any of the following phrases:
        "play the queen of hearts"
        "play a queen of hearts"
        "play the left queen of hearts"
        etc.
    Note that the italicized words will be recognized by the speech recognition engine,
        but will not be returned to the application. The application should not put
        any application-logic sensitive inside of a wildcard, since the text is not
        returned.

    return to the top of this page Back to top


Grammar Format Tags: Special Characters (Microsoft Speech Platform)

 Microsoft Speech Platform

Grammar Format Tags: Special Characters

The following Grammar Format tags have associated special characters which can be used as shorthand to modify words within a rule or used to modify the rule itself. These tags allow greater flexibility of a rule by accepting a wider range of words for a given position.

The following tags are available:
    Optional word (OPT,O): ?
    Wildcard (WILDCARD): ...
    Dictation (DICTATION): *
    Confidence increase (No associated XML tag): +
    Confidence decrease (No associated XML tag): -

Tags

Optional word: ?

    The question before a word marks that word as optional. The word may or may not be used in the position and have no effect on possible rule activation. Using optional words allows for a more natural speaking manner. For example,

    <P>?Please play the card<P>

    The equivalent complete form of the phrase would be:

    <P><O>Please</O>play the card<P>
    This rule permits the user to eliminate the word "please" and still fire a valid rule. If it were required, the user would have to say "please" in order for the speech recognition (SR) engine to recognize the rule.

    return to the top of this page Back to top

Wildcard: ...

    An ellipsis is used to accept words not critical to the rule's intent and allow any word or words to be spoken for that position. Unlike other words in a rule that are explicitly listed, the speaker may use any word or words in this position. The SR engine will attempt to recognize the words, and if successful, will accept them as valid elements for activating the rule. However, the words are not returned in the subsequent phrase list. Regardless of the number of words spoken, the phrase element will contain only one representation for all the words. Using wildcards allows for a more natural speaking manner and is meant for words that are unimportant to the intent of the rule. Wildcards extend the optional (question mark tag) by not requiring an explicit list of all the words. For example,

<P>I would like a hamburger<P>
<P>... hamburger<P>

    The equivalent complete form of the phrase would be:

    <P><WILDCARD/>hamburger<P>

    Both phrases attempt the same action, that of ordering a hamburger. In the first instance, the user would have to use the exact syntax stated. Even optional words would have to be listed and the rule could be cumbersome. The second instance the user can say virtually anything preceding the word "hamburger."

    However, listing other words is not redundant to using just the wildcard. Explicitly listing alternative phrases increases the confidence of the statement. It also increases the SR engine's recognition process because more is known about the possible spoken content. "Please get me a hamburger," is a much more common phrase, and hence is easier to recognize than a non sequitur word allowed by a wildcard. As an example, "aardvark hamburger," is a valid statement according to the rules above, but would be harder for the SR engine to recognize.

    return to the top of this page Back to top

Dictation: *

    The dictation asterisk allows any word or words to be spoken for that position and each word is returned by the SR engine in the phrase element list. Unlike the wildcard, the word or words are considered important to the rule. Using the dictation asterisk, a user can say any word without the engine expecting or anticipating its context. For example, using the following rule, users can speak their first name:

    <P>My first name is *<P>

    The equivalent complete form of the previous phrase would be:

    <P>My first name is <DICTATION/><P>

    If additional words are needed, use the plus sign after dictation to indicate multiple words (up to a pseudo-infinite number, 255):

    <P>My full name and address is *+<P>

    The equivalent complete form of the previous phrase would be:

    <P>My full name and address is <DICTATION MAX="INF"/><P>

    return to the top of this page Back to top

Confidence increase: +
Confidence decrease: -

    One of these two signs placed in front of words respectively increases or decreases the required confidence for a successful recognition. Increasing the required confidence means that the SR engine will have to be much more certain that the word it recognizes really is the expected word. For example, if the user is responding to an important question such as "Reform hard disk?," increasing the required confidence is additional confirmation a "yes" really is "yes." To be certain, the rule would be noted as "+yes".

    Likewise, the minus sign decreases the required confidence for the word. This de-emphasizes words. Although the word is required for the rule, it is not important to verify that the user actually said it.

    For example, in the following rule the user makes a request. However, while the command is required, it is more important that "name" is properly recognized rather than "enter."

    <P>-enter +name<P>

    NOTE: There is no XML Grammar tag equivalent for the confidence special characters, "-" and "+".

    The exact numerical measurement of low confidence, normal confidence, and high confidence as mapped to the recognition process is defined by the SR engine vendor. See also the SR Properties White Paper for more information on manipulating the confidence thresh holds by the SR engine.

    return to the top of this page Back to top


Overview of SAPI Grammar: Solitaire Example (Microsoft Speech Platform)

 Microsoft Speech Platform

SAPI Grammar Example: Solitaire

Grammar rules define sentence contents and phrase elements. Each grammar and grammar element determines the speech recognition (SR) engine's ability to effectively construct phrase elements. Phrases and sub–expressions are commonly represented by a separate rule and combined into larger phrases and sentences with higher level rules. For more information, see the Grammar rules section.

The card game called Solitaire, uses semantic objects such as cards, suits, and ranks, and semantic actions, such as "move SomeCard to AnotherCard", and "new game." The following example illustrates how to implement a grammar for a game of solitaire, which supports the previously mentioned semantic objects and actions. The example also specifies the exact voice command phrases (in American English) that must be spoken in order to play the game.

<!-- The grammar tag surrounds the entire CFG description
       Specify the language of the grammar as
       English-American ('409') -->
<GRAMMAR LANGID="409">
    <!-- Specify a set of easy-to-read strings to
            represent specific values. Similar to
            constants or #define in Visual Basic or
            C/++ programming languages -->
    <DEFINE>
        <ID NAME="FROM" VAL="1"/>
        <ID NAME="TO" VAL="2"/>
        <ID NAME="SUIT" VAL="3"/>
        <ID NAME="COLOR" VAL="4"/>
        <ID NAME="RANK" VAL="5"/>
        <ID NAME="ColorRed" VAL="11101"/>
        <ID NAME="ColorBlack" VAL="10011"/>
    </DEFINE>

   <!-- Define a top-level rule for the new game
           command, called 'newgame' -->
   <!-- Make the rule 'active', by default, so
           the rule is available as soon is speech
           is activated in the application -->
   <RULE NAME="newgame" TOPLEVEL="ACTIVE">
      <!-- Require high confidence for the word,
              game, to avoid accidental recognition
              of this important rule -->
      <!-- Make the last word, please, optional,
              only require low-confidence to
              make the command phrasing more
              flexible -->
      <P>new +game</P><O>-please</O>
   </RULE>

   <!-- Define another active top-level rule,
          called 'playcard' which enables the user
          to use voice commanding to play cards -->
   <!-- Define the 'playcard' rule as exportable, so
          we can create other solitaire or card game
          grammars which can re-use the 'playcard'
          rule functionality. -->
   <RULE NAME="playcard" TOPLEVEL="ACTIVE" EXPORT="1">
      <O>please</O>
      <P>play the</P>
         <!-- Allow for extraneous garbage words
              from the user. The user could say
              "play the little ace of spades" without
              breaking the voice command -->
      <O>...</O>
         <!-- Use a rule reference to a card grammar
                 which is defined elsewhere in the
                 overall solitaire grammar. Using
                 rule references is similar to
                 reusable components in an object-
                 oriented programming language or
                 component model -->
      <RULEREF NAME="card"/>
      <O>please</O>
   </RULE>

   <!-- Define another top-level voice command for
          moving one card to another location -->
   <!-- Note that phrase structure allows for two
           types of move-commands by making to_card
           section optional. The grammar supports
           both 'move from_card to to_card' and
           simply 'move from_card'. The application
           can select the from_card when the latter
           voice command is recognized, or the
           application can perform the full move
           with the former voice command. -->
   <RULE NAME="movecard" TOPLEVEL="ACTIVE">
      <O>please</O>
      <P>
         <L>
            <P>move</P>
            <P>put</P>
         </L>
         <P>the</P>
      </P>

      <!-- Use a semantic tag/property, called 'FROM'
              which represents the from_card, and
              will contain the phrase structure
              recognized in the rule reference. By
              using semantic properties, the application
              can abstract away the exact phrase text
              and build application logic based on
              the action (i.e., Action=move
              FromCard=(Rank=Ace, Suit=Hearts) -->
      <RULEREF PROPNAME="from" PROPID="FROM" NAME="card"/>
      <O>
         <L>
            <P>on</P>
            <P>to</P>
         </L>
         <P>the</P>
         <!-- Use another semantic property for the
                 ToCard information -->
         <RULEREF PROPNAME="to" PROPID="TO" NAME="card"/>
      </O>
      <O>please</O>
   </RULE>

   <!-- Create a reusable card grammar, which contains
           the structure of a card's descriptor (e.g.,
           "red ace", "ace of hearts", or "heart").
           Note: It is not a top-level rule, since
              it is only used by other top-level
              rules and is not directly recognizable -->
   <RULE NAME="card">
      <!-- Use a phrase list to allow the descriptor
           to be one of three forms, including
           a color and rank, or a rank and
           suit, or only a suit. -->
     <!-- The application can decode the
             card by analyzing the semantic
             property structure. For example,
             the color and rank form will
             include a property called 'color'
             with a value either ColorRed or
             ColorBlack (note that these values
             are actually numeric defines).-->
      <L>
         <P><!-- color and rank form -->
            <L PROPNAME="color" PROPID="COLOR">
               <P VAL="ColorRed">red</P>
               <P VAL="ColorBlack">black</P>
            </L>
            <RULEREF NAME="rank"/>
         </P>
         <P><!-- rank and suit form -->
            <RULEREF NAME="rank"/>
            <O>
               <P>of</P>
               <L PROPNAME="suit" PROPID="SUIT">
                  <P VAL="0">clubs</P>
                  <P VAL="1">hearts</P>
                  <P VAL="2">diamonds</P>
                  <P VAL="3">spades</P>
               </L>
            </O>
         </P>
         <!-- suit only form -->
         <L PROPNAME="suit" PROPID="SUIT">
            <P VAL="0">club</P>
            <P VAL="1">heart</P>
            <P VAL="2">diamond</P>
            <P VAL="3">spade</P>
         </L>
      </L>
   </RULE>
   <!-- Create a reusable grammar component, called
           'rank' which represents the numeric rank
           of the various cards. Note that each card
           has an associated value.
        The application can use the semantic property
           called 'rank' (specified by PROPNAME), and
           the value (specified by VAL) to abstract
           itself from the phrasing, and use only the
           numeric rank values. Note that the words
           'king' and 'emperor' both refer to the
           value 13. The grammar author can change
           or update the text without breaking the
           application's semantically-dependent
           logic -->
   <RULE NAME="rank">
      <!-- Specify the property name/id in the LIST
              tag, which will be inherited by all
              of the list tag's child phrase tags.
           Specifying the name/id in the LIST tag avoids
              having to specify it multiple times, once
              for each P tag -->
      <L PROPNAME="rank" PROPID="RANK">
         <P VAL="1">ace</P>
         <P VAL="2">two</P>
         <P VAL="3">three</P>
         <P VAL="4">four</P>
         <P VAL="5">five</P>
         <P VAL="6">six</P>
         <P VAL="7">seven</P>
         <P VAL="8">eight</P>
         <P VAL="9">nine</P>
         <P VAL="10">ten</P>
         <P VAL="11">jack</P>
         <P VAL="12">queen</P>
         <P VAL="13">king</P>
         <P VAL="12">lady</P>
         <P VAL="13">emperor</P>
      </L>
   </RULE>
<!-- End of Grammar definition -->
</GRAMMAR>

return to the top of this page Back to top


ISpGrammarBuilder (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarBuilder

This interface details the SAPI context-free grammar (CFG) backend compiler. These methods can be used to programmatically construct and modify grammars.

When To Use

Applications should use the ISpGrammarBuilder interface to change and save dynamically loaded grammars (see ISpRecoGrammar).

Methods in Vtable Order

ISpGrammarBuilder Methods | Description
ResetGrammar | Clears all grammar rules (un-defines them) and resets the grammar's language to NewLanguage.
GetRule | Retrieves a grammar rule's initial state information (and defines the rule if requested).
ClearRule | Removes all of the grammar rule information except for the rule's initial state handle.
CreateNewState | Creates a new state in the same grammar rule as hState.
AddWordTransition | Adds a word or a sequence of words to the grammar.
AddRuleTransition | Adds a rule (reference) transition from one grammar rule to another.
AddResource | Adds a resource (name and string value) to the grammar rule specified in hRuleState.
Commit | Performs consistency checks of the grammar structure, creates the serialized format, saves the grammar structure, reloads the grammar structure to the stream provided by SetSaveObjects, or reloads it into the SR engine.
Additionally, a sample code is provided to demonstrate ISpGrammarBuilder.
  • Example application of ISpGrammarBuilder


Example application of ISpGrammarBuilder (Microsoft Speech Platform)

 Microsoft Speech Platform

Example application of ISpGrammarBuilder

The code example below illustrates an implementation of a travel grammar, using the ISpGrammarBuilder interface.

An approximation of the XML form is included for each of the following three grammar authoring approaches.

// Declare local identifiers:
HRESULT                       hr = S_OK;
CComPtr<ISpGrammarBuilder>    cpGrammarBuilder;
SPSTATEHANDLE                 hStateTravel;
SPSTATEHANDLE                 hStateTravel_Second;
SPSTATEHANDLE                 hStateMethod;
SPSTATEHANDLE                 hStateDest;

// Create (if rule does not already exist)
// top-level Rule, defaulting to Active.
hr = cpGrammarBuilder->GetRule(L"Travel", 0, SPRAF_TopLevel | SPRAF_Active, TRUE, &hStateTravel);

// Approach 1: list all possible phrases--
// This is the most intuitive approach, and it does not sacrifice efficiency
// because the grammar builder will merge shared sub-phrases when possible.
// Internally, SAPI may break the transitions into separate transitions if
// there are common roots (e.g. "fly to Seattle" and "fly to New York").
// There is only one root state, hStateTravel, and the terminal NULL state,
// and there are 6 unique transitions between root state and NULL state.

/* XML Approximation:
   <RULE NAME="Travel" TOPLEVEL="ACTIVE">
      <PHRASE>fly to Seattle</PHRASE>
      <PHRASE>fly to New York</PHRASE>
      <PHRASE>fly to Washington DC</PHRASE>
      <PHRASE>drive to Seattle</PHRASE>
      <PHRASE>drive to New York</PHRASE>
      <PHRASE>drive to Washington DC</PHRASE>
   </RULE>
*/

// Create set of peer phrases, each containing complete phrase.
// Note: the word delimiter is set as " ", so that the text we
// attach to the transition can be multiple words (for example,
// "fly to Seattle" is implicitly "fly" + "to" + "Seattle"):
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateTravel, NULL, L"fly to Seattle", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateTravel, NULL, L"fly to New York", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateTravel, NULL, L"fly to Washington DC", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateTravel, NULL, L"drive to Seattle", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateTravel, NULL, L"drive to New York", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateTravel, NULL, L"drive to Washington DC", L" ", SPWT_LEXICAL, 1, NULL);
}

// Approach 2: construct the directed-graph using intermediate states--
// This approach gives you more control of the grammar layout, and may be
// easier to implement when you have some combinations.
// Using this approach, there is one root state (hStateTravel), one interim state
// (hStateTravel_Second), and the final terminal NULL state. There are three
// unique transitions between the root state and the interim state. And there are
// three more unique transitions between the interim state, and the final NULL state.
// Note that graph includes only 2-transition paths. The user is not capable of saying
// only the first transition or the second transition (e.g. "fly to" is an invalid
// phrase as is "Seattle", but "fly to Seattle" is valid.)

/* XML Approximation:
   <RULE NAME="Travel" TOPLEVEL="ACTIVE">
      <LIST>
         <PHRASE>fly to</PHRASE>
         <PHRASE>drive to</PHRASE>
         <PHRASE>take train to</PHRASE>
      </LIST>
      <LIST>
         <PHRASE>Seattle</PHRASE>
         <PHRASE>New York</PHRASE>
         <PHRASE>Washington DC</PHRASE>
      </LIST>
   </RULE>
*/

// Create a new transition which starts at
// the root state and ends at a second state.
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->CreateNewState(hStateTravel, &hStateTravel_Second);
}

// Attach the first part of the phrase to to first transition:
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateTravel, hStateTravel_Second, L"fly to", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateTravel, hStateTravel_Second, L"drive to", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateTravel, hStateTravel_Second, L"take train to", L" ", SPWT_LEXICAL, 1, NULL);
}

// Attach the second and final part of the phrase to
// the last transition (ending with the NULL state):
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateTravel_Second, NULL, L"Seattle", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateTravel_Second, NULL, L"New York", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateTravel_Second, NULL, L"Washington DC", L" ", SPWT_LEXICAL, 1, NULL);
}

// Approach 3: Using sub rules--
// This approach let you structure the grammars and is useful when building large grammars,
// since it allows for reusable component rules (see also the XML Grammar tag, RULEREF).
// Note that forward-declarations are allowed, since the grammar validation is not performed
// until the XML is compiled or the GrammarBuilder instance is 'Commit'ted.
// The main difference between Approach 2 and Approach 3 is the use of component rules, which
// are combined into one top-level rule. This facilitates the reuse of the component rules
// in other rules (e.g. create a second rule called "Geography" which combines the phrase
// "where is" with the "Dest" rule, allowing the user to say "where is New York", without
// requiring the grammar author/designer to place the same phrase text in multiple places
// of the grammar leading to grammar maintenance problems.

/* XML Approximation:
   <RULE NAME="Travel" TOPLEVEL="ACTIVE">
      <RULEREF NAME="Method"/>
      <RULEREF NAME="Dest"/>
   </RULE>
   <RULE NAME="Method">
      <LIST>
         <PHRASE>fly to</PHRASE>
         <PHRASE>drive to</PHRASE>
         <PHRASE>take train to</PHRASE>
      </LIST>
   </RULE>
   <RULE NAME="Dest" DYNAMIC="TRUE">
      <LIST>
         <PHRASE>Seattle</PHRASE>
         <PHRASE>New York</PHRASE>
         <PHRASE>Washington DC</PHRASE>
      </LIST>
   </RULE>
*/

if (SUCCEEDED(hr))
{
   // Note the two new rules ("Method" & "Dest") are NOT marked Top-level, since they are
   // reused by other top-level rules, and are not by themselves recognizable phrases:
   hr = cpGrammarBuilder->GetRule(L"Method", 0, 0, TRUE, &hStateMethod);
}
if (SUCCEEDED(hr))
{
   // Marking the "Dest" rules as Dynamic allows the programmatic grammar author to
   // update only the "Dest" rule after the initial ::Commit (e.g. to add more travel
   // destinations depending on user history, preferences, or geographic data):
   hr = cpGrammarBuilder->GetRule(L"Dest", 0, SPRAF_Dynamic, TRUE, &hStateDest);
}

if (SUCCEEDED(hr))
{
   // Create an interim state (same as Approach 2).
   hr = cpGrammarBuilder->CreateNewState(hStateTravel, &hStateTravel_Second);
}

// Then attach rules to the transitions from Root->Interim and Interim->NULL state:
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddRuleTransition(hStateTravel, hStateTravel_Second, hStateMethod, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddRuleTransition(hStateTravel_Second, NULL, hStateDest, 1, NULL);
}

// Add the set of sibling transitions for travel "method":
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateMethod, NULL, L"fly to", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateMethod, NULL, L"drive to", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateMethod, NULL, L"take train to", L" ", SPWT_LEXICAL, 1, NULL);
}

// Add the set of sibling transitions for travel "destinations":
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateDest, NULL, L"Seattle", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateDest, NULL, L"New York", L" ", SPWT_LEXICAL, 1, NULL);
}
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hStateDest, NULL, L"Washington DC", L" ", SPWT_LEXICAL, 1, NULL);
}

// Must Commit before the grammar changes before using the grammar.
// NOTE: grammar changes are only given to the engine at synchronize
// points (see ISpSREngineSite::Synchronize).
if (SUCCEEDED(hr))
{
   hr = cpGrammarBuilder->Commit(0);
}

if (SUCCEEDED(hr))
{
   // Do some more stuff here.
}


ISpGrammarBuilder::ResetGrammar (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarBuilder::ResetGrammar

ISpGrammarBuilder::ResetGrammar clears all grammar rules (un-defines them) and resets the grammar's language to NewLanguage. The state handles for this grammar are no longer valid after this point.

HRESULT ResetGrammar(
   LANGID   NewLanguage
);

Parameters

NewLanguage
[in] Language identifier associated with the grammar rule.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED(hr) | Appropriate error message.

Example

The following code snippet illustrates the use of ResetGrammar.

// Declare local identifiers:
HRESULT                       hr = S_OK;
CComPtr<ISpGrammarBuilder>    cpGrammarBuilder;

// ResetGrammar when no rules.
hr = cpGrammarBuilder->ResetGrammar(409);

if (SUCCEEDED (hr))
{
   // Set language to default user language.
   hr = cpGrammarBuilder->ResetGrammar(SpGetUserDefaultUILanguage());
}

if (SUCCEEDED (hr))
{
   // Set language to non-english.
   hr = cpGrammarBuilder->ResetGrammar(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED));
}

if (SUCCEEDED (hr))
{
   hr = cpGrammarBuilder->ResetGrammar(MAKELANGID(LANG_JAPANESE, SUBLANG_DEFAULT));
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpGrammarBuilder::GetRule (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarBuilder::GetRule

ISpGrammarBuilder::GetRule retrieves grammar rule's initial state.

HRESULT GetRule(
   LPCWSTR        *pszRuleName,
   DWORD           dwRuleId,
   DWORD           dwAttributes,
   BOOL            fCreateIfNotExist,
   SPSTATEHANDLE  *phInitialState
);

Parameters

pszRuleName
[in] Address of the null-terminated string containing the grammar rule name. If NULL, no search is made for the name.
dwRuleId
[in] Grammar rule identifier. If zero, no search is made for the rule ID.
dwAttributes
[in] Grammar rule attributes for the new rule created. Ignored if the rule already exists. Must be of type SPCFGRULEATTRIBUTES. Values may be combined to allow for multiple attributes.
fCreateIfNotExist
[in] Boolean indicating that the grammar rule is to be created if one does not currently exist. TRUE allows the creation; FALSE does not.
phInitialState
[out] The initial state of the rule. May be NULL.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_RULE_NOT_FOUND | No rule matching the specified criteria can be found and a new rule is not created.
SPERR_RULE_NAME_ID_CONFLICT | One of the name and ID matches an existing rule but the other does not match the same rule.
E_INVALIDARG | At least one parameter is invalid. Also returned when both pszRuleName and dwRuleId are NULL.
E_OUTOFMEMORY | Not enough memory to complete operation.

Remarks

Either the rule name or ID must be provided (the other unused parameter can either be NULL or zero). If both a grammar rule name and identifier are provided, they both must match in order for this call to succeed. If the grammar rule does not already exist and fCreateIfNotExists is true, the grammar rule is defined. Otherwise this call will return an error.

Example

The following code snippet illustrates the use of GetRule.

// Declare local identifiers:
HRESULT                       hr = S_OK;
CComPtr<ISpGrammarBuilder>    cpGrammarBuilder;
CComPtr<ISpGrammarBuilder>    cpBackend;
SPSTATEHANDLE                 hState;
SPSTATEHANDLE                 phTarget;
WCHAR                         *pszRuleName = L"SAPI5OBJECT:MyApp.ClassId\\\\RuleName";

// Create a rule with name and ID.
hr = cpGrammarBuilder->GetRule(L"rule1", 1, SPRAF_Dynamic, TRUE, &hState);

if (SUCCEEDED (hr))
{
   // Create a rule with name only.
   hr = cpGrammarBuilder->GetRule(L"rule", 0, SPRAF_Dynamic, TRUE, &hState);
}

if (SUCCEEDED (hr))
{
   // Create a rule with ID only.
   hr = cpGrammarBuilder->GetRule(NULL, 2, SPRAF_Dynamic, TRUE, &hState);
}

if (SUCCEEDED (hr))
{
   // Get an existing rule by ID.
   hr = cpGrammarBuilder->GetRule(L"rule1", 1, SPRAF_Dynamic, FALSE, &hState);
}

if (SUCCEEDED (hr))
{
   hr = cpGrammarBuilder->GetRule(NULL, 1, SPRAF_Dynamic, FALSE, &hState);
}

if (SUCCEEDED (hr))
{
   // Get an existing rule by name.
   hr = cpGrammarBuilder->GetRule(L"rule1", 0, SPRAF_Dynamic, FALSE, &hState);
}

if (SUCCEEDED (hr))
{
   // Get rule references to other grammars and
   // compose the name of the rule as follows.
   // Please note the double back-slash before the rule name.
   // OBJECT --> pszRuleName = L"SAPI5OBJECT:MyApp.ClassId\\\\RuleName"
   // URL --> pszRuleName = L"URL:http://myserver.com\\\\RuleName"
   hr = cpBackend->GetRule(pszRuleName, 0 , SPRAF_Import, TRUE, &phTarget);
}

if (SUCCEEDED (hr))
{
   // phTarget contains a valid rule handle that can by
   // used to reference the rule; now do some more stuff.
}


ISpGrammarBuilder::ClearRule (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarBuilder::ClearRule

ISpGrammarBuilder::ClearRule removes all of the grammar rule information except for the rule's initial state handle.

HRESULT ClearRule(
   SPSTATEHANDLE   hState
);

Parameters

hState
[in] Handle to the any of the states in the grammar rule to be cleared. Only the rule's initial state handle is still valid.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Value specified in hState is not valid.

Example

The following code snippet illustrates the use of ClearRule.

// Declare local identifiers:
HRESULT                       hr = S_OK;
CComPtr<ISpGrammarBuilder>    cpGrammarBuilder;
SPSTATEHANDLE                 hInit;
SPSTATEHANDLE                 hState;

hr = cpGrammarBuilder->GetRule(L"rule1", 1, 0, TRUE, &hInit);

if (SUCCEEDED (hr))
{
  hr = cpGrammarBuilder->CreateNewState(hInit, &hState);
}

if (SUCCEEDED (hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hInit, hState, L"word", NULL, SPWT_LEXICAL, 1, NULL);
}

if (SUCCEEDED (hr))
{
   // Call ClearRule using initial state.
   hr = cpGrammarBuilder->ClearRule(hInit);
}

if (SUCCEEDED (hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hInit, hState, L"word", NULL, SPWT_LEXICAL, 1, NULL);
}

if (FAILED (hr)) {}
{
   // Because hState is no longer valid.
   _ASSERT(hr == E_INVALIDARG);

   // Call ClearRule using hState != hInit.
   hr = cpGrammarBuilder->CreateNewState(hInit, &hState);
}

if (SUCCEEDED (hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hInit, hState, L"word", NULL, SPWT_LEXICAL, 1, NULL);
}

if (SUCCEEDED (hr))
{
   hr = cpGrammarBuilder->ClearRule(hState);
}

if (SUCCEEDED (hr))
{
   hr = cpGrammarBuilder->AddWordTransition(hInit, hState, L"word", NULL, SPWT_LEXICAL, 1, NULL);
}

if (FAILED (hr))
{
   // Because hState is no longer valid.
   _ASSERT(hr == E_INVALIDARG);
}


ISpGrammarBuilder::CreateNewState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarBuilder::CreateNewState

ISpGrammarBuilder::CreateNewState creates a new state in the same grammar rule as hState.

HRESULT CreateNewState(
   SPSTATEHANDLE   hState,
   SPSTATEHANDLE  *phState
);

Parameters

hState
[in] Handle to any existing state in the grammar rule.
phState
[out] Address of the state handle for a new state in the same grammar rule.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | The hState is not a valid state handle.
E_POINTER | The phState pointer is invalid.
E_OUTOFMEMORY | Exceeded available memory.

Example

The following code snippet illustrates the use of CreateNewState.

// Declare local identifiers:
HRESULT                       hr = S_OK;
CComPtr<ISpGrammarBuilder>    cpGrammarBuilder;
SPSTATEHANDLE                 hInit;
SPSTATEHANDLE                 hState;
SPSTATEHANDLE                 hState2;

hr = cpGrammarBuilder->GetRule(L"rule1", 1, 0, TRUE, &hInit);

if (SUCCEEDED (hr))
{
   // Call CreateNewState using the initial state.
hr = cpGrammarBuilder->CreateNewState(hInit, &hState);
}

if (SUCCEEDED (hr))
{
   // Call CreateNewState using hState != hInit.
   hr = cpGrammarBuilder->CreateNewState(hState, &hState2);
}

if (SUCCEEDED(hr))
{
   // Do something here.
}


ISpGrammarBuilder::AddWordTransition (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarBuilder::AddWordTransition

ISpGrammarBuilder::AddWordTransition adds a word or a sequence of words to the grammar.

HRESULT AddWordTransition(
   SPSTATEHANDLE          hFromState,
   SPSTATEHANDLE          hToState,
   LPCWSTR               *psz,
   LPCWSTR               *pszSeparators,
   SPGRAMMARWORDTYPE      eWordType,
   float                  Weight,
   const SPPROPERTYINFO  *pPropInfo
);

Parameters

hFromState
[in] Handle of the state from which the arc (or sequence of arcs in the case of multiple words) should originate.
hToState
[in] Handle of the state where the arc (or sequence of arcs) should terminate. If NULL, the final arc will be to the (implicit) terminal node of this grammar rule.
psz
[in] Address of a null-terminated string containing the word or words to be added. If psz is NULL, an epsilon arc will be added.
pszSeparators
[in] Address of a null-terminated string containing the transition word separation characters.
psz points to a single word if pszSeperators is NULL, or else pszSeperators specifies the valid separator characters. This parameter may not contain a forward slash ("/") as that is used for the complex word format.
eWordType
[in] The SPGRAMMARWORDTYPE enumeration that specifies the word type. SAPI 5.1 supports only SPWT_LEXICAL. SAPI 5.3 supports SPWT_LEXICAL and SPWT_LEXICAL_NO_SPECIAL_CHARS. If neither of these are specified, the method returns E_INVALIDARG.
Weight
[in] Value specifying the arc's relative weight in case there are multiple arcs originating from hFromState.
pPropInfo
[in] The SPPROPERTYINFO structure containing property name and value information that is associated with this arc or sequence of arcs.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | At least one of psz, pszSeparators, or pPropInfo is invalid or bad; eWordType is a value other than SPWT_LEXICAL; flWeight is less than 0.0; a slash ("/") is used as a separators.
SPERR_WORDFORMAT_ERROR | Invalid word format.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.

Remarks

When specifying a word in Display/Lexical/Pronunciation (DLP) format for the psz parameter, you must separate the word types with forward slashes, and terminate the parameter with a semi-colon (003B). You cannot terminate the parameter with the full-width semi-colon (FF1B), as this will generate an error on compiling the grammar. The following example specifies a display form (in line) and a lexical form (inline) for the word to add, followed by a regular semi-colon:

hr = cpRecoGrammar->AddWordTransition(hsSendMail, hsBeforeDictation, L "/in line/inline/;", L" ", SPWT_LEXICAL, NULL, NULL);


ISpGrammarBuilder::AddRuleTransition (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarBuilder::AddRuleTransition

ISpGrammarBuilder::AddRuleTransition adds a rule (reference) transition from one grammar rule to another.

HRESULT AddRuleTransition(
   SPSTATEHANDLE           hFromState,
   SPSTATEHANDLE           hToState,
   SPSTATEHANDLE           hRule,
   float                   Weight,
   const SPPROPERTYINFO   *pPropInfo
);

Parameters

hFromState
[in] Handle of the state from which the arc should originate.
hToState
[in] Handle of the state where the arc should terminate. If NULL, the final arc will be to the (implicit) terminal node of this grammar rule.
hRule
[in] Handle of any state of the rule to be called with this transition. Get the hRule using the ISpGrammarBuilder::GetRule() call. To refer to a rule in another grammar, and "import" that rule by calling ISpGrammarBuilder::GetRule( ... , SPRAF_Import, TRUE /*fCreatIfNotExist*/, ...).

hRule can also be one of the following special transition handles:

Transition handle | Description
SPRULETRANS_WILDCARD | <WILDCARD> transition
SPRULETRANS_DICTATION | <DICTATION> single word from dictation
SPRULETRANS_TEXTBUFFER | <TEXTBUFFER> transition
Weight
[in] Value specifying the arc's relative weight in case there are multiple arcs originating from hFromState.
pPropInfo
[in] The SPPROPERTYINFO structure containing property name and value information that is associated with this arc.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | At least one parameter is invalid.
E_OUTOFMEMORY | Not enough memory to complete operation.
FAILED(hr) | Appropriate error message.


ISpGrammarBuilder::AddResource (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarBuilder::AddResource

ISpGrammarBuilder::AddResource adds a resource (name and string value) to the grammar rule specified in hRuleState. The resource can be queried by a rule interpreter.

HRESULT AddResource(
   SPSTATEHANDLE      hRuleState,
   LPCWSTR           *pszResourceName,
   LPCWSTR           *pszResourceValue
);

Parameters

hRuleState
[in] Handle of a state in the rule to which the resource is to be added.
pszResourceName
[in] Address of a null-terminated string specifying the resource name.
pszResourceValue
[in] Address of a null-terminated string specifying the resource value.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | At least one of the parameters is invalid.
SPERR_DUPLICATE_RESOURCE_NAME | The resource already exists.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.

Example

The following code snippet illustrates the use of AddResource.

// Declare local identifiers:
HRESULT                       hr = S_OK;
CComPtr<ISpGrammarBuilder>    cpGrammarBuilder;
SPSTATEHANDLE                 hInit;
SPSTATEHANDLE                 hState;

hr = cpGrammarBuilder->GetRule(L"rule1", 1, 0, TRUE, &hInit);

if (SUCCEEDED (hr))
{
   hr = cpGrammarBuilder->CreateNewState(hInit, &hState);
}

if (SUCCEEDED (hr))
{
   // Call AddResource using the hInitState.
   hr = cpGrammarBuilder->AddResource(hInit, L"ResName1", L"ResValue1");
}

if (SUCCEEDED(hr))
{
   // Call AddResource using hState != hInit.
   hr = cpGrammarBuilder->AddResource(hState, L"ResName2", L"ResValue2");
}

if (SUCCEEDED(hr))
{
   // Do something here.
}


ISpGrammarBuilder::Commit (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarBuilder::Commit

ISpGrammarBuilder::Commit performs consistency checks of the grammar structure, creates the serialized format, saves the grammar structure, or reloads the grammar structure.

The grammar structure may be saved to the stream provided by SetSaveObjects, or reloaded into the SR engine. Commit must be called before any changes to the grammar can take effect.

Commit can be used to optimize the grammar structure. Typically the grammar optimization is done in the final Commit() call. The span of the semantic properties may be incorrect after grammar optimization.

HRESULT Commit(
   DWORD   dwFlags
);

Parameters

dwFlags
[in] Bitwise flags of type SPGRAMBUILDCOMMITFLAGS. If SPGBCF_NONE, then the grammar structure is NOT optimized. If SPGBCF_OPTIMIZE, then the grammar structure is optimized.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | dwFlags is not SPGBCF_NONE and not SPGBCF_OPTIMIZE. In SAPI 5.3 and below, if dwFlags is not zero.
SPERR_UNINITIALIZED | Stream not initialized. Call SetSaveObjects before Commit.
SPERR_NO_RULES | A grammar must have at least one rule and one word.
SPERR_NO_TERMINATING_RULE_PATH | At least one rule is not empty but has no terminating path (path of transitions from the initial state to a NULL state).
SPERR_CIRCULAR_RULE_REF | At least one rule has left recursion (a direct or indirect rule reference to itself originated from the initial state).
SPERR_STATE_WITH_NO_ARCS | At least one rule has a node with no outgoing transitions.
SPERR_EXPORT_DYNAMIC_RULE | Dynamic rules or rules referencing dynamic rules (directly or indirectly) cannot be exported.


ISpGrammarBuilder2 (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarBuilder2

New in SAPI 5.3

ISpGrammarBuilder2 extends the ISpGrammarBuilder interface.

Methods in Vtable Order

ISpGrammarBuilder2 Methods | Description
AddTextSubset | Adds text for use with subset matching.
SetPhoneticAlphabet | Sets a new phonetic alphabet.


ISpGrammarBuilder2::AddTextSubset (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarBuilder2::AddTextSubset

ISpGrammarBuilder2::AddTextSubset adds text for use with subset matching.

HRESULT AddTextSubset(
   SPSTATEHANDLE    hFromState,
   SPSTATEHANDLE    hToState,
   LPCWSTR           psz,
   SPMATCHINGMODE **eMatchMode
);

Parameters

hFromState
[in] Handle of the state from which the arc should originate.
hToState
[in] Handle of the state where the arc should terminate.
psz
[in] The text subset to be matched.
eMatchMode
[in] The subset matching mode.

Return values

Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Not enough memory to complete operation.

Remarks

If not specified, the value for eMatchMode defaults to 1 (Subsequence).

Currently, you cannot specify the value 0 (AllWords) for eMatchMode.


ISpGrammarBuilder2::SetPhoneticAlphabet (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarBuilder2::SetPhoneticAlphabet

ISpGrammarBuilder2::SetPhoneticAlphabet sets a new phonetic alphabet.

HRESULT SetPhoneticAlphabet(
   PHONETICALPHABET      phoneticALphabet,
);

Parameters

phoneticALphabet
A member of the PHONETICALPHABET enumeration that represents the phonetic alphabet to be used.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_PHONEME_CONVERSION | The new PHONETICALPHABET is not compatible with the old PHONETICALPHABET, and the old PHONETICALPHABET may have been modified.
E_INVALIDARG | The requested PHONETICALPHABET is not supported.


ISpGrammarCompiler (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarCompiler

Microsoft Speech Platform Text Grammar compiler.

Methods in Vtable Order

ISpGrammarCompiler Methods | Description
CompileStream | Loads the XML grammar and produces the binary grammar format.


ISpGrammarCompiler::CompileStream (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpGrammarCompiler::CompileStream

ISpGrammarCompiler::CompileStream loads a SAPI 5 grammar file and produces the binary grammar format. It compiles the grammar file pointed to by pSource stream and writes the output to the pDest stream. It can optionally generate C/C++ header information from the <DEFINE> <ID> tags.

HRESULT CompileStream(
   IStream       *pSource,
   IStream       *pDest,
   IStream       *pHeader,
   IUnknown      *pReserved,
   ISpErrorLog   *pErrorLog,
   DWORD          dwFlags
);

Parameters

pSource
Pointer to the source of the XML grammar text.
pDest
Pointer to the destination stream for the binary grammar.
pHeader
Pointer to the stream to write the C/C++ header information (from the <DEFINE> tags) to (e.g., #define myterm 3).
pReserved
Reserved. Do not use.
pErrorLog
Pointer to the error log receiving the messages.
dwFlags
[in] Not currently used. Must be zero.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One of the parameters is bad or invalid.
FAILED (hr) | Appropriate error message.


Lexicon (Microsoft Speech Platform)

 Microsoft Speech Platform

Lexicon interfaces

The following section covers:

  • Lexicon Interfaces Overview
  • ISpContainerLexicon
  • ISpLexicon
  • ISpLexicon2
  • ISpPhoneConverter
  • ISpPhoneticAlphabetConverter
  • ISpPhoneticAlphabetSelection
  • ISpShortcut


Lexicon Interfaces Overview (Microsoft Speech Platform)

 Microsoft Speech Platform

Lexicon Interfaces Overview

The ISpLexicon interface provides a uniform way for applications and engines to access the user lexicon, application lexicon, and engine private lexicons.

The following topics are covered in this section:

  • ISpLexicon information for application developers
  • ISpLexicon information for engine developers

ISpLexicon information for application developers

SpLexicon is the SAPI standard lexicon object which implements the ISpLexicon interface. It contains the user lexicon and all application lexicons registered in the system when the SpLexicon object was CoCreated. Engines can add their private lexicons through ISpContainerLexicon interface. However, if an application uses ISpContainerLexicon to add a lexicon to an instance of SpLexicon, the engine will not use the lexicon.

You can get pronunciations from both the user and application lexicons:

  hr = cpLexicon->GetPronunciation(... eLEXTYPE_USER ...);
  hr = cpLexicon->GetPronunciation(... eLEXTYPE_APP ...);
  hr = cpLexicon->GetPronunciation(... eLEXTYPE_USER | eLEXTYPE_APP ...);

You can also add or remove an application lexicon. To do so, let your COM object implement the ISpLexicon and ISpObjectWithToken interfaces, and register it as illustrated in the following example:

  hr = SpCreateNewTokenEx(SPCAT_APPLEXICONS, pszLangIndependentName, &CLSID_YourLexicon, pszLangIndependentName, langid, pszLangDependentName, &cpToken, &cpDataKeyAttribs);
  // hr = cpDataKeyAttribs->SetStringValue(name1, value1); // optional.  Can be used to find your lexicon later
  // hr = cpDataKeyAttribs->SetStringValue(name2, value2); // optional
  // ...

You can also use the SAPI-provided CLSID_SpUnCompressedLexicon to implement your application lexicon as follows (the CLSID_SpCompressedLexicon is intended for engine vendors):

  hr = SpCreateNewTokenEx(SPCAT_APPLEXICONS, pszLangIndependentName, &CLSID_SpUnCompressedLexicon, pszLangIndependentName, langid, pszLangDependentName, &cpToken, &cpDataKeyAttribs);

  // hr = cpDataKeyAttribs->SetStringValue(name1, value1); // optional.  Can be used to find your lexicon later
  // hr = cpDataKeyAttribs->SetStringValue(name2, value2); // optional
  // ...

  hr = SpCreateObjectFromToken(cpToken, &cpAppLexicon);

  cpAppLexicon->AddPronunciation(...);
  cpAppLexicon->AddPronunciation(...);
  cpAppLexicon.Release();  // the CLSID_SpUnCompressedLexicon object will be read-only after this point

To remove an application lexicon from the system:

  1. Locate your lexicon with the SpFindBestToken(..., &cpToken) function.
  2. Call cpToken->Remove (NULL) to remove the lexicon from the system.

When an application lexicon is added to the system, it is shared by all applications. Any SpLexicon object created afterward will automatically load the application lexicon. Application lexicons will override engine private lexicons.

return to the top of this page Back to top

ISpLexicon information for engine developers

ISpLexicon provides a uniform format to access user, application, and engine private lexicons. CLSID_SpLexicon implements ISpContainerLexicon, which is derived from ISpLexicon and has one more method, AddLexicon.

CComPtr<ISpContainerLexicon> cpLexicon;
  // load user lexicon and all application lexicons registered in the system automatically
     hr = cpLexicon.CoCreateInstance(CLSID_SpLexicon);

  // create your private lexicons implementing ISpLexicon, e.g. pMyLex1, pMyLex2
     hr = cpLexicon->AddLexicon(pMyLex1, eLEXTYPE_PRIVATE1);
     hr = cpLexicon->AddLexicon(pMyLex2, eLEXTYPE_PRIVATE2);
     ...

Engines can can access lexicons in the following manner:

     hr = cpLexicon->GetPronunciations(... eLEXTYPE_USER ...);
     hr = cpLexicon->GetPronunciations(... eLEXTYPE_APP ...);
     hr = cpLexicon->GetPronunciations(... eLEXTYPE_USER | eLEXTYPE_APP | eLEXTYPE_PRIVATE1 | eLEXTYPE_PRIVATE2 ...);

GetPronunciations will return a SPWORDPRONUNCIATIONLIST structure consisting of pronunciations found in all the specified lexicons.

The lexicon pronunciation information is returned from GetPronunciations in the following order:

  1. Pronunciation from user lexicon (could have multiple pronunciations)
  2. Pronunciation from application lexicon(s) (could have multiple pronunciations)
  3. Pronunciation from the added lexicons in the same order the lexicons were added.

The expected order of priority is the same as what is returned from GetPronunciations in the above list.

The ISpLexicon interface can be used to add or remove words from the user lexicon. However, engine developers will not typically use ISpLexicon::AddPronunciation and ISpLexicon::RemovePronunciation to add or remove words from user lexicons.

When private lexicons are implemented through the ISpLexicon interface, SAPI will only call GetPronunciations and GetWords on the private lexicon. Implementing the AddPronunciation or RemovePronunciation methods to populate lexicons can modify private lexicons.

If you cache the pronunciations from user or application lexicons, you need to call GetGeneration periodically to determine if the pronunciation has been modified. For optimum efficiency, an engine should maintain synchronization with the user and application lexicons.

When the call to GetGeneration returns a larger generation number than the previous call, the engine should call GetGenerationChange or GetWords to update the cache.

Private lexicons can be added to the ISpContainerLexicon interface, or engine developers can elect to create their own method of implementing a private lexicon. However, to ensure consistent performance among all applications, engines should always use the pronunciations from the user and application lexicons.

return to the top of this page Back to top


ISpContainerLexicon (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpContainerLexicon

The container lexicon object automatically loads the user lexicon and all available application lexicons when created. This allows an application and the engine to quickly access all the additional lexicon information present on the system.

ISpContainerLexicon inherits from ISpLexicon.

Implemented By
  • SpLexicon

Methods in Vtable Order

ISpContainerLexicon Methods | Description
AddLexicon | Adds a lexicon and its type to the lexicon stack.


ISpContainerLexicon::AddLexicon (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpContainerLexicon::AddLexicon

ISpContainerLexicon::AddLexicon adds a lexicon and its type to the lexicon stack. Mainly used by engines to add private lexicons to their instance of the container lexicon for consistency of lexicon access.

HRESULT AddLexicon(
   ISpLexicon   *pAddLexicon,
   DWORD         dwFlags
);

Parameters

pAddLexicon
[in] Pointer to the lexicon to be added.
dwFlags
[in] flags of type SPLEXICONTYPE indicating the lexicon type. Should use exactly one of the types from eLEXTYPE_PRIVATE1 through eLEXTYPE_PRIVATE20.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Either dwFlag is invalid or bad, or the lexicon could not be added.
SPERR_ALREADY_INITIALIZED | Attempted to add either the user or application.
E_POINTER | pAddLexicon is invalid or bad.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.

Remarks

For an application to create a new application lexicon, calling AddLexicon for the new lexicon on the application's instance of the container lexicon will not update the engine's instance of the container lexicon. The correct way to update an instance of the container lexicon is to release it and recreate the object. At this point it will re-enumerate all available application lexicons. To guarantee an update of the engine's instance of the container lexicon, the engine must be released and recreated, at which point it will recreate its instance of the container lexicon.


ISpLexicon (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpLexicon

The ISpLexicon interface is used to access the lexicons, which contain information about words that can be recognized or spoken. For more information, please see the ISpLexicon Overview.

Implemented By
  • SpLexicon
  • SpCompressedLexicon
  • SpUncompressedLexicon

Methods in Vtable Order

ISpLexicon Methods | Description
GetPronunciations | Gets pronunciations and parts of speech for a word.
AddPronunciation | Adds pronunciation and parts of speech of a word to the user lexicon.
RemovePronunciation | Removes a word from the user lexicon.
GetGeneration | Passes back the generation ID for a word.
GetGenerationChange | Passes back a list of words which have changed between the current and a specified generation.
GetWords | Gets a list of all words in the lexicon.


ISpLexicon::GetPronunciations (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpLexicon::GetPronunciations

ISpLexicon::GetPronunciations gets pronunciations and parts of speech for a word.

HRESULT GetPronunciations(
   LPCWSTR                  *pszWord,
   LANGID                    LangID,
   DWORD                     dwFlags,
   SPWORDPRONUNCIATIONLIST  *pWordPronunciationList
);

Parameters

pszWord
[in] Pointer to a null-terminated text string as a search keyword. Length must be equal to less than SP_MAX_WORD_LENGTH.
LangID
[in] The language ID of the word. May be zero to indicate that the word can be of any LANGID.
dwFlags
[in] Bitwise flags of type SPLEXICONTYPE indicating that the lexicons searched for this word.
pWordPronunciationList
[in, out] Pointer to SPWORDPRONUNCIATIONLIST structure in which the pronunciations and parts of speech are returned.

Return values

Value | Description
S_OK | Function completed successfully.
SP_WORD_EXISTS_WITHOUT_PRONUNCIATION | The word exists but does not have a pronunciation.
E_POINTER | pWordPronunciationList is not a valid write pointer.
E_INVALIDARG | At least one of the parameters is invalid or bad.
E_OUTOFMEMORY | Exceeded available memory.
SPERR_UNINITIALIZED | The interface has not been initialized.
SPERR_NOT_IN_LEX | Word is not found in the lexicon.
FAILED(hr) | Appropriate error message.

Remarks

The application must create a zero-initialized SPWORDPRONUNCIATIONLIST structure before calling GetPronunciations, using functions such as ZeroMemory or memset to do so. GetPronunciations creates a linked list of word pronunciations that start at the location pointed to by the pvBuffer member of SPWORDPRONUNCIATIONLIST. As long as the SPWORDPRONUNCIATIONLIST structure is still being used, the pvBuffer buffer should not be freed, because GetPronunciations reuses the buffer for reasons of efficiency, and reallocates storage when necessary.

When this structure is no longer needed, free the memory pointed to by pvBuffer by a call to CoTaskMemFree.

Depending on the language, GetPronunciations may return SAPI IDs or Universal Phone Set (UPS) IDs. To determine which phone set (phonetic alphabet) was used to create pronunciations, use the ISpPhoneticAlphabetSelection::IsAlphabetUPS method.

Example

The following example is a code fragment demonstrating the use of GetPronunciations.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpLexicon>          cpLexicon;
SPWORDPRONUNCIATIONLIST      *pwordpronlist;
SPWORDPRONUNCIATION          *pwordpron;

memset(pwordpronlist, 0, sizeof(pwordpronlist));

hr = cpLexicon->GetPronunciations(L"resume", 409, eLEXTYPE_USER | eLEXTYPE_APP, pwordpronlist);

if( SUCCEEDED(hr))
{
   for (pwordpron = pwordpronlist->pFirstWordPronunciation;
      pwordpron != NULL;
      pwordpron = pwordpron->pNextWordPronunciation)
      {
         // Do something with the SPWORDPRONUNCIATION structure's
         // members (for example, ePartOfSpeech and szPronunciation).
      }
}

// Free all the buffers.
CoTaskMemFree(pwordpronlist.pvBuffer);


ISpLexicon::AddPronunciation (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpLexicon::AddPronunciation

ISpLexicon::AddPronunciation adds word pronunciations and parts of speech (POS) to the user lexicon.

HRESULT AddPronunciation(
   LPCWSTR          *pszWord,
   LANGID            LangID,
   SPPARTOFSPEECH    ePartOfSpeech,
   PCSPPHONEID      *pszPronunciation
);

Parameters

pszWord
[in] A pointer to memory that contains the null-terminated word to add. The length, which includes the terminating null character, must be less than or equal to SP_MAX_WORD_LENGTH.
LangID
[in] The language ID of the word pointed to by the pszWord parameter. The speech user default will be used if LANGID is omitted.
ePartOfSpeech
[in] The part of speech as a value of the SPPARTOFSPEECH enumerated type.
pszPronunciation
[in] A pointer to memory that contains the null-terminated pronunciation of the word in phoneme IDs (not phone labels). Multiple pronunciations may be added for a single word. The length must be less than or equal to SP_MAX_PRON_LENGTH. pszPronunciation can be NULL.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | At least one of the parameters is not valid.
SP_ALREADY_IN_LEX | The same pronunciation of the word already exists in the user lexicon.
SPERR_APPLEX_READ_ONLY | Cannot add a word to application lexicon.
SPERR_UNINITIALIZED | The interface has not been initialized.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.

Remarks

See the documentation on ISpPhoneConverter for more information on phone sets.

SAPI will not modify the word if spelling, pronunciation, and POS are the same as an existing entry in the user lexicon. A word can be added without pronunciation by passing in NULL as the pszPronunciation

Example

The following is an example of AddPronunciation.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpPhoneConverter>   cpPhoneConv;
CComPtr<ISpLexicon>          cpLexicon;
LANGID                       langidUS;
SPPHONEID                    wszId[SP_MAX_PRON_LENGTH];

hr = cpLexicon.CoCreateInstance(CLSID_SpLexicon);

// 0x409 for English.
langidUS = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US);

if(SUCCEEDED(hr))
{
   hr = SpCreatePhoneConverter(langidUS, NULL, NULL, &cpPhoneConv);
}

if(SUCCEEDED(hr))
{
   hr = cpPhoneConv->PhoneToId(L"r eh d", wszId);
}
if(SUCCEEDED(hr))
{
   hr = cpLexicon->AddPronunciation(L"red", langidUS, SPPS_Noun, wszId);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpLexicon::RemovePronunciation (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpLexicon::RemovePronunciation

ISpLexicon::RemovePronunciation removes a word and all its pronunciations from a user lexicon.

HRESULT RemovePronunciation(
   LPCWSTR         *pszWord,
   LANGID           LangID,
   SPPARTOFSPEECH   ePartOfSpeech,
   PCSPPHONEID      *pszPronunciation
);

Parameters

pszWord
[in] The word to remove.
LangID
[in] The language ID of the word. The speech user default will be used if LangID is omitted.
ePartOfSpeech
[in] The part of speech of type SPPARTOFSPEECH.
pszPronunciation
[in] Null-terminated pronunciation of the word in the NUM phone set. Multiple pronunciations may be added for a single word. The length must be equal to or less than SP_MAX_PRON_LENGTH. pszPronunciation may be NULL.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One of the parameters is not valid.
E_OUTOFMEMORY | Exceeded available memory.
SPERR_NOT_IN_LEX | Word is not found in the lexicon.
SPERR_APPLEX_READ_ONLY | Cannot remove a word from application lexicon.
SPERR_UNINITIALIZED | Interface not initialized.
FAILED(hr) | Appropriate error message.


ISpLexicon::GetGeneration (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpLexicon::GetGeneration

ISpLexicon::GetGeneration passes back the generation ID for a word.

Passes back the current generation ID of the user lexicon. It is used to detect the changes in the user lexicon because each change in the user lexicon (add/remove a word or install/uninstall an application lexicon) will increment the generation ID.

HRESULT GetGeneration(
   DWORD   *pdwGeneration
);

Parameters

pdwGeneration
The generation ID. This is a relative count of how many times the custom lexicons have changed.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pdwGeneration is not a valid write pointer.
SPERR_UNINITIALIZED | Interface is not initialized.
FAILED(hr) | Appropriate error message.

Remarks

ISpLexicon::GetGenerationChange and ISpLexicon::GetGeneration can be used when an application wants to determine what it has been done to the lexicon over a given period of time. That is, it can back out of changes it has made due to a user cancel. To do this before it begins modifying the lexicon, the application would call ISpLexicon::GetGeneration and store the generation ID. Later, when the application wants to see what words in the lexicon it has modified, it would call ISpLexicon::GetGenerationChanges with the stored ID. This can only be done for small changes, as SPERR_LEX_VERY_OUT_OF_SYNC will be returned once sufficient changes have been made.


ISpLexicon::GetGenerationChange (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpLexicon::GetGenerationChange

ISpLexicon::GetGenerationChange passes back a list of words which have changed between the current and a specified generation.

HRESULT GetGenerationChange(
   DWORD         dwFlags,
   DWORD        *pdwGeneration,
   SPWORDLIST   *pWordList
);

Parameters

dwFlags
[in] The lexicon category of type SPLEXICONTYPE. Currently it must be zero for the SpLexicon (container lexicon) object, and must be the correct flag for the type of SpUnCompressedLexicon object (either eLEXTYPE_USER or eLEXTYPE_APP).
pdwGeneration
[in, out] The generation ID of client when passed in. The current generation ID is passed back on successful completion of the call.
pWordList
[in, out] The buffer containing the word list and its related information. This must be initialized (memset to zero) before first use. If pWordList is successfully returned, CoTaskMemFree must be used to free the list (pWordList->pvBuffer) when no longer needed.

Return values

Value | Description
S_OK | Function completed successfully.
SP_LEX_NOTHING_TO_SYNC | Nothing changed since the passed in generation ID.
SPERR_LEX_VERY_OUT_OF_SYNC | There are too many changes since the passed in generation ID, so that a change history is not available. It could also be returned after installation/uninstallation of an application lexicon. Use ISpLexicon::GetWords if GetGenerationChange returns SPERR_LEX_VERY_OUT_OF_SYNC to regenerate an entire list of words based on the current generation.
E_POINTER | pdwGeneration or pWordList is not a valid write pointer.
E_INVALIDARG | dwFlags is invalid.
SPERR_UNINITIALIZED | Interface has not been initialized.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.

Remarks

An application can determine what has been done to a lexicon over a given period of time using ISpLexicon::GetGenerationChange and ISpLexicon::GetGeneration. That is, it can back out of changes it has made due to a user cancel. To do this, before it starts modifying the lexicon, the application would call ISpLexicon::GetGeneration and store the generation ID. Later, when the application wants to see what words in the lexicon it has modified, it would call ISpLexicon::GetGenerationChanges with the stored ID. This can only be done for small changes because, past a certain point, SPERR_LEX_VERY_OUT_OF_SYNC will be returned and the change history will not be available from the original generation.

Example

The following is an example of GetGenerationChange.

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpLexicon>        cpSpLexicon;
DWORD                      dwGeneration;
SPWORDLIST                 spwordlist;
SPWORD                     *pword;
SPWORDPRONUNCIATION        *pwordpron;

for (;;)
{

   hr = cpSpLexicon->GetGenerationChange(eLEXTYPE_USER, &dwGeneration, &spwordlist);

   // If, for example, a new application lexicon was
   // added, we'll have to rebuild from scratch.
   if (hr == SPERR_LEX_VERY_OUT_OF_SYNC)
   {
      // Call ISpLexicon::GetWords to get
      // a list of all words in the lexicon.
   }
   else if (FAILED(hr))
   {
      // Pass hr to some error-handling routine you have written.
   }
   else
   {
      // Loop thru the changed words, and their new pronunciations--
      for (pword = spwordlist.pFirstWord;
         pword != NULL;
         pword = pword->pNextWord)

         {
            for (pwordpron = pword->pFirstWordPronunciation;
               pwordpron != NULL;
               pwordpron = pwordpron->pNextWordPronunciation)

               {
                  if(pword->eWordType == eWORDTYPE_ADDED)
                  {
                     // Call routine named something like
                     // AddPronunciationToEngineDataStructures,
                     // passing it these 3 parameters:
                     // 1. pword->pszWord
                     // 2. pwordpron->ePartOfSpeech
                     // 3. pwordpron->szPronunciation[]

                  }
                  else // pword->eWordType == eWORDTYPE_DELETED
                  {
                     // Call routine named something like
                     // RemovePronunciationFromEngineDataStructures,
                     // passing it these 3 parameters:
                     // 1. pword->pszWord
                     // 2. pwordpron->ePartOfSpeech
                     // 3. pwordpron->szPronunciation[]

                  }
               }
         }
   }
}


ISpLexicon::GetWords (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpLexicon::GetWords

ISpLexicon::GetWords gets a list of all words in the lexicon.

HRESULT GetWords(
   DWORD         dwFlags,
   DWORD        *pdwGeneration,
   DWORD        *pdwCookie,
   SPWORDLIST   *pWordList
);

Parameters

dwFlags
[in] Bitwise flags of type SPLEXICONTYPE from which words are to be retrieved.
pdwGeneration
[out] The current generation ID of the custom lexicon.
pdwCookie
[in, out] Cookie passed back by this call. It should subsequently be passed back in to get more data. If the call returns S_FALSE, data is remaining and GetWords should be called again. The initial value of the cookie passed in must be zero or pdwCookie will be a NULL pointer. NULL pdwCookie indicates the method should return all words contained in the lexicon at once. If it cannot, SP_LEX_REQUIRES_COOKIE is returned instead.
pWordList
[in, out] The buffer containing the word list and its related information. If pWordList is successfully returned, CoTaskMemFree must be used to free the list (pWordList->pvBuffer) when no longer needed.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | Additional words are left in the lexicon(s) to process.
SPERR_LEX_REQUIRES_COOKIE | A complete list of words cannot be returned at once from the container lexicon. pdwCookie must not be NULL.
E_POINTER | At least one of pdwGeneration, pdwCookie, pWordList is not valid. Alternatively, the block of memory is too small or is not writable.
E_INVALIDARG | At least one of the parameters is not valid.
E_OUTOFMEMORY | Exceeded available memory.
SPERR_UNINITIALIZED | Interface not initialized.
FAILED(hr) | Appropriate error message.

Remarks

To retrieve all of the words in a lexicon, this method typically must be called repeatedly with the cookie (initially set to zero before the first call) until S_OK is returned. S_FALSE is returned to indicate that additional words remain in the lexicon. Optionally, the cookie pointer passed in may be NULL, which indicates that the application is asking to receive all of the words at one time. The lexicon is not required to support this and may return the error SP_LEX_REQUIRES_COOKIE. The SpLexicon object (container lexicon) requires a cookie currently.

Between calls to GetWords it is possible for the GenerationId out parameter to change as the lexicon is updated. The caller of this method should retain the value of GenerationId that is passed out from the first call to GetWords (when the cookie is initially 0). When pdwCookie is nonnull and the cookie value is nonzero, the application should completely ignore the value of GenerationId passed out when GetWords returns.

Example

The following is an example of using GetWords.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpLexicon>          cpLexicon;
SPWORDLIST                   spwordlist;
SPWORDPRONUNCIATIONLIST      *pwordpronlist;
SPWORDPRONUNCIATION          *pwordpron;
SPWORD                       *pword;
DWORD                        dwCookie = 0;
DWORD                        dwGeneration;

memset(pwordpronlist, 0, sizeof(pwordpronlist));

while (SUCCEEDED(hr = cpLexicon->GetWords(eLEXTYPE_USER | eLEXTYPE_APP, &dwGeneration, &dwCookie, &spwordlist)))
{
   for (pword = spwordlist.pFirstWord;
      pword != NULL;
      pword = pword->pNextWord)
   {
      for (pwordpron = pword->pFirstWordPronunciation;
         pwordpron != NULL;
         pwordpron = pwordpron->pNextWordPronunciation)
      {
         // Do something with the SPWORDPRONUNCIATION structure's
         // members (for example, ePartOfSpeech and szPronunciation).
      }
   }

   if (SUCCEEDED (hr))
   {
      // Nothing more to retrieve.
   }

}

// Free all the buffers.
CoTaskMemFree(spwordlist.pvBuffer);


ISpLexicon2 (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpLexicon2

The ISpLexicon2 interface is used to load a lexicon from a file or a stream, and to save a lexicon to a file or a stream.

Implemented By
  • CSpPLSLexicon
  • SpUncompressedLexicon

Methods in Vtable Order

ISpLexicon2 Methods | Description
LoadLexiconFromFile | Loads a lexicon from a file.
LoadLexiconFromStream | Loads a lexicon from a stream.
SaveLexiconToFile | Saves a lexicon to a file.
SaveLexiconToStream | Saves a lexicon to a stream.


ISpLexicon2::LoadLexiconFromFile (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpLexicon2::LoadLexiconFromFile

ISpLexicon2::LoadLexiconFromFile loads a lexicon from a file.

HRESULT LoadLexiconFromFile  (
   LPCWSTR          pszFileName,
   DWORD            dwReserved
);

Parameters

pszFileName
[in] A pointer to a null-terminated text string that is the lexicon file name.
dwReserved
[in] Reserved for future use.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pszFileName is not a valid write pointer.
E_INVALIDARG | At least one of the parameters is invalid.
E_OUTOFMEMORY | Exceeded available memory.
SPERR_ALREADY_INITIALIZED | The object is already initialized.
FAILED(hr) | Appropriate error message.


ISpLexicon2::LoadLexiconFromStream (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpLexicon2::LoadLexiconFromStream

ISpLexicon2::LoadLexiconFromStream loads a lexicon from a stream.

HRESULT LoadLexiconFromStream (
   IStream          *pStream,
   DWORD            dwReserved
);

Parameters

pStream
[in] A pointer to a stream.
dwReserved
[in] Reserved for future use.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pStream is not a valid write pointer.
E_INVALIDARG | At least one of the parameters is invalid.
E_OUTOFMEMORY | Exceeded available memory.
SPERR_ALREADY_INITIALIZED | The object is already initialized.
FAILED(hr) | Appropriate error message.


ISpLexicon2::SaveLexiconToFile (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpLexicon2::SaveLexiconToFile

ISpLexicon2::SaveLexiconToFile saves a lexicon to a file.

HRESULT SaveLexiconToFile  (
   LPCWSTR          pszFileName,
   DWORD            dwReserved
);

Parameters

pszFileName
[in] A pointer to a null-terminated text string that is the lexicon file name.
dwReserved
[in] Reserved for future use.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pszFileName is not a valid write pointer.
E_INVALIDARG | At least one of the parameters is invalid.
E_OUTOFMEMORY | Exceeded available memory.
E_NOTIMPL | The method is not implemented.


ISpLexicon2::SaveLexiconToStream (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpLexicon2::SaveLexiconToStream

ISpLexicon2::SaveLexiconToStream saves a lexicon to a stream.

HRESULT SaveLexiconToStream  (
   IStream          pStream,
   DWORD            dwReserved
);

Parameters

pStream
[in] A pointer to a stream.
dwReserved
[in] Reserved for future use.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pStream is not a valid write pointer.
E_INVALIDARG | At least one of the parameters is invalid.
E_OUTOFMEMORY | Exceeded available memory.
E_NOTIMPL | The method is not implemented.


ISpPhoneConverter (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhoneConverter

The ISpPhoneConverter interface enables the client to convert from the SAPI character phoneset to the Id phoneset.

When to Use
Call methods of the ISpPhoneConverter interface to convert between character and NUM phonesets.
Implemented By
  • SpPhoneConverter

Methods in Vtable Order

ISpPhoneConverter Methods | Description
ISpObjectWithToken interface | Inherits from ISpObjectWithToken and those methods are accessible from an ISpPhoneConverter object.
PhoneToId | Converts a character phoneme string to an ID code string.
IdToPhone | Converts a null-terminated ID code array to the SAPI character format.


ISpPhoneConverter::PhoneToId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhoneConverter::PhoneToId

ISpPhoneConverter::PhoneToId converts a character phoneme string to an ID code string.

The English and Chinese phoneme character sets require that each phoneme be separated/delimited from the next phoneme by a space. The Japanese phoneme character set requires the phoneme characters to be continuous, with no delimiters. See the individual English, Chinese, and Japanese topics for more details about their character sets.

HRESULT PhoneToId(
   LPCWSTR      *pszPhone,
   SPPHONEID    *pId
);

Parameters

pszPhone
[in] Address of a null-terminated string that contains the phoneme string information.
pId
[out] Address of the SPPHONEID array that receives the phoneme identifiers. On return the array will be a null--terminated list of SPPHONEIDs.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid, or phoneme not found.
SPERR_UNINITIALIZED | Interface not initialized.
E_FAIL | pId is invalid or bad.
E_FAILED(hr) | Appropriate error message.


ISpPhoneConverter::IdToPhone (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhoneConverter::IdToPhone

ISpPhoneConverter::IdToPhone converts a null-terminated ID code array to the SAPI character format.

The English and Chinese phoneme character sets require that each phoneme be separated/delimited from the next phoneme by a space. The Japanese phoneme character set requires the phoneme characters to be continuous, with no delimiters. See the individual English, Chinese, and Japanese topics for more details about their character sets.

HRESULT IdToPhone(
   const PCSPPHONEID    *pId,
   WCHAR                *pszPhone
);

Parameters

pId
[in] Address of the null-terminated array of SPPHONEIDs that contains the phoneme identifiers.
pszPhone
[out] Address of a null-terminated string that receives the phoneme string information.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid. Alternatively, pId exceeds SP_MAX_PRON_LENGTH.
E_POINTER | pszPhone or pId is invalid or bad.
SPERR_UNINITIALIZED | Interface not initialized.
E_FAIL | Member exceeds available size.
FAILED(hr) | Appropriate error message.


ISpPhoneticAlphabetConverter (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhoneticAlphabetConverter

New in SAPI 5.3

Enables applications to convert phonemes from SAPI to the Universal Phone Set (UPS) and from UPS to SAPI.

New applications should use the UPS phone set. To use this interface, applications must call SetLangId to set the language in use, hence the phone set, to which the SAPI phonemes belong. Then it can call the SAPI2UPS and UPS2SAPI methods to perform alphabet conversions.

When to Use

Legacy applications using SAPI phone sets can use this interface to convert existing pronunciations to the UPS phone set. These languages use a SAPI phone set:

  • English (en-US)
  • Chinese (zh-CN)
  • German (de-DE)
  • Spanish (es-SP)
  • French (fr-FR)
  • Japanese (ja-JP)
In addition, SAPI supports the UPS for those and all other languages. Thus, alphabet conversion only applies to the above languages.

Implemented By
  • SpPhoneConverter

Methods in Vtable Order

ISpPhoneticAlphabetConverter Methods | Description
GetLangId | Gets the LANGID of the language of the SAPI phone set being used for conversion.
GetMaxConvertLength | Get the maximum length of a string after conversion.
SAPI2UPS | Returns the UPS phone id of the specified SAPI phone.
SetLangId | Sets the language of the SAPI phone set to be used in the conversion.
UPS2SAPI | Returns the SAPI phone id of the specified UPS phone.


ISpPhoneticAlphabetConverter::GetLangId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhoneticAlphabetConverter::GetLangId

Gets the LANGID of the language of the SAPI phone set being used for conversion.

HRESULT GetLangId(
   LANGID            *pLangID
);

Parameters

pLangID
[out] The LangId of the current phoneset.

Return values

Value | Description
S_OK | Function completed successfully.


ISpPhoneticAlphabetConverter::GetMaxConvertLength (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhoneticAlphabetConverter::GetMaxConvertLength

Gets the maximum length of a string after conversion.

The length returned is measured in phonemes, and includes the terminating null.

HRESULT GetMaxConvertLength(
   DWORD           cSrcLength
   BOOL            bSAPI2UPS
   DWORD          *pcMaxDestLength
);

Parameters

cSrcLength
The length of the string to be converted.
bSAPI2UPS
TRUE if converting from SAPI to UPS; FALSE if converting from UPS to SAPI.
pcMaxDestLength
[out] The maximum length of the string after conversion.

Return values

Value | Description
SPERR_UNINITIALIZED | The language of the SAPI phone set has not been set.
S_OK | Function completed successfully.


ISpPhoneticAlphabetConverter::SAPI2UPS (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhoneticAlphabetConverter::SAPI2UPS

Returns the UPS phone id of the specified SAPI phone.

HRESULT SAPI2UPS(
   SPPHONEID       *pszSAPIId
   SPPHONEID       *pszUPSId
   DWORD            cMaxLength
);

Parameters

pszSAPIId
[in] The SAPI phone to be converted.
pszUPSId
[out] The UPS phone that was converted from SAPI.
cMaxLength
The length, in phonemes, of the caller-provided buffer pszUPSId, including the terminating null phoneme ID. Applications can supply a buffer size of SP_MAX_PRON_LENGTH + 1, or they can obtain the required size of the output buffer by calling GetMaxConvertLength.

Return values

Value | Description
SPERR_BUFFER_TOO_SMALL | The specified output buffer length is not sufficient.
SPERR_PHONEME_CONVERSION | The input phoneme string cannot be converted to the desired alphabet. This typically means the phoneme IDs are invalid for the current language.
S_OK | Function completed successfully.


ISpPhoneticAlphabetConverter::SetLangId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhoneticAlphabetConverter::SetLangId

Sets the language of the SAPI phone set to be used in the conversion.

This method must be called before any other methods.

HRESULT SetLangId(
   HRESULT       LANGID LangID
);

Parameters

LangID
The new Lang ID.

Return values

Value | Description
S_FALSE | Function succeeded but the selected language does not have a SAPI phone set. As a result, no conversion is necessary, and calls to the conversion methods will return the same input phonemes as output.
S_OK | Function completed successfully.


ISpPhoneticAlphabetConverter::UPS2SAPI (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhoneticAlphabetConverter::UPS2SAPI

Returns the SAPI phone id of the specified UPS phone.

HRESULT UPS2SAPI(
   SPPHONEID       *pszUPSId
   SPPHONEID       *pszSAPIId
   DWORD            cMaxLength
);

Parameters

pszUPSId
[in] The UPS phone to be converted.
pszSAPIId
[out] The SAPI phone that was converted from UPS.
cMaxLength
The length, in phonemes, of the caller-provided buffer pszUPSId, including the terminating null phoneme ID. Applications can supply a buffer size of SP_MAX_PRON_LENGTH + 1, or they can obtain the required size of the output buffer by calling GetMaxConvertLength.

Return values

Value | Description
SPERR_BUFFER_TOO_SMALL | The specified output buffer length is not sufficient.
SPERR_PHONEME_CONVERSION | The input phoneme string cannot be converted to the desired alphabet. This typically means the phoneme IDs are invalid for the current language.
S_OK | Function completed successfully.
T


ISpPhoneticAlphabetSelection (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhoneticAlphabetSelection

New in SAPI 5.3

Enables the client to control the character phoneset in which pronunciations are encoded by the GetPronunciations method.

Applications utilize this interface to use pronunciations in the Universal Phone Set rather than the SAPI phone set. This is necessary for languages that have SAPI phone sets. For other languages, this interface should have no effect.

By default, all pronunciations sent to and received from SAPI interfaces are in the SAPI phone set. COM components that support UPS should implement this interface to allow applications to detect such support and select the desired alphabet.

Use the IsAlphabetUPS method to discover the alphabet being used. Use the IsAlphabetUPS method to change the alphabet.

Implemented By
  • SpPhoneConverter
  • SpLexicon
  • SpUnCompressedLexicon
  • SpSharedRecoContext
  • SpInProcRecoContext
  • SpVoice

Methods in Vtable Order

ISpPhoneticAlphabetSelection Methods | Description
IsAlphabetUPS | Returns whether the component is using UPS or SAPI.
SetAlphabetToUPS | Sets the alphabet to be used by GetPronunciations.


ISpPhoneticAlphabetSelection::IsAlphabetUPS (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhoneticAlphabetSelection::IsAlphabetUPS

Returns whether the component is using UPS or SAPI.

Call this function to determine if pronunciations returned by GetPronunciations are in the UPS (Universal Phone Set) or in the SAPI phonetic alphabet.

Applications can change the alphabet via the SetAlphabetToUPS method. If an application does not explicitly set the alphabet with SetAlphabetToUPS, the alphabet specified in the lexicon file is used.

HRESULT IsAlphabetUPS(
   BOOL            *pfIsUPS
);

Parameters

pfIsUPS
[out] true if the current alphabet is UPS; otherwise false.

Return values

Value | Description
S_OK | Function completed successfully.


ISpPhoneticAlphabetSelection::SetAlphabetToUPS (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhoneticAlphabetSelection::SetAlphabetToUPS

Sets the alphabet to be used by GetPronunciations.

Call this method to specify the phonetic alphabet that the GetPronunciations method uses to return pronunciations.

A successful call does not imply that pronunciations will be converted successfully. GetPronunciations will fail if the pronunciations cannot be converted to the specified alphabet.

HRESULT SetAlphabetToUPS(
   BOOL         fForceUPS
);

Parameters

fForceUPS
true if pronunciations should be returned in the UPS alphabet; false if pronunciations should be returned in the SAPI alphabet.

Return values

Value | Description
S_OK | Function completed successfully.


ISpShortcut (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpShortcut

New in SAPI 5.3

Provides methods that implement user shortcuts. This is a lexicon that maps a spoken term to an expanded printed term. For example, a user may define "my home address" as "12345 NE 678 Av NE Someplace WA 98888" to save them having to dictate and correct the full address.

Methods in Vtable Order

ISpShortcut Methods | Description
AddShortcut | Adds a user shortcut (that is, a lexicon that maps a spoken term to an expanded printed term).
RemoveShortcut | Removes a user shortcut.
GetShortcuts | Returns all the user shortcuts for a given language.
GetGeneration | Gets the current generation ID.
GetGenerationChange | Gets the list of changes that have happened in a user shortcut since a specific generation.
GetWords | Returns a linked list of shortcut pairs for a generation.


ISpShortcut::AddShortcut (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpShortcut::AddShortcut

ISpShortcut::AddShortcut adds a user shortcut (that is, a lexicon that maps a spoken term to an expanded printed term).

HRESULT AddShortcut(
   LPCWSTR            pszDisplay,
   LANGID             LangID,
   LPCWSTR            pszSpoken,
   SPSHORTCUTTYPE     shType
);

Parameters

pszDisplay
The text to be displayed when the shortcut is spoken.
LangID
The language ID of the shortcut (0 equals default).
pszSpoken
The text the recognizer should listen for.
shType
The type of shortcut.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | The utterance is empty or greater than 384 characters in length.


ISpShortcut::GetGeneration (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpShortcut::GetGeneration

ISpShortcut::GetGeneration gets the current generation ID.

HRESULT GetGeneration(
   DWORD    *pdwGeneration
);

Parameters

pdwGeneration
Address of the dword that the current generation ID should be stored in.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pdwGeneration is not a valid write pointer.
SPERR_UNINITIALIZED | Interface is not initialized.
FAILED(hr) | Appropriate error message.


ISpShortcut::GetGenerationChange (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpShortcut::GetGenerationChange

ISpShortcut::GetGenerationChange gets the list of changes that have happened in a user shortcut since a specific generation.

HRESULT GetGenerationChange(
   DWORD         dwFlags,
   DWORD        *pdwGeneration,
   SPWORDLIST   *pWordList
);

Parameters

dwFlags
[in] A bitfield of SPLEXICONTYPE. It only takes the value of eLEXTYPE_USER_SHORTCUT.
pdwGeneration
[in, out] Used to pass in the generation ID. Changes that occurred between this generation and the current generation will be returned. Upon return, pdwGeneration will contain the current generation ID.
pWordList
[in, out] The linked list of shortcut pairs that are new since the specified generation.

Return values

Value | Description
S_OK | Function completed successfully.
SP_LEX_NOTHING_TO_SYNC | Nothing changed since the passed in generation ID.
SPERR_LEX_VERY_OUT_OF_SYNC | There are too many changes since the passed in generation ID, so that a change history is not available. It could also be returned after installation/uninstallation of an application lexicon. Use ISpLexicon::GetWords if GetGenerationChange returns SPERR_LEX_VERY_OUT_OF_SYNC to regenerate an entire list of words based on the current generation.
E_POINTER | pdwGeneration or pWordList is not a valid write pointer.
E_INVALIDARG | dwFlags is invalid.
SPERR_UNINITIALIZED | Interface has not been initialized.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.


ISpShortcut::GetShortcuts (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpShortcut::GetShortcuts

ISpShortcut::GetShortcuts returns all of the user shortcuts for a given language.

HRESULT GetShortcuts(
   LANGID            LangID,
   SPSHORTCUTPAIRLIST    *pShortcutpairList
);

Parameters

LangID
[in] The language the shortcuts are desired for (0 equals default).
pShortcutpairList
[in, out] A pointer to a list of shortcut pairs.

Return values

Value | Description
S_OK | Function completed successfully.

Remarks

The application must create a zero-initialized SPSHORTCUTPAIRLIST before calling GetShortcuts, using functions such as ZeroMemory or memset to do so. GetShortcuts creates a linked list of user shortcuts that start at the location pointed to by the pvBuffer member of SPSHORTCUTPAIRLIST. As long as the SPSHORTCUTPAIRLIST structure is still being used, the pvBuffer buffer should not be freed, because GetShortcuts reuses the buffer for reasons of efficiency, and reallocates storage when necessary.

When this structure is no longer needed, free the memory pointed to by pvBuffer by a call to CoTaskMemFree.


ISpShortcut::GetWords (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpShortcut::GetWords

ISpShortcut::GetWords returns a linked list of shortcut pairs for a generation.

HRESULT GetWords(
   DWORD         dwFlags,
   DWORD        *pdwGeneration,
   DWORD        *pdwCookie,
   SPWORDLIST   *pWordList
);

Parameters

dwFlags
[in] A bitfield of SPLEXICONTYPE. It only takes the value of eLEXTYPE_USER_SHORTCUT.
pdwGeneration
[in, out] The current generation ID will be returned.
pdwCookie
[in, out] Should initially be NULL. A cookie will be returned, which can then be passed into a subsequent call to get more data, and so on.
pWordList
[in, out] A linked list of shortcut pairs. If you want more, just use the cookie and call GetWords again

Return Value

An ISpeechLexiconWords object, which is a collection of one or more ISpeechLexiconWord objects.


ISpShortcut::RemoveShortcut (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpShortcut::RemoveShortcut

ISpShortcut::RemoveShortcut removes a user shortcut. All four parameters are needed so that the shortcut can be unambiguously identified.

HRESULT RemoveShortcut(
   LPCWSTR            pszDisplay,
   LANGID             LangID,
   LPCWSTR            pszSpoken,
   SPSHORTCUTTYPE     shType
);

Parameters

pszDisplay
The display text for the shortcut.
LangID
The language ID of the shortcut (0 equals default).
pszSpoken
The text the recognizer should listen for.
shType
The type of shortcut.

Return values

Value | Description
S_OK | Function completed successfully.


Resource management interfaces (Microsoft Speech Platform)

 Microsoft Speech Platform

Resource interfaces

The following section covers:

  • Object Tokens Overview
  • ISpDataKey
  • ISpRegDataKey
  • ISpObjectTokenInit
  • ISpObjectTokenCategory
  • ISpObjectToken
  • IEnumSpObjectTokens
  • ISpObjectWithToken
  • ISpResourceManager


Object Tokens Overview SAPI 5.4

 Microsoft Speech Platform

Object Tokens Overview

This document is a high level summary of Object Tokens, Categories and Registries used in SAPI. It is intended to assist developers of speech-enabled applications in understanding the concepts of tokens and categories and using them.

Token

A token is an object representing a resource. It provides an application an easy mechanism with which to inspect the various attributes of a resource without instantiating it. SAPI stores information about tokens in the registry. A token is represented in the registry by a key, and the key's underlying keys and values. For example, MSMary is a token, it represents the Microsoft Mary Voice, and its TokenId is HKEY_LOCAL_MACHINE\Software\Microsoft\Speech\Voices\Tokens\MSMary. Generally, a token contains a language-independent name, a CLSID used to instantiate the object from token, and a set of attributes. It may also contain a CLSID for certain types of user interfaces (UIs), and a set of files from which SAPI returns the paths to all the associated files for the token.

Categories

An Object Token Category is a class of tokens. It is represented in the registry by a key containing one or more token keys under it. Categories contain a single key called Tokens, and the keys for the tokens that belong to that category under it, or keys for token enumerators. See Object Tokens and Registry Settings for detailed descriptions of token enumerators. For example, Voice is a Category, and it contains the Microsoft Mary, Microsoft Sam, Microsoft Mike voices. Its CategoryId is HKEY_LOCAL_MACHINE\Software\Microsoft\Speech\Voices. SAPI categories that are located under HKEY_LOCAL_MACHINE\Software\Microsoft\Speech are Voices, Recognizers, AppLexicons, AudioInput, AudioOutput and PhoneConverter. Another category, Recoprofiles, is located under HKEY_CURRENT_USER\Software\Microsoft\Speech.

Using Tokens and Categories

To enumerate tokens, the application can call the ISpObjectTokenCategory::EnumTokens method, or the helper function SpEnumTokens. The following code examples demonstrate a request for female voices, using each technique. In both cases, adult voices will be listed first.

The first example calls ISpObjectTokenCategory::EnumTokens.

CComPtr<ISpObjectTokenCategory> cpCategory;
CComPtr<IEnumSpObjectTokens> cpEnum;

HRESULT hr = cpCategory.CoCreateInstance(CLSID_SpObjectTokenCategory);
//check hr
hr = cpCategory->SetId(SPCAT_VOICES, false);
//check hr
hr = cpCategory->EnumTokens(L"Gender=Female", L"Age=Adult", &cpEnum);
//check hr

The second example calls SpEnumTokens.

CComPtr<IEnumSpObjectTokens> cpEnum;

hr = SpEnumTokens(SPCAT_VOICES, L"Gender=Female", L"Age=Adult", &cpEnum);

// After getting enumerator, use methods in IEnumSpObjectTokens to get tokens.

CComPtr<ISpObjectToken> cpToken;

hr = cpEnum->Next(1, &cpToken, NULL);

Other helper functions that can simplify the steps, for example: SpGetDefaultTokenFromCategoryId, SpFindBestToken. Please see the Helper Functions document for more detail descriptions.

Engine developers also need to associate files with tokens and be able to create new tokens. A token can query for all the files under the Files key using ISpObjectToken::GetStorageFileName. SAPI does not store full paths, for example:

%1c%\Microsoft\Speech\Files\MSASR\SP_63EB435D95104977BDB68E3BE3469803.dat

Use ISpObjectToken::RemoveStorageFileName to remove the files.

Keys under a token can be inspected. Following is a sample code to add a Special attribute to the default Voices token:

CComPtr<ISpObjectToken> cpToken;
CComPtr<ISpDataKey> cpKey;

hr = SpGetDefaultTokenFromCategoryId(SPCAT_VOICES, &cpToken);
//check hr
hr = cpToken->OpenKey(L"Attributes", &cpKey);
//check hr
hr = cpKey->SetStringValue(L"Special", L"fun");
//check hr
WCHAR *psz = NULL;
hr = cpKey->GetStringValue(L"Special", &psz);
//check hr
::CoTaskMemFree(psz);

To create a key under default voice token, call CreateKey from the Token:

CComPtr<ISpObjectToken> cpToken;
CComPtr<ISpDataKey> cpKey;

hr = SpGetDefaultTokenFromCategoryId(SPCAT_VOICES, &cpToken);
//check hr
hr = cpToken->CreateKey(L"CreatedKey", &cpKey);
//check hr
hr = cpKey->SetStringValue(L"Attri", L"data");
//check hr

Detailed information can be found in Object Tokens and Registry Settings and individual API documents.


ISpDataKey (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey

The ISpDataKey interface provides a mechanism for storing and retrieving string and other data. ISpDataKey is used in conjunction with object tokens, which implement ISpObjectToken, which inherits from ISpDataKey. For example, data can be stored in an object token representing a recognizer or TTS engine using this interface.

Implemented By
  • SpObjectToken object. This is the standard class used for all existing SAPI object tokens. The data for each object token is stored in the registry.
  • Applications or engines can implement this interface directly if they wish to provide a custom data key implementation.

Methods in Vtable Order

ISpDataKey Methods | Description
SetData | Sets the binary data for a token.
GetData | Retrieves the binary data for a token.
SetStringValue | Sets the string value information for a specified token.
GetStringValue | Retrieves the string value information from a specified token.
SetDWORD | Sets the value information for a specified token.
GetDWORD | Retrieves the value information from a specified token.
OpenKey | Opens a specified token subkey.
CreateKey | Creates a new token subkey.
DeleteKey | Deletes a specified token key and all its descendants.
DeleteValue | Deletes a named value from the specified token.
EnumKeys | Enumerates the subkeys of the specified token.
EnumValues | Enumerates the values of the specified token.


ISpDataKey::SetData (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey::SetData

ISpDataKey::SetData sets the binary data for a token.

HRESULT SetData(
   LPCWSTR       *pszValueName,
   ULONG          cbData,
   const BYTE    *pData
);

Parameters

pszValueName
[in] Address of a null-terminated string that contains the registry key value name.
cbData
[in] Size of the pData parameter.
pData
[out] Pointer to the buffer containing the information.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Either pszValueName or pData is an invalid or bad pointer.
FAILED(hr) | Appropriate error message.


ISpDataKey::GetData (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey::GetData

ISpDataKey::GetData retrieves the binary data for a token.

HRESULT GetData(
   LPCWSTR       *pszValueName,
   ULONG         *pcbData,
   BYTE          *pData
);

Parameters

pszValueName
Address of a null-terminated string containing the name of the registry key from which to retrieve the registry key value.
pcbData
[in] Size of the pData parameter.
pData
[out] Pointer to the buffer receiving the information.

Return values

Value | Description
S_OK | Function completed successfully, or pData was NULL. For more information, see Remarks.
E_INVALIDARG | pszValueName is invalid or bad.
E_POINTER | Either pcbData or pData is an invalid or bad pointer.
SPERR_NOT_FOUND | Token key not found.
FAILED(hr) | Appropriate error message.

Remarks

If GetData is called with NULL for pData it returns S_OK and the size of the required buffer in *pcbData.


ISpDataKey::SetStringValue (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey::SetStringValue

ISpDataKey::SetStringValue sets the string value information for a specified token.

HRESULT SetStringValue(
   LPCWSTR      *pszValueName,
   LPCWSTR      *pszValue
);

Parameters

pszValueName
Address of the null-terminated string specifying the name of the string value. If NULL, the default value of the token is used.
pszValue
Address of a null-terminated string that contains the string value to be set for the specified key.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Either pszValueName or pszValue is invalid or bad.
FAILED(hr) | Appropriate error message.


ISpDataKey::GetStringValue (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey::GetStringValue

ISpDataKey::GetStringValue retrieves the string value information from a specified token.

HRESULT GetStringValue(
   LPCWSTR       *pszValueName,
   LPWSTR       **ppszValue
);

Parameters

pszValueName
Address of a null-terminated string that specifies the name of the registry key. If NULL, the default value of the token is read.
ppszValue
Address of a pointer to a null-terminated string that receives the string value for the specified key.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszValueName is invalid or bad.
E_POINTER | ppszValue is invalid or bad.
SPERR_NOT_FOUND | Registry file not found.
FAILED(hr) | Appropriate error message.


ISpDataKey::SetDWORD (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey::SetDWORD

ISpDataKey::SetDWORD sets the value information for a specified token.

HRESULT SetDWORD(
   LPCWSTR       *pszValueName,
   DWORD          dwValue
);

Parameters

pszValueName
Address of a null-terminated string that contains the attribute name.
dwValue
The data buffer containing the attribute key value.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszKeyName is invalid or bad.
FAILED(hr) | Appropriate error message.


ISpDataKey::GetDWORD (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey::GetDWORD

ISpDataKey::GetDWORD retrieves the value information from a specified token.

HRESULT GetDWORD(
   LPCWSTR       *pszKeyName,
   DWORD         *pdwValue
);

Parameters

pszKeyName
[in] Address of a null-terminated string containing the token name.
pdwValue
[out] Address of the destination data buffer receiving the token key value.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszKeyName is invalid or bad.
E_POINTER | pdwValue is invalid or bad.
SPERR_NOT_FOUND | Registry key not found.
FAILED(hr) | Appropriate error message.


ISpDataKey::OpenKey (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey::OpenKey

ISpDataKey::OpenKey opens a specified token subkey. Passes back a new object that supports ISpDataKey for the specified subkey.

HRESULT OpenKey(
   LPCWSTR       *pszSubKeyName,
   ISpDataKey   **ppSubKey
);

Parameters

pszSubKeyName
Address of a null-terminated string specifying the name of the key to open.
ppSubKey
Address of a pointer to an ISpDataKey interface.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszSubKeyName is invalid or bad.
E_POINTER | ppSubKey is invalid or bad.
SPERR_NOT_FOUND | Registry key not found.
FAILED(hr) | Appropriate error message.


ISpDataKey::CreateKey (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey::CreateKey

ISpDataKey::CreateKey creates a new token subkey. Returns a new object which supports ISpDataKey for the specified subkey. If the key already exists, the function will open the existing key instead of overwriting it.

HRESULT CreateKey(
   LPCWSTR       *pszSubKeyName,
   ISpDataKey   **ppSubKey
);

Parameters

pszSubKeyName
Address of a null-terminated string specifying the name of the key to create.
ppSubKey
Address of a pointer to an ISpDataKey interface.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Either pszSubKeyName or ppKey is invalid or bad.
FAILED(hr) | Appropriate error message.


ISpDataKey::DeleteKey (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey::DeleteKey

ISpDataKey::DeleteKey deletes a specified token key and all its descendants.

HRESULT DeleteKey(
   LPCWSTR   *pszSubKeyName
);

Parameters

pszSubKeyName
Address of a null-terminated string specifying the name of the key or subkey to delete.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszSubKeyName is invalid or bad.
SPERR_NOT_FOUND | Token key not found.
FAILED(hr) | Appropriate error message.


ISpDataKey::DeleteValue (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey::DeleteValue

ISpDataKey::DeleteValue deletes a named value from the specified token.

HRESULT DeleteValue(
   LPCWSTR   *pszValueName
);

Parameters

pszValueName
Address of a null-terminated string specifying the value name to be deleted.

Return values

Value Description S_OK Function completed successfully. E_INVALIDARG pszValueName is invalid or bad. SPERR_NOT_FOUND Registry key not found. FAILED(hr) Appropriate error message.


ISpDataKey::EnumKeys (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey::EnumKeys

ISpDataKey::EnumKeys enumerates the subkeys of the specified token.

HRESULT EnumKeys(
   ULONG      Index,
   LPWSTR   **ppszSubKeyName
);

Parameters

Index
[in] Value indicating which token in the enumeration sequence to locate.
ppszSubKeyName
[out] Address of a pointer to a null-terminated string that receives the enumerated key name. This must be freed with CoTaskMemFree() when no longer required.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | ppszSubKeyName is invalid or bad.
SPERR_NOT_FOUND | Registry key not found.
E_OUTOFMEMORY | Not enough memory to allocate string.
SPERR_NO_MORE_ITEMS | No items could be accessed.
FAILED(hr) | Appropriate error message.


ISpDataKey::EnumValues (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpDataKey::EnumValues

ISpDataKey::EnumValues enumerates the values of the specified token.

HRESULT EnumValues(
   ULONG      Index,
   LPWSTR   **ppszValueName
);

Parameters

Index
[in] Value indicating which token in the enumeration sequence to locate.
ppszValueName
Address of a pointer to a null-terminated string that receives the enumerated registry key values. This must be freed with CoTaskMemFree() when no longer required.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | ppszValueName is invalid or bad.
SPERR_NOT_FOUND | Registry key not found.
E_OUTOFMEMORY | Not enough memory to allocate string.
SPERR_NO_MORE_ITEMS | No items could be accessed.
FAILED(hr) | Appropriate error message.


ISpRegDataKey (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRegDataKey

This interface is used to create a new data key using a specific key in the registry for storage. The ISpRegDataKey inherits from ISpDataKey.

The ISpRegDataKey inherits from ISpDataKey.

Applications will not normally need to use or implement this interface.

Implemented By
  • SpDataKey. This class stores all the data for a data key in the registry.

Methods in Vtable Order

ISpRegDataKey Methods | Description
SetKey | Sets the hive registry key (HKEY) to use for subsequent token operations.


ISpRegDataKey::SetKey (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRegDataKey::SetKey

ISpRegDataKey::SetKey sets the hive registry key (HKEY) to use for subsequent token operations.

HRESULT SetKey(
   HKEY   hkey,
   BOOL   fReadOnly
);

Parameters

hkey
[in] The registry key to use.
fReadOnly
[in] Boolean flag setting the keys to read/write status. If TRUE, the registry is read only; FALSE sets it to read and write.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_ALREADY_INITIALIZED | Interface is already initialized.

Example

The following code snippet adds, tests and deletes a superfluous key from the speech registry.

// Declare local identifiers:
HRESULT                           hr = S_OK;
CComPtr<ISpRegDataKey>            cpSpRegDataKey;
CComPtr<ISpDataKey>               cpSpCreatedDataKey;
CComPtr<ISpDataKey>               cpSpDataKey;
CComPtr<ISpObjectTokenCategory>   cpSpCategory;
HKEY                              hkey;

// Create a bogus key under Voices.
hr = RegCreateKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Speech\\Voices\\bogus", 0, NULL, 0, KEY_READ | KEY_WRITE, NULL, &hkey, NULL);

if (SUCCEEDED(hr))
{
   hr = cpSpRegDataKey.CoCreateInstance(CLSID_SpDataKey);
}

if (SUCCEEDED(hr))
{
   hr = cpSpRegDataKey->SetKey(hkey, false);
}

if (SUCCEEDED(hr))
{
   // Do not need to do RegCloseKey on this hkey;
   // the handle gets released inside SetKey().
   hkey = NULL;

   hr = cpSpRegDataKey->QueryInterface(&cpSpCreatedDataKey);
}

if (SUCCEEDED(hr))
{
   // Delete this bogus key.
   hr = SpGetCategoryFromId(SPCAT_VOICES, &cpSpCategory);
}

if (SUCCEEDED(hr))
{
   hr = cpSpCategory->GetDataKey(SPDKL_LocalMachine, &cpSpDataKey);
}

if (SUCCEEDED(hr))
{
   hr = cpSpDataKey->DeleteKey(L"bogus");
}


ISpObjectTokenInit (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectTokenInit

This interface inherits from ISpObjectToken.
Associated Class IDs

The following class IDs (CLSID) may be used with this interface. A complete CLSID listing for all interfaces is in the Class IDs section.

    CLSID_SpObjectToken

Methods in Vtable Order

ISpObjectTokenInit Methods | Description
InitFromDataKey | Initializes a token to use a specified datakey.


ISpObjectTokenInit::InitFromDataKey (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectTokenInit::InitFromDataKey

ISpObjectTokenInit::SetObjectToken initializes a token to use a specified datakey.

HRESULT InitFromDataKey(
   const WCHAR   *pszCategoryId,
   const WCHAR   *pszTokenId,
   ISpDataKey    *pDataKey
);

Parameters

pszCategoryId
[in] The null-terminated string name of the categoryId from which to create the token.
pszTokenId
[in] The null-terminated string name of the TokenId.
pDataKey
[in] Address of an ISpDataKey interface that specifies the system registry key from which to create the token.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | At least one of the parameters is invalid or bad.
SPERR_ALREADY_INITIALIZED | Token is already initialized.
SPERR_TOKEN_DELETED | Key has been deleted.
E_OUTOFMEMORY | Exceeded available memory.

Remarks

Dynamic token enumerators can use this to create tokens under their token enumerator's token. Once created, this enables ISpDataKey::CreateKey to make a new data key, create a new object token, and then use InitFromDataKey.


ISpObjectTokenCategory (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectTokenCategory

Each object token category represents a collection of similar tokens, such as voices, recognizers, and audio input devices. Categories may be created or manipulated with helper functions or methods from this interface.

Each category has a Category ID that is unique and identifies only one type of object token. The set of available categories are listed in Token Category IDs. Category IDs are always null-terminated strings.

An application can create an SpObjectTokenCategory object, which implements this interface. Then it calls SetId in order to set the Category ID that this object is using. The application can then enumerate the object tokens associated with this category using EnumTokens. Applications can also locate and change the default object token for a category with the methods SetDefaultTokenId and GetDefaultTokenId.

ISpObjectTokenCategory inherits from ISpDataKey.

Implemented By
  • SpObjectTokenCategory object. This is the standard class used for categories in SAPI. The category and the list of associated tokens are stored in the registry.
How Created
  • Applications will normally create object token categories by directly creating the SpObjectTokenCategory class.
  • If the application is using the category to find an associated token that matches certain attributes, it is often easier to use the helper functions SpEnumTokens or SpFindBestToken.

Methods in Vtable Order

ISpObjectToken Methods | Description
SetId | Sets the category ID.
GetId | Retrieves the token ID.
GetDataKey | Gets the data key associated with a specific location.
EnumTokens | Enumerates the tokens for the category.
SetDefaultTokenId | Sets a specific TokenId as the default for the category.
GetDefaultTokenId | Retrieves the default TokenId for the category.


ISpObjectTokenCategory::SetId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectTokenCategory::SetId

ISpObjectTokenCategory::SetId sets the category ID.

This method may be called only once. If called more than once, SPERR_ALREADY_INITIALIZED will return.

HRESULT SetId(
   LPCWSTR       *pszCategoryId,
   BOOL           fCreateIfNotExist
);

Parameters

pszCategoryId
[in] The null-terminated string name of category to set. SAPI-defined categories are listed in Token Category IDs.
fCreateIfNotExist
[in] Indicates creating the category if one is not already present. TRUE creates the entry. FALSE does not.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_ALREADY_INITIALIZED | Category interface is already initialized.
E_INVALIDARG | pszCategoryId is invalid or bad.
FAILED(hr) | Appropriate error message.


ISpObjectTokenCategory::GetId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectTokenCategory::GetId

ISpObjectTokenCategory::GetId retrieves the category ID.

HRESULT GetId(
   LPWSTR   **ppszCoMemCategoryId
);

Parameters

ppszCoMemCategoryId
[in] The null-terminated string name of the current category. ppszCoMemCategoryId must be freed with CoTaskMemFree when no longer required.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_UNINITIALIZED | Category interface is not initialized.
E_POINTER | ppszCoMemCategoryId is invalid or bad.
FAILED(hr) | Appropriate error message.

Example

The following code snippet retrieves CategoryId for SPCAT_VOICES.

// Declare local identifiers:
HRESULT                           hr = S_OK;
CComPtr<ISpObjectTokenCategory>   cpSpObjectTokenCategory;
WCHAR                             *cpwszOldID;

hr = SpGetCategoryFromId(SPCAT_VOICES, &cpSpObjectTokenCategory);

if (SUCCEEDED (hr))
{
   hr = cpSpObjectTokenCategory->GetId(&cpwszOldID);
}

if (SUCCEEDED (hr))
{
   CoTaskMemFree(cpwszOldID);
}


ISpObjectTokenCategory::GetDataKey (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectTokenCategory::GetDataKey

ISpObjectTokenCategory::GetDataKey gets the data key associated with a specific location.

HRESULT GetDataKey(
   SPDATAKEYLOCATION   spdkl,
   ISpDataKey        **ppDataKey
);

Parameters

spdkl
[in] The registry's top-level node to be searched.
ppDataKey
[out] The data key interface associated with the location spdkl.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_UNINITIALIZED | Data key interface is not initialized.
E_POINTER | ppDataKey is invalid or bad.
FAILED(hr) | Appropriate error message.

Example

The following code snippet retrieves the data key associated with the local computer registry for SPCAT_VOICES.

// Declare local identifiers:
HRESULT                           hr = S_OK;
CComPtr<ISpObjectTokenCategory>   cpSpObjectTokenCategory;
CComPtr<ISpDataKey>               cpSpDataKey;

hr = SpGetCategoryFromId(SPCAT_VOICES, &cpSpObjectTokenCategory);

if (SUCCEEDED (hr))
{
   hr = cpSpObjectTokenCategory->GetDataKey(SPDKL_LocalMachine, &cpSpDataKey);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpObjectTokenCategory::EnumTokens (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectTokenCategory::EnumTokens

ISpObjectTokenCategory::EnumTokens enumerates the tokens for the category by attempting to match specified requirements. Attributes, enumerations, and searches are discussed in Object Tokens and Registry Settings White Paper.

HRESULT EnumTokens(
   LPCWSTR               *pszReqAttribs,
   LPCWSTR               *pszOptAttribs,
   IEnumSpObjectTokens  **ppEnum
);

Parameters

pszReqAttribs
[in] The null terminated string of required attributes for the token.
pszOptAttribs
[in] The null terminated string of optional attributes for the token. The order in which the tokens are listed in ppEnum is based on the order they match pszOptAttribs.
ppEnum
[out] The enumerated list of tokens found.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_UNINITIALIZED | Data key interface is not initialized.
E_POINTER | At least one of the parameters is invalid or bad.
FAILED(hr) | Appropriate error message.

Example

The following code snippet demonstrates getting a complete enumerated token list. Since no specific requirement is given (pszReqAttribs and pszOptAttribs are NULL), all values are returned for SPCAT_VOICES.

// Declare local identifiers:
HRESULT                           hr = S_OK;
CComPtr<ISpObjectTokenCategory>   cpSpObjectTokenCategory;
CComPtr<IEnumSpObjectTokens>      cpSpEnumTokens;

hr = SpGetCategoryFromId(SPCAT_VOICES, &cpSpObjectTokenCategory);

if (SUCCEEDED (hr))
{
   hr = cpSpObjectTokenCategory->EnumTokens(NULL, NULL, &cpSpEnumTokens);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpObjectTokenCategory::SetDefaultTokenId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectTokenCategory::SetDefaultTokenId

ISpObjectTokenCategory::SetDefaultTokenId sets a specific token ID as the default for the category.

HRESULT SetDefaultTokenId(
   LPCWSTR    *pszTokenId
);

Parameters

pszTokenId
[in] The null-terminated string name of the token ID to be used as the default.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_UNINITIALIZED | Data key interface is not initialized.
E_INVALIDARG | pszTokenId is invalid or bad.
FAILED(hr) | Appropriate error message.

Remarks

The defaults are stored either directly in the category by setting the DefaultTokenID value in the category data key, or indirectly by the DefaultTokenIDLocation. Default tokens are discussed in Object Tokens and Registry Settings White Paper.


ISpObjectTokenCategory::GetDefaultTokenId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectTokenCategory::GetDefaultTokenId

ISpObjectTokenCategory::GetDefaultTokenId retrieves the default token ID for the category.

HRESULT GetDefaultTokenId(
   LPWSTR   **ppszCoMemTokenId
);

Parameters

ppszCoMemTokenId
[in] The null-terminated string name of the token ID used as the default. Must be released with CoTaskMemFree () when no longer needed.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_UNINITIALIZED | Data key interface is not initialized.
E_POINTER | ppszCoMemTokenId is invalid or bad.
FAILED(hr) | Appropriate error message.

Remarks

There is a hierarchy for returning a default token ID value. A default token has an attribute marked as DefaultTokenID. When a token is not explicitly marked as such, SAPI attempts to return the default from the user profile. If none exists there, SAPI returns a specially named token called DefaultdefaultTokenID for the category ID. Default tokens are discussed in Object Tokens and Registry Settings White Paper.


ISpObjectToken (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectToken

The ISpObjectToken interface handles object token entries.

An object token is an object representing a resource that is available on a computer, such as a voice, recognizer, or an audio input device. A token provides an application a simple way to inspect the various attributes of a resource without having to instantiate it. The Vendor of a Recognizer, and Gender of a Voice are examples of attributes of resources. An application can enumerate the various tokens that exist on the computer by using the SpEnumTokens helper function, or by using the ISpObjectTokenCategory::EnumTokens method to enumerate the tokens of a particular category. Applications can find the best token that matches certain attributes by using the SpFindBestToken function.

Conceptually, a token contains the following information:

  • An identifier that uniquely identifies the object token.
  • The language-independent name is the name that should be displayed wherever the name of the token is displayed. The implementer of the token may also choose to provide a set of language-dependent names in several languages.
  • The CLSID used to instantiate the object from the token.
  • A set of Attributes, which are the set of queriable values in a token. SAPI provides a mechanism to query for tokens whose attributes match certain values.

A token may also contain the following:

  • If a token has user interfaces (UIs), such as the properties of a Recognizer or a wizard to customize a Voice to display, the token will also contain the CLSID for the COM object used to instantiate each type of UI.
  • The set of Files from which SAPI returns the paths to all the associated files for the token.

Attributes are null-terminated strings forming a series of key-pair entries. This is usually in the form of definition relationships. For example, a token may be defined as:

"vendor=microsoft;language=409;someflag"

In this instance:

  • "vendor=microsoft" means a string exists under TokenID\attributes with name vendor and value "microsoft";
  • "language=409" means a string exists under TokenID\attributes with name language and value "409" (representing US English);
  • "someflag" means a string exists under TokenID\attributes with name someflag but has no additional information. Sometimes the presence or absence of the attribute name itself is indicative.

Implemented By
  • SpObjectToken object. This is the standard class used for all existing SAPI object tokens. The data for each object token is stored in the registry.
  • Applications or engines can implement this interface directly to provide a custom object token implementation. For instance, this could be used to avoid storing object token data in the registry, or to provide the ability for object tokens to be downloaded from a server. In this case IEnumSpObjectTokens would also need to be implemented so that the new object tokens to be enumerated.
How Created
  • Applications will normally create object tokens from an object token enumerator or helper function, rather than by directly creating them.
  • Various API methods also return an object token referring to a specific type of resource, e.g., ISpRecognizer::GetRecognizer returns the object token associated with the current recognition engine; ISpRecognizer::GetRecoProfile returns the object token referring to the current recognition profile; and ISpVoice::GetVoice returns the object token referring to the current TTS engine.

ISpObjectToken inherits from ISpDataKey.

Object tokens are discussed in more detail in the Object Tokens and Registry Settings White Paper.

Methods in Vtable Order

ISpObjectToken Methods | Description
SetId | Sets the category identifier for object token.
GetId | Retrieves the object identifier for an object token.
GetCategory | Retrieves the category for a specified token if one is available.
CreateInstance | Creates an instance of an object.
GetStorageFileName | Retrieves the object token file name.
RemoveStorageFileName | Removes the object token file name.
Remove | Removes an object token.
IsUISupported | Determines if the UI associated with the object is supported.
DisplayUI | Displays the UI associated with the object.
MatchesAttributes | Determines if an object token supports a specified attribute.


ISpObjectToken::SetId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectToken::SetId

ISpObjectToken::SetId sets the CategoryId for object token.

This may be called only once.

HRESULT SetId(
   LPCWSTR       *pszCategoryId,
   LPCWSTR       *pszTokenId,
   BOOL           fCreateIfNotExist
);

Parameters

pszCategoryId
[in] The null-terminated string name of category to set.
pszTokenId
[in] The null-terminated string name of token to set.
fCreateIfNotExist
[in] A Boolean indicating the object is to be created if not currently existing. TRUE allows the creation; FALSE does not.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_ALREADY_INITIALIZED | Category interface is already initialized.
SPERR_TOKEN_DELETED | Key has been deleted.
E_INVALIDARG | Either pszCategoryId and/or pszTokenId is invalid or bad.
FAILED(hr) | Appropriate error message.

Notes

CategoryIds appear in the fully qualified form as:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Recognizers

The only acceptable HKEYs are:

HKEY_CLASSES_ROOT,

HKEY_CURRENT_USER,

HKEY_LOCAL_MACHINE,

HKEY_CURRENT_CONFIG


ISpObjectToken::GetID (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectToken::GetId

ISpObjectToken::GetId retrieves the object identifier for an object token. This identifier can be used later to recreate a token instance.

HRESULT GetId(
   LPWSTR    **ppszCoMemTokenId
);

Parameters

ppszCoMemTokenId
Address of a pointer to a null-terminated string that receives the identifier for the token object. The caller must call CoTaskMemFree() to free the string pointer.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppszCoMemTokenId is invalid or bad.
E_OUTOFMEMORY | Exceeded available memory.
SPERR_UNINITIALIZED | TokenId interface is not initialized.
FAILED(hr) | Appropriate error message.


ISpObjectToken::GetCategory (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectToken::GetCategory

ISpObjectToken::GetCategory retrieves the category for a specified token if one is available.

HRESULT GetCategory(
   ISpObjectTokenCategory   **ppTokenCategory
);

Parameters

ppTokenCategory
[out] The category interface for the token. ppTokenCategory must be freed when no longer required.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppTokenCategory is invalid or bad.
SPERR_UNINITIALIZED | Token does not have a category.
FAILED(hr) | Appropriate error message.


ISpObjectToken::CreateInstance (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectToken::CreateInstance

ISpObjectToken::CreateInstance creates an instance of an object.

HRESULT CreateInstance(
   IUnknown   *pUnkOuter,
   DWORD       dwClsContext,
   REFIID      riid,
   void      **ppvObject
);

Parameters

pUnkOuter
[in] If the object is being created as part of an aggregate, this is a pointer to the controlling IUnknown interface of the aggregate. Otherwise, pUnkOuter must be NULL.
dwClsContext
[in] Context in which the code that manages the newly created object will run. It should be one of the following values:
  • CLSCTX_INPROC_SERVER
  • CLSCTX_INPROC_HANDLER
  • CLSCTX_LOCAL_SERVER
  • CLSCTX_REMOTE_SERVER
riid
[in] Reference to the identifier of the interface used to communicate with the newly created object. If pUnkOuter is NULL, this parameter is frequently the IID of the initializing interface; if pUnkOuter is non-NULL, riid must be IID_IUnknown.
ppvObject
[out, iid_is(riid)] Address of pointer variable that receives the interface pointer requested in riid. Upon successful return, ppvObject contains the requested interface pointer. If the object does not support the interface specified in riid, the implementation must set ppvObject to NULL.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppvObject is invalid or bad.
E_INVALIDARG | pUnkOuter is invalid or bad.
SPERR_UNINITIALIZED | Either the data key or the token delegator interface is not initialized.
SPERR_TOKEN_DELETED | Key has been deleted.
FAILED(hr) | Appropriate error message.

Remarks

This method is used to create the underlying object that the object token represents. This method looks at the CLSID value stored in the object token and creates a COM object from this CLSID.

For example, when this method is called on an object token from the audio input category, an audio object that implements ISpStreamFormat will be created and returned.

This method is not used to create speech recognition or text-to-speech engines. Instead, an SpRecognizer or SpVoice object is created and the engine is then created by passing an object token to the ISpRecognizer::SetRecognizer or ISpVoice::SetVoice methods.

Example

The following code snippet creates an InProc server instance.

// Declare local identifiers:
HRESULT                        hr = S_OK;
CComPtr<ISpObjectWithToken>    cpObjectWithToken;
CComPtr<ISpObjectToken>        cpObjectToken;

hr = SpGetDefaultTokenFromCategoryId(SPCAT_VOICES, &cpObjectToken);

if (SUCCEEDED (hr))
{
   hr = cpObjectToken->CreateInstance(NULL, CLSCTX_INPROC_SERVER, IID_ISpObjectWithToken, (void **)&cpObjectWithToken);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpObjectToken::GetStorageFileName (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectToken::GetStorageFileName

ISpObjectToken::GetStorageFileName retrieves the object token file name from the registry.

HRESULT GetStorageFileName(
    REFCLSID      clsidCaller,
    LPCWSTR      *pszValueName,
    LPCWSTR      *pszFileNameSpecifier,
    ULONG         nFolder,
    LPWSTR      **ppszFilePath
);

Parameters

clsidCaller
[in] Globally unique identifier (GUID) of the calling object. The registry is searched for an entry key name of clsidCaller, and then a corresponding "Files" subkey. If the registry entry is not present, one is created.
pszValueName
[in] The name of the attribute file for the registry entry of clsidCaller. This attribute stores the location of the resource file.
pszFileNameSpecifier
[in] The specifier that is either NULL or a path/file name for storage file.

If this starts with "X:\" or "\\" it is assumed to be a full path.

Otherwise it is assumed to be relative to special folders given in the nFolder parameter.

If it ends with a '\', or is NULL a unique file name will be created. The file name will be something like:
"SP_7454901D23334AAF87707147726EC235.dat". "SP_" and ".dat" are the default prefix name and file extension name. The numbers in between are generated guid number to make sure the file name is unique.

If the name contains a %d the %d is replaced by a number to give a unique file name. The default file extension is .dat, the user can specify anything else.

Intermediate directories are created.

If a relative file is being used the value stored in the registry includes the nFolder value as %nFolder% before the rest of the path.

nFolder
[in] A CSIDL value that identifies the folder whose path is to be retrieved. The user can force the creation of a folder by combining the folder's CSIDL with CSIDL_FLAG_CREATE. If pszFileNameSpecifier is NULL or "\", nFolder must have a specified CSIDL folder combined with CSIDL_FLAG_CREATE if the user wants to force to create the file.
ppszFilePath
[out] Address of a pointer to the null-terminated string that receives the file path information. Must be freed when no longer required.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppszFilePath is invalid or bad.
E_OUTOFMEMORY | Exceeded available memory.
S_FALSE | A new file was created.
E_INVALIDARG | pszValueName is invalid or bad.
SPERR_UNINITIALIZED | Either the data key or the token delegate interface is uninitialized.
SPERR_TOKEN_DELETED | Key has been deleted.
FAILED(hr) | Appropriate error message.

Example

The following code snippet creates and removes two token objects for two test files.

// Declare local identifiers:
HRESULT                   hr = S_OK;
CComPtr<ISpObjectToken>   cpObjectToken;
GUID                      guid0;
GUID                      guid1;
WCHAR                     *cpFileName;
WCHAR                     *cpFileName2;
ULONG                     CSIDL_LOCAL_APPDATA = 28;
ULONG                     CSIDL_FLAG_CREATE = 32768;

// Get the default text-to-speech engine token.
hr = SpGetDefaultTokenFromCategoryId(SPCAT_VOICES, &cpObjectToken);

if (SUCCEEDED (hr))
{
   hr = CoCreateGuid(&guid0);
}

if (SUCCEEDED (hr))
{
   hr = CoCreateGuid(&guid1);
}

if (SUCCEEDED (hr))
{
   // Create file with default format and store it in folder that
   // contains application-specific data that does not roam.
   hr = cpObjectToken->GetStorageFileName(guid0, L"TestFile", NULL, CSIDL_FLAG_CREATE|CSIDL_LOCAL_APPDATA, &cpFileName);
}

if (SUCCEEDED (hr))
{
   // Remove object token.
   hr = cpObjectToken->Remove(&guid0);
}

if (SUCCEEDED (hr))
{
   // Create file to be stored under C:\Program Files and that is to
   // have name like MyData "7412341D23334A7321707145534EC235.dump.
   hr = cpObjectToken->GetStorageFileName(guid1, L"TestFile2", L"c:\\Program Files\\MyData%d.dump", CSIDL_FLAG_CREATE, &cpFileName2);
}
if (SUCCEEDED (hr))
{
   // Remove object token.
   hr = cpObjectToken->Remove(&guid1);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpObjectToken::RemoveStorageFileName (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectToken::RemoveStorageFileName

ISpObjectToken::RemoveStorageFileName removes the object token file name.

HRESULT RemoveStorageFileName(
   REFCLSID       clsidCaller,
   LPCWSTR       *pszKeyName,
   BOOL           fDeleteFile
);

Parameters

clsidCaller
[in] Globally unique identifier (GUID) of the calling object.
pszKeyName
[in] Address of a null-terminated string containing the registry key name.
fDeleteFile
[in] Value specifying if the file should be deleted. TRUE deletes the file afterward; FALSE does not.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszKeyName is invalid or bad.
SPERR_UNINITIALIZED | Either the data key or token delegate interface is not initialized.
SPERR_TOKEN_DELETED | Key has been deleted.
FAILED(hr) | Appropriate error message.

Example

The following code snippet creates a test file, removes it and manually deletes it. It may also have been deleted automatically by setting fDeleteFile to TRUE.

// Declare local identifiers:
HRESULT                   hr = S_OK;
CComPtr<ISpObjectToken>   cpObjectToken;
GUID                      guid0;
WCHAR                     *cpFileName;
ULONG                     CSIDL_LOCAL_APPDATA = 28;
ULONG                     CSIDL_FLAG_CREATE = 32768;

// Get the default text-to-speech engine token.
hr = SpGetDefaultTokenFromCategoryId(SPCAT_VOICES, &cpObjectToken);

if (SUCCEEDED (hr))
{
   hr = CoCreateGuid(&guid0);
}

if (SUCCEEDED (hr))
{
   // Create file with default format and store it in folder that
   // contains application-specific data that does not roam.
   hr = cpObjectToken->GetStorageFileName(guid0, L"TestFile", NULL, CSIDL_FLAG_CREATE|CSIDL_LOCAL_APPDATA, &cpFileName);
}

if (SUCCEEDED (hr))
{
   // Remove object token.
   hr = cpObjectToken->RemoveStorageFileName(guid0, L"TestFile", false);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpObjectToken::Remove (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectToken::Remove

ISpObjectToken::Remove removes an object token.

HRESULT Remove(
   const CLSID  *pclsidCaller
);

Parameters

pclsidCaller
[in] Address of the identifier associated with the object token to remove. If pclsidCaller is NULL, the entire token is removed; otherwise, only the specified section is removed.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pclsidCaller is invalid or bad.
SPERR_UNINITIALIZED | The token ID interface is uninitialized.
SPERR_TOKEN_DELETED | Key has been deleted.
FAILED(hr) | Appropriate error message.

Example

The following code snippet creates and removes a token object for a test file.

// Declare local identifiers:
HRESULT                   hr = S_OK;
CComPtr<ISpObjectToken>   cpObjectToken;
GUID                      guid0;
WCHAR                     *cpFileName;
ULONG                     CSIDL_LOCAL_APPDATA = 28;
ULONG                     CSIDL_FLAG_CREATE = 32768;

// Get the default text-to-speech engine token.
hr = SpGetDefaultTokenFromCategoryId(SPCAT_VOICES, &cpObjectToken);

if (SUCCEEDED (hr))
{
   hr = CoCreateGuid(&guid0);
}

if (SUCCEEDED (hr))
{
   // Create file with default format and store it in folder that
   // contains application-specific data that does not roam.
   hr = cpObjectToken->GetStorageFileName(guid0, L"TestFile", NULL, CSIDL_FLAG_CREATE|CSIDL_LOCAL_APPDATA, &cpFileName);
}

if (SUCCEEDED (hr))
{
   // Remove object token.
   hr = cpObjectToken->Remove(&guid0);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpObjectToken::IsUISupported (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectToken::IsUISupported

ISpObjectToken::IsUISupported determines if the user interface (UI) associated with the object is supported.

>
[local] HRESULT IsUISupported(
    LPCWSTR      *pszTypeOfUI,
    void         *pvExtraData,
    ULONG         cbExtraData,
    IUnknown     *punkObject,
    BOOL         *pfSupported
);

Parameters

pszTypeOfUI
[in] Address of the null-terminated string containing the UI type that is being queried. Must be a SPDUI_xxx type.
pvExtraData
[in] Pointer to additional information needed for the object. See Remarks section.
cbExtraData
[in] Size, in bytes, of the ExtraData.
punkObject
[in] Address of the IUnknown interface pointer. See Remarks section.
pfSupported
[out] Address of a variable that receives the value indicating support for the interface. This value is set to TRUE when this interface is supported, and FALSE when it is not. If this value is TRUE, but the return code is S_FALSE, the UI type (guidTypeOfUI) is supported, but not with the current parameters or run-time environment. Check with the implementer of the UI object to verify run-time requirements.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | The UI is supported but not with the current run-time environment or parameters.
E_INVALIDARG | One of the parameters is invalid or bad.
SPERR_UNINITIALIZED | Either the data key or token delegate interface is not initialized.
SPERR_TOKEN_DELETED | Key has been deleted.
FAILED(hr) | Appropriate error message.

Remarks

pvExtraData and punkObject Parameters: When asking an ISpObjectToken to display a particular piece of UI, the UI object may require extra functionality that only it understands. Common implementation practice for accessing this functionality is to QueryInterface off of a known IUnknown interface. For example, to display a Speech Recognition Training UI requires a specific SR engine.

Example

The following code snippet illustrates the use of ISpObjectToken::IsUISupported.

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpObjectToken>    cpObjectToken;
CComPtr<ISpVoice>          cpVoice;
BOOL                       fSupported;
HWND                       hwndParent;

// Get the default text-to-speech engine object token.
hr = SpGetDefaultTokenFromCategoryId(SPCAT_VOICES, &cpObjectToken);

if (SUCCEEDED(hr))
{
   // Create the engine object based on the object token.
   hr = SpCreateObjectFromToken(cpObjectToken, &cpVoice);
}

if (SUCCEEDED(hr))
{
   // Check if the default engine object has UI for Properties.
   hr = cpObjectToken->IsUISupported(SPDUI_EngineProperties, NULL, NULL, cpVoice, &fSupported);
}

if (SUCCEEDED(hr))
{
   // If default engine object has UI for
   // Engine Properties, display UI--
   if (fSupported == TRUE)
   {
      hr = cpObjectToken->DisplayUI(hwndParent, L"My App's Caption", SPDUI_EngineProperties, NULL, NULL, cpVoice);
   }
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpObjectToken::DisplayUI (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectToken::DisplayUI

ISpObjectToken::DisplayUI displays the user interface (UI) associated with the object.

[local] HRESULT DisplayUI(
   HWND           hwndParent,
   LPCWSTR       *pszTitle,
   LPCWSTR        pszTypeOfUI,
   void          *pvExtraData,
   ULONG          cbExtraData,
   IUnknown      *punkObject
);

Parameters

hwndParent
[in] Specifies the handle of the parent window.
pszTitle
[in] Address of a null-terminated string containing the window title.
pszTypeOfUI
[in] Address of the null-terminated string containing the UI type that is being queried. Must be a SPDUI_xxx type.
pvExtraData
[in] Pointer to additional information needed for the object.
cbExtraData
[in] Size, in bytes, of the ExtraData. See Remarks section.
punkObject
[in] Address of the IUnknown interface pointer. See Remarks section.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | The UI is supported but not with the current run-time environment or parameters.
E_INVALIDARG | One of the parameters is invalid or bad.
SPERR_UNINITIALIZED | Either the data key or token delegate interface is not initialized.
SPERR_TOKEN_DELETED | Key has been deleted.
FAILED(hr) | Appropriate error message.

Remarks

pvExtraData and punkObject Parameters: When requesting an ISpObjectToken to display a particular piece of UI, the UI object may require extra functionality. Common implementation practice for accessing this functionality is to QueryInterface from a known IUnknown interface. For example, asking to display Speech Recognition Training UI requires the use of a specific SR engine.

The best practice for using ISpObjectToken::DisplayUI is to call ISpObjectToken::IsUISupported with a specific UI type before calling DisplayUI.

The call to DisplayUI is synchronous and the call will not return until the UI has been closed.

Example

The following code snippet illustrates the use of ISpObjectToken::DisplayUI.

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpObjectToken>    cpObjectToken;
CComPtr<ISpVoice>          cpVoice;
BOOL                       fSupported;
HWND                       hwndParent;

// Get the default text-to-speech engine object token.
hr = SpGetDefaultTokenFromCategoryId(SPCAT_VOICES, &cpObjectToken);

if (SUCCEEDED(hr))
{
   // Create the engine object based on the object token.
   hr = SpCreateObjectFromToken(cpObjectToken, &cpVoice);
}

if (SUCCEEDED(hr))
{
   // Check if the default engine object has UI for Properties.
   hr = cpObjectToken->IsUISupported(SPDUI_EngineProperties, NULL, NULL, cpVoice, &fSupported);
}

if (SUCCEEDED(hr))
{
   // If default engine object has UI for
   // Engine Properties, display UI--
   if (fSupported == TRUE)
   {
      hr = cpObjectToken->DisplayUI(hwndParent, L"My App's Caption", SPDUI_EngineProperties, NULL, NULL, cpVoice);
   }
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpObjectToken::MatchesAttributes (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectToken::MatchesAttributes

ISpObjectToken::MatchesAttributes determines if an object token supports a specified attribute.

HRESULT MatchesAttributes(
   const WCHAR   *pszAttributes,
   BOOL          *pfMatches
);

Parameters

pszAttributes
[in] Address of the null-terminated string specifying the object token attribute to match.
pfMatches
[out] Address of a variable that receives the value indicating a match of the object token attribute specified in pszAttributes. This value is set to TRUE when the object token attribute matches, and FALSE when it does not match.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
SPERR_UNINITIALIZED | The object has not been properly initialized.
FAILED(hr) | Appropriate error message.


IEnumSpObjectTokens (Microsoft Speech Platform)

 Microsoft Speech Platform

IEnumSpObjectTokens

The IEnumSpObjectTokens interface is used to enumerate speech object tokens.

Associated Class IDs

The following class IDs (CLSID) may be used with this interface. A complete CLSID listing for all interfaces is in the Class IDs section.

    CLSID_SpMMAudioEnum

Methods in Vtable Order

IEnumSpObjectTokens Methods | Description
Next | Retrieves the next object token in the enumeration sequence.
Skip | Skips a specified number of object tokens in the enumeration sequence.
Reset | Resets the enumeration sequence to the beginning.
Clone | Creates a new enumerator object with the same items.
Item | Locates a specific token in the enumeration.
GetCount | Retrieves the number of object tokens contained in the enumeration sequence.


IEnumSpObjectTokens::Next (Microsoft Speech Platform)

 Microsoft Speech Platform

IEnumSpObjectTokens::Next

IEnumSpObjectTokens::Next retrieves the next object token in the enumeration sequence.

If there are fewer than the requested number of elements left in the sequence, the remaining elements are retrieved.

HRESULT Next(
   ULONG                                                             celt,
   [out, size_is(celt), length_is(*pceltFetched)] ISpObjectToken   **pelt,
   ULONG                                                            *pceltFetched
);

Parameters

celt
[in] The number of object tokens to retrieve.
pelt
[out] Address of an array that receives ISpObjectToken pointers. If an error value is returned, no entries in the array are valid.
pceltFetched
[out] Address of a variable that receives the number of ISpObjectToken pointers actually copied to the array. This parameter cannot be NULL if celt is greater than one. If this parameter is NULL, celt must be one.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER One of the following errors was encountered:
pelt is bad or invalid,
pceltFetched is bad or invalid,
pceltFetched is bad and celt is greater than one.
E_INVALIDARG | celt is zero.
SPERR_UNINITIALIZED | Attribute parser interface is not initialized.
S_FALSE | celt is greater than the number of objects available.
FAILED (hr) | Appropriate error message.


IEnumSpObjectTokens::Skip (Microsoft Speech Platform)

 Microsoft Speech Platform

IEnumSpObjectTokens::Skip

IEnumSpObjectTokens::Skip skips a specified number of object tokens in the enumeration sequence.

HRESULT Skip(
   ULONG   celt
);

Parameters

celt
[in] Number of object tokens to skip in the enumeration sequence.

Return values

Value | Description
S_OK | Number of elements skipped was celt.
S_FALSE | Number of elements skipped was less than celt.
SPERR_UNINITIALIZED | Attribute parser interface is not initialized.
FAILED (hr) | Appropriate error message.


IEnumSpObjectTokens::Reset (Microsoft Speech Platform)

 Microsoft Speech Platform

IEnumSpObjectTokens::Reset

IEnumSpObjectTokens::Reset resets the enumeration sequence to the beginning.

HRESULT Reset ( void );

Parameters

None

Return values

Value | Description
S_OK | Method completed successfully.
SPERR_UNINITIALIZED | Attribute parser interface is not initialized.


IEnumSpObjectTokens::Clone (Microsoft Speech Platform)

 Microsoft Speech Platform

IEnumSpObjectTokens::Clone

IEnumSpObjectTokens::Clone creates a new enumerator object with the same items.

Returns a new enumerator object with the same items but an independent index. The items in the clone are not guaranteed to be in the same order as the original enumerator.

HRESULT Clone(
   IEnumSpObjectTokens   **ppEnum
);

Parameters

ppEnum
[out] Address of the IEnumSpObjectTokens pointer variable that receives the interface pointer to the cloned enumerator. Using Clone, it is possible to record a particular point in the enumeration sequence and then return to that point at a later time. The enumerator returned is of the same interface type as the one being cloned.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_UNINITIALIZED | Attribute parser interface is not initialized.
FAILED (hr) | Appropriate error message.


IEnumSpObjectTokens::Item (Microsoft Speech Platform)

 Microsoft Speech Platform

IEnumSpObjectTokens::Item

IEnumSpObjectTokens::Item locates a specific token in the enumeration.

HRESULT Item(
   ULONG             Index,
   ISpObjectToken  **ppToken
);

Parameters

Index
[in] Value indicating which token in the enumeration sequence to locate.
ppToken
[out] Address of an ISpObjectToken interface pointer.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_NO_MORE_ITEMS | Index is greater than the amount of items available.
E_POINTER | ppToken is bad or invalid.
SPERR_UNINITIALIZED | Attribute parser interface is not initialized.
FAILED (hr) | Appropriate error message.


IEnumSpObjectTokens::GetCount (Microsoft Speech Platform)

 Microsoft Speech Platform

IEnumSpObjectTokens::GetCount

IEnumSpObjectTokens::GetCount retrieves the number of object tokens contained in the enumeration sequence.

HRESULT GetCount(
   ULONG   *pulCount
);

Parameters

pulCount
[out] The number of object token items contained in the enumeration sequence.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pulCount is bad or invalid.
SPERR_UNINITIALIZED | Attribute parser interface is not initialized.
FAILED (hr) | Appropriate error message.


ISpObjectWithToken (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectWithToken

Any object associated with an object token implements the ISpObjectWithToken interface. When the method ISpObjectToken::CreateInstance is called on the object token, SAPI creates the associated object. If this object implements ISpObjectWithToken, the SetObjectToken method will be called, passing in a reference to the object token.

After SAPI calls ISpObjectWithToken::SetObjectToken, a token object is created and its data may be accessed.

Applications do not need to implement this interface, but engine, lexicon, or custom audio developers may implement it in order to access their object token data.

Implemented By
  • SpMMAudioEnum
  • SpRecPlayAudio
  • SpUnCompressedLexicon
  • SpCompressedLexicon

Methods in Vtable Order

ISpObjectWithToken Methods | Description
SetObjectToken | Binds the instance object to the specified token.
GetObjectToken | Retrieves an object token.


ISpObjectWithToken::SetObjectToken (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectWithToken::SetObjectToken

ISpObjectWithToken::SetObjectToken binds the instance object to the specified token.

HRESULT SetObjectToken(
   ISpObjectToken  *pToken
);

Parameters

pToken
[in] The token interface pointer this instance object is to combine with.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pToken is invalid or bad.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.


ISpObjectWithToken::GetObjectToken (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpObjectWithToken::GetObjectToken

ISpObjectWithToken::GetObjectToken retrieves an object token.

HRESULT GetObjectToken(
   ISpObjectToken   **ppToken
);

Parameters

ppToken
[out] Address of an ISpObjectToken interface that receives the object token.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppToken is invalid or bad.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.


ISpResourceManager (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpResourceManager

The ISpResourceManager interface provides access to the shared resources between different speech components in the same process. The object CLSID_SpResourecManager is a COM singleton. That is, the same resource manager will be shared by all clients in a single process that uses CoCreateInstance to create the object with CLSID_SpResourceManager. This allows for a common point of control for sharing other COM objects.

Applications and engines do not need to use or implement this interface.

This interface inherits from IServiceProvider. The IServiceProvider interface supports a single method, QueryService, which provides access to objects in the resource manager.

Associated Class IDs

The following class IDs (CLSID) may be used with this interface. A complete CLSID listing for all interfaces is in the Class IDs section.

    CLSID_SpResourceManager

Methods in Vtable Order

ISpResourceManager Methods | Description
SetObject | Adds a service object to the current service list.
GetObject | Retrieves a service object from the current service list, or creates one if it does not exist.


ISpResourceManager::SetObject (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpResourceManager::SetObject

ISpResourceManager::SetObject adds a COM object to the current service list. If an object is already set for the specified service, the ISpResourceManager::SetObject method will replace the current object with the new one. If pUnkObject is NULL, the current service object is removed.

HRESULT SetObject(
   REFGUID     guidServiceId,
   IUnknown   *pUnkObject
);

Parameters

guidServiceId
[in] The unique identifier of the service.
pUnkObject
[in] Address of the IUnknown interface of the object that is setting the service. Any existing service object is removed if this parameter is NULL.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pUnkObject is bad or invalid.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.


ISpResourceManager::GetObject (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpResourceManager::GetObject

ISpResourceManager::GetObject retrieves a service object from the current service list, or creates one if it does not exist.

HRESULT GetObject(
   REFGUID    guidServiceId,
   REFCLSID   ObjectCLSID,
   REFIID     ObjectIID,
   BOOL       fReleaseWhenNoRefs,
   void     **ppObject
);

Parameters

guidServiceId
[in] The unique identifier of the service.
ObjectCLSID
[in] Class identifier of the object.
ObjectIID
[in] Identifier of interface to return in ppObject
fReleaseWhenNoRefs
[in] Boolean indicating whether the object should be freed when the last client outside of the resource manager releases the object. If this flag is set, the object specified by ObjectCLSID must support aggregation.
ppObject
[out] Address of a pointer that receives the interface pointer of the service.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
E_POINTER | ppObject is bad or invalid.
REGDB_E_CLASSNOTREG | Class is not registered.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.

Remarks

If the object does not exist, the ObjectCLSID parameter will be used to CoCreateInstance the object. This functionality allows multiple threads to ensure that a single shared object is created atomically by the resource manager. If the fReleaseWhenNoRefs flag is set to TRUE, the final release of the object will remove it from the service list. If fReleaseWhenNoRefs is FALSE, the service will remain in the service list until the resource manager is released or the service is explicitly removed through a SetObject call.


Speech Recognition Interfaces (Microsoft Speech Platform)

 Microsoft Speech Platform

Speech Recognition interfaces

The following section covers:

  • ISpRecoCategory
  • ISpRecoContext
  • ISpRecoContext2
  • ISpRecoGrammar
  • ISpRecoGrammar2
  • ISpRecoResult
  • ISpRecoResult2
  • ISpRecognizer
  • ISpRecognizer2
  • ISpRecognizer3
  • ISpPhrase
  • ISpPhrase2
  • ISpPhraseAlt
  • ISpSerializeState
  • ISpXMLRecoResult
  • ISpProperties


ISpRecoCategory (Speech API (SAPI) SDK 5.4)

 Microsoft Speech SDK Version 5.4

ISpRecoCategory

New in Microsoft Speech Platform

The ISpRecoCategory interface enables an application to determine the type of a category. For more information, see SPCATEGORYTYPE.

Methods in Vtable Order

ISpRecoCategory Methods | Description
GetType | Returns the type of a category.


ISpRecoCategory::GetType (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoCategory::GetType

New in Microsoft Speech Platform

ISpRecoCategory::GetType returns the type of a category.

HRESULT GetType(
   SPCATEGORYTYPE   *peCategoryType
);

Parameters

peCategoryType
[out] A pointer to memory that will receive a value of the SPCATEGORYTYPE enumerated type.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | The memory pointed to by peCategoryType cannot be written to.
FAILED(hr) | Appropriate error message.


ISpRecoContext (Speech API (SAPI) SDK 5.4)

 Microsoft Speech SDK Version 5.4

ISpRecoContext

The ISpRecoContext interface enables applications to create different functional views or contexts of the SR engine. Each ISpRecoContext object can take interest in different SR events (see also ISpEventSource and SPEVENTENUM) and use different recognition grammars (see also ISpRecoGrammar). Applications must have at least one ISpRecoContext instance to receive recognitions. Applications can also create multiple ISpRecoContext instances to separate different types of recognition with their application. For example, a multiple-document-interface (MDI) application could associate a different ISpRecoContext instance with each document pane to localize the grammar and support and event processing.

A new ISpRecoContext object can be created by calling ISpRecognizer::CreateRecoContext.

To use a shared recognizer (see description of ISpRecognizer), an application can easily create a shared ISpRecoContext by calling ::CoCreateInstance with CLSID_SpSharedRecoContext.

Associated Class IDs

The following class IDs (CLSID) may be used with this interface. A complete CLSID listing for all interfaces is in the Class IDs section.

    CLSID_SpSharedRecoContext

Methods in Vtable Order

ISpRecoContext Methods | Description
ISpEventSource | Inherits from ISpEventSource and those methods are accessible from ISpRecoContext.
GetRecognizer | Returns a reference to the current recognizer object associated with this context.
CreateGrammar | Creates an SpGrammar object.
GetStatus | Retrieves current state information associated with a context.
GetMaxAlternates | Retrieves the maximum number of alternates that will be generated for command and control grammars.
SetMaxAlternates | Sets the maximum number of alternates returned for command and control grammars.
SetAudioOptions | Sets the audio options for results from this recognition context.
GetAudioOptions | Retrieves the audio options for the context.
DeserializeResult | Creates a new result object from a serialized result.
Bookmark | Sets a bookmark within the current recognition stream.
SetAdaptationData | Passes a block of text to the SR engine which can be used to adapt the active language models.
Pause | Pauses the engine object to synchronize with the SR engine.
Resume | Resumes the SR engine from the paused state and restarts the recognition process.
SetVoice | Sets the associated ISpVoice to this context.
GetVoice | Retrieves a reference to the associated ISpVoice object.
SetVoicePurgeEvent | Sets the SR engine events that stop audio output, and purges the current speaking queue.
GetVoicePurgeEvent | Retrieves the set of SR engine events that stop audio output, and purges the current speaking queue.
SetContextState | Sets the state of the recognition context.
GetContextState | Retrieves the state of the recognition context.


ISpRecoContext::GetRecognizer (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::GetRecognizer

ISpRecoContext::GetRecognizer returns a reference to the current recognizer object associated with this context.

HRESULT GetRecognizer(
   ISpRecognizer   **ppRecognizer
);

Parameters

ppRecognizer
[out] Address of a pointer that receives the ISpRecognizer interface. The application must call IUnknown::Release when finished with the interface.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Invalid pointer.
FAILED (hr) | Appropriate error message.

Example

The following code snippet illustrates the use of ISpRecoContext::GetRecognizer with a shared context

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;
CComPtr<ISpRecognizer>     cpRecognizer;

// Create a shared recognition context.
hr = cpRecoContext.CoCreateInstance(CLSID_SpSharedRecoContext);

if (SUCCEEDED(hr))
{
   // Get a reference to the associated recognizer.
   hr = cpRecoContext->GetRecognizer(&cpRecognizer);
}

if (SUCCEEDED(hr))
{
   // Assert that our shared context has a shared recognizer.
   hr = cpRecognizer->IsSharedInstance();
}

if (SUCCEEDED(hr))
{
   // Do something here.
}


ISpRecoContext::CreateGrammar (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::CreateGrammar

ISpRecoContext::CreateGrammar creates an SpRecoGrammar object.

HRESULT CreateGrammar(
   ULONGLONG          ullGrammarId,
   ISpRecoGrammar   **ppGrammar
);

Parameters

ullGrammarId
[in] Specifies the grammar identifier. The identifier is used by the application and is not required. This identifier is associated with all result objects from the grammar (see SPPHRASE.ullGrammarID).
ppGrammar
[out] Address of a pointer which receives the ISpRecoGrammar object. The application must call IUnknown::Release on the object when finished using it.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppGrammar is invalid.
E_OUTOFMEMORY | Not enough system memory to create a grammar object.
SPERR_SR_ENGINE_EXCEPTION | An exception was thrown by the SR engine.
FAILED(hr) | Appropriate error message.

Example

The following code snippet illustrates the use of ISpRecoContext::CreateGrammar.

// Declare local identifiers:
HRESULT	                   hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;
CComPtr<ISpRecoResult>     cpRecoResult;
CComPtr<ISpRecoGrammar>    cpRecoGrammar;
ULONGLONG                  ullGramId = 1;
SPPHRASE                   *pPhrase;
const WCHAR                *MY_CFG_FILENAME = L"Foo.cfg";    // Dummy file name.

// Create a grammar object.
hr = cpRecoContext->CreateGrammar(ullGramId, &cpRecoGrammar);

if (SUCCEEDED(hr))
{
   // Load a cfg from a file (constant points to dummy file name).
   hr = cpRecoGrammar->LoadCmdFromFile(MY_CFG_FILENAME, SPLO_STATIC);
}

if (SUCCEEDED(hr))
{
   // Activate the top-level rules.
   hr = cpRecoGrammar->SetRuleState(NULL, NULL, SPRS_ACTIVE);
}

if (SUCCEEDED(hr))
{
   // Get a recognition.
   // ...
}

// Get the recognized phrase from the recognition result object.
hr = cpRecoResult->GetPhrase(&pPhrase);

if (SUCCEEDED(hr))
{
   // Check the grammar id of the recognition result.
   _ASSERT(GRAM_ID == pPhrase->ullGrammarID);

   // Release system resources.
   ::CoTaskMemFree(&pPhrase);

}


ISpRecoContext::GetStatus (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::GetStatus

ISpRecoContext::GetStatus retrieves current state information associated with a context (e.g., last SR engine requested UI, audio signal status, etc.).

HRESULT GetStatus(
   SPRECOCONTEXTSTATUS   *pStatus
);

Parameters

pStatus
[out] Address of the SPRECOCONTEXTSTATUS structure that receives the context state information.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pStatus is invalid or bad.
FAILED (hr) | Appropriate error message.

Remarks

A graphical application that is interested in SPEI_REQUEST_UI events from the SR engine can call ISpRecoContext::GetStatus, and check the szRequestTypeOfUI field to check the last requested UI-type. After the application has called ISpRecognizer::DisplayUI, the SR engine can clear the szRequestTypeOfUI field.

An application can also periodically query the recognition context status to check the audio signal quality (see also SPINTERFERENCE) and respond appropriately. An application can prompt the user to access the SR engine's microphone training UI to improve the audio signal quality, or prompt the user to modify the audio settings using Speech properties in Control Panel.

Example

The following code snippet illustrates the use of ISpRecoContext::GetStatus for responding to SR engine UI requests.

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;
CComPtr<ISpRecognizer>     cpRecognizer;
SPRECOCONTEXTSTATUS        contextStatus;
BOOL                       fSupported;

// Assume UI request [SPEI_REQUEST_UI] has been received.

// Check what kind of UI the SR Engine wants.
hr = cpRecoContext->GetStatus(&contextStatus);

if (SUCCEEDED(hr))
{
   // Get a reference to the SR Engine.
   hr = cpRecoContext->GetRecognizer(&cpRecognizer);
}

if (SUCCEEDED(hr))
{
   // Sanity check that the UI type is supported.
   hr = cpRecognizer->IsUISupported(contextStatus.szRequestTypeOfUI, NULL, NULL, &fSupported);
}

if (SUCCEEDED(hr))
{
   // Ask the SR engine to display the UI and use the default window title.
   hr = cpRecognizer->IsUISupported(contextStatus.szRequestTypeOfUI, NULL, NULL, &fSupported);
}

if (SUCCEEDED(hr))
{
   // Do something here.
}


ISpRecoContext::GetMaxAlternates (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::GetMaxAlternates

ISpRecoContext::GetMaxAlternates retrieves the maximum number of alternates that the SR engine will return for command and control or proprietary grammars associated with this context. See Remarks section.

HRESULT GetMaxAlternates(
   ULONG   *pcMaxAlternates
);

Parameters

pcMaxAlternates
[out] The maximum number of alternates. The default value is zero, unless the application specifies it by ISpRecoContext::SetMaxAlternates.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pcMaxAlternates is invalid or bad.
FAILED(hr) | Appropriate error message.

Remarks

The value is the maximum number of alternates that will be returned to the application. For SR engine's that do not support command and control (or proprietary grammar) alternates, this method will succeed, but the alternates returned will always be zero.

For applications and SR engines that are using proprietary grammars and proprietary alternates, ISpRecoContext::GetMaxAlternates and ISpRecoContext::SetMaxAlternates is the recommended method of coordinating maximum alternate values between the application and SR engine.

This method has no effect on dictation alternates. See ISpRecoResult::GetAlternates for information regarding dictation alternates.

Versions of the Microsoft SR engine up to 5.1 did not support command and control alternates, but versions 6.0 and above do.


ISpRecoContext::SetMaxAlternates (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::SetMaxAlternates

ISpRecoContext::SetMaxAlternates sets the maximum number of alternates that the SR engine will return for command and control or proprietary grammars associated with this context. See Remarks section.

HRESULT SetMaxAlternates(
   ULONG   cAlternates
);

Parameters

cAlternates
[in] Specifies the maximum number of alternates the engine will return.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED(hr) | Appropriate error message.

Remarks

By default, the maximum alternates value is zero, so an application must call ::SetMaxAlternates to retrieve alternates.

The value is the maximum number of alternates that will be returned to the application. For SR engine's that do not support command and control (or proprietary grammar) alternates, this method will succeed, but the alternates returned will always be zero.

For applications and SR engines using proprietary grammars and proprietary alternates, ISpRecoContext::GetMaxAlternates and ISpRecoContext::SetMaxAlternates are the recommended methods of coordinating maximum alternate values between the application and the SR engine.

This method has no effect on dictation alternates. See ISpRecoResult::GetAlternates for information regarding dictation alternates.

Versions of the Microsoft speech recognition engine up to 5.1 did not support command and control alternates, but versions 6.0 and above do. Other manufacturers' engines may also support alternates.


ISpRecoContext::SetAudioOptions (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::SetAudioOptions

ISpRecoContext::SetAudioOptions sets the audio options for result objects from this recognition context. This method also enables or disables the retention of audio with result objects and can change the retained audio format.

HRESULT SetAudioOptions(
   SPAUDIOOPTIONS        Options,
   const GUID           *pAudioFormatId,
   const WAVEFORMATEX   *pWaveFormatEx
);

Parameters

Options
[in] Flag of type SPAUDIOOPTIONS indicating the option. It must be one of the following:
Value | Description
SPAO_NONE | Do not retain audio for results.
SPAO_RETAIN_AUDIO | Retain audio for all future results.
pAudioFormatId
[in] The audio stream format id [of type GUID]. Usually this value is SPDFID_WaveFormatEx. If this value is NULL, the retained audio format will not be changed. Reset the retained audio format to the SR engine's recognition format by setting this value to GUID_NULL and pWaveFormatEx to NULL.
pWaveFormatEx
[in] The audio stream wave format [of type WAVEFORMATEX]. This is only valid if *pAudioFormatId == SPFID_WaveFormatEx.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Options is not one of the correct types, or the specified audio format is not valid.
FAILED(hr) | Appropriate error message.

Remarks

If a WAVEFORMATEX-based retained audio format is specified, but the SR engine and the audio input stream agree on a non-WAVEFORMATEX-based audio input format (e.g., custom audio object/format), ISpRecoContext::SetAudioOptions will return successfully, but will not retain the audio.

By default, SAPI does not retain recognition audio.

By default, when an audio format is not specified, the audio will be retained in the same format that the SR engine used to perform the recognition.

Example

The following code snippet illustrates the use of ISpRecoContext::SetAudioOptions.

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;
CComPtr<ISpStream>         cpSpStream;
CSpStreamFormat            sfRetained;

// Activate retained audio settings with default
// format (that is, SR engine recognition format).
hr = cpRecoContext->SetAudioOptions(SPAO_RETAIN_AUDIO, &GUID_NULL, NULL);

if (SUCCEEDED(hr))
{
   // Deactivate retained audio settings.
   hr = cpRecoContext->SetAudioOptions(SPAO_NONE, NULL, NULL);
}

if (SUCCEEDED(hr))
{
   // Use the stream format helper to fill in the WAVEFORMATEX structure.
   CSpStreamFormat sfRetained(SPSF_24kHz16BitStereo, &hr);
}

if (SUCCEEDED(hr))
{
   // Change the settings to the selected stream format.
   hr = cpRecoContext->SetAudioOptions(SPAO_RETAIN_AUDIO, &sfRetained.FormatId(), sfRetained.WaveFormatExPtr());
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}

Development Helpers

Helper Enumerations and Functions | Description
SPSTREAMFORMAT | SAPI supported stream formats
CSpStreamFormat | Class for managing SAPI supported stream formats and WAVEFORMATEX structures


ISpRecoContext::GetAudioOptions (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::GetAudioOptions

ISpRecoContext::GetAudioOptions retrieves the audio options for the context.

HRESULT GetAudioOptions(
   SPAUDIOOPTIONS  *Options,
   GUID            *pAudioFormatId,
   WAVEFORMATEX   **ppCoMemWFE
);

Parameters

Options
[out] Address that will receive pointer to SPAUDIOOPTIONS flag, indicating the options set for this context. If this value is not to be retrieved, specify NULL. The flag can be one of the following values:
Value | Meaning
SPAO_NONE | Do not retain audio for results.
SPAO_RETAIN_AUDIO | Retain audio for all future results.
pAudioFormatId
[in] Address that will receive the audio stream format type (i.e., GUID). If the application is not interested in the retained audio format, NULL is specified (i.e., ignore both pAudioFormatId and pWaveFormatEx parameters).
ppCoMemWFE
[in] Address that will receive a pointer to the audio stream wave format structure (i.e., WAVEFORMATEX). This can be NULL if the application is not interested in the retained audio format. If WAVEFORMATEX data is retrieved, it must be freed using ::CoTaskMemFree().

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | One of the pointers is invalid or bad.
FAILED(hr) | Appropriate error message.

Remarks

The default audio options are none (i.e., SPAO_NONE). The default retained audio format is the speech recognition engine's recognition format (see ISpRecognizer::GetFormat with SPWF_SRENGINE).

See also ISpRecoContext::SetAudioOptions.

Example

The following code snippet illustrates the use of ISpRecoContext::GetAudioOptions and querying the different retained audio settings.

// Declare local identifiers:
HRESULT	                   hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;
WAVEFORMATEX               *pWaveFormatEx;
SPAUDIOOPTIONS             pAudioOptions;
GUID                       guidFormat;

// Check if audio is being retained (default is NO).
hr = cpRecoContext->GetAudioOptions(&pAudioOptions, NULL, NULL);

if (SUCCEEDED(hr))
{
   // Check what audio format would be retained.
   hr = cpRecoContext->GetAudioOptions(NULL, &guidFormat, &pWaveFormatEx);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}

// Free the wave format memory.
::CoTaskMemFree(pWaveFormatEx);

// Check if audio is being retained and, if so, what the format is.
hr = cpRecoContext->GetAudioOptions(&pAudioOptions, &guidFormat, &pWaveFormatEx);

if (SUCCEEDED(hr))
{
   // Do stuff here.
}

// Free the wave format memory.
::CoTaskMemFree(pWaveFormatEx);

Development Helpers

Helper Enumerations and Functions | Description
SPSTREAMFORMAT | SAPI supported stream formats
CSpStreamFormat | Class for managing SAPI supported stream formats and WAVEFORMATEX structures


ISpRecoContext::DeserializeResult (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::DeserializeResult

ISpRecoContext::DeserializeResult creates a new result object from a serialized result.

HRESULT DeserializeResult(
   const SPSERIALIZEDRESULT  *pSerializedResult,
   ISpRecoResult            **ppResult
);

Parameters

pSerializedResult
[in] Pointer to a serialized result. See also SPSERIALIZEDRESULT
ppResult
[out] The unserialized result object. The application must call IUnknown::Release when finished using the ISpRecoResult reference.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pSerializedResult is invalid or bad.
E_POINTER | ppResult is invalid or bad.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.

Remarks

After deserializing the ISpRecoResult object, the application can retrieve alternates for the RecoResult, retrieve the retained audio, or examine the recognition.

The same SR engine that was originally used to generate the ISpRecoResult object (or recognition) must be the same SR engine that is associated with the ISpRecoContext that called ::DeserializeResult (see SPPHRASE.SREngineID). The SR engine requirement ensures that the SR engine is capable of recognizing the original phrase, and that it understands any SR engine private result data (see SPPHRASE.ulSREnginePrivateDataSize).

Example

The following code snippet illustrates the use ISpRecoContext::Deserialize a previously serialized result object.

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpRecoResult>     cpRecoResult;
CComPtr<ISpRecoResult>     cpRecoResultNew;
CComPtr<IStream>           cpStreamWithResult;
CComPtr<ISpRecoContext>    cpRecoContext;
SPSERIALIZEDRESULT*        pSerializedResult = NULL;
ULONG                      cbWritten = 0;
ULONG                      ulSerializedSize = 0;
LARGE_INTEGER              liseek;
LARGE_INTEGER              li;

// ... Obtain a recognition result object from the recognizer ...
hr = CreateStreamOnHGlobal(NULL, true, &cpStreamWithResult);

if (SUCCEEDED(hr))
{
   // Serialize result to memory.
   hr = cpRecoResult->Serialize(&pSerializedResult);
}

if (SUCCEEDED(hr))
{
   // Serialize to a stream pointer.
   hr = cpStreamWithResult->Write(pSerializedResult, pSerializedResult->ulSerializedSize, &cbWritten);
}

if (SUCCEEDED(hr))
{
   // Free the serialized result.
   if (pSerializedResult) ::CoTaskMemFree(pSerializedResult);

   // Commit the stream changes.
   hr = cpStreamWithResult->Commit(STGC_DEFAULT);
}

if (SUCCEEDED(hr))
{
   // ... Persist stream to disk, network share, etc ...
   // ... Shutdown application ...
   // ... Restart application and get the persisted stream ...

   // Reset the stream seek pointer to the start before deserialization:
   li.QuadPart = 0;
   hr = cpStreamWithResult->Seek(li, STREAM_SEEK_SET, NULL);
}

if (SUCCEEDED(hr))
{
   // Find the size of the stream.
   hr = cpStreamWithResult->Read(&ulSerializedSize, sizeof(ULONG), NULL);
}

if (SUCCEEDED(hr))
{
   // Reset the seek pointer:
   liseek.QuadPart = 0 - sizeof(ULONG);
   hr = cpStreamWithResult->Seek(liseek, STREAM_SEEK_CUR, NULL);
}

if (SUCCEEDED(hr))
{
   // Allocate the memory for the result.
   pSerializedResult = (SPSERIALIZEDRESULT*)::CoTaskMemAlloc(ulSerializedSize);

   // Check pSerializedResult in case out "out-of-memory".

   // Copy the stream into a serialized result object.
   hr = cpStreamWithResult->Read(pSerializedResult, ulSerializedSize, NULL);
}

if (SUCCEEDED(hr))
{
   // Deserialize result from memory.
   hr = cpRecoContext->DeserializeResult(pSerializedResult, &cpRecoResultNew);
}

if (SUCCEEDED(hr))
{
   // Free the pSerializedResult memory.
   if (pSerializedResult) CoTaskMemFree(pSerializedResult);
}

// As long as the same engine was used to generate original
// result object, as is now being used, applications can
// now get alternates for the cpRecoResultNew's phrase.


ISpRecoContext::Bookmark (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::Bookmark

ISpRecoContext::Bookmark sets a bookmark within the current recognition stream. When the engine reaches the specified stream position, a bookmark event is added to the event queue.

HRESULT Bookmark(
   SPBOOKMARKOPTIONS   Options,
   ULONGLONG           ullStreamPosition,
   LPARAM              lParamEvent
);

Parameters

Options
[in] Indicates the option associated with the bookmark. Must be one of type SPBOOKMARKOPTIONS.
ullStreamPosition
[in] Specifies the stream position. This value may be anywhere in the stream and will send a Bookmark event when that position is reached. Additionally it may be any one of two special values: SP_STREAMPOS_ASAP or SP_STREAMPOS_REALTIME. See Remarks section for additional information.
lParamEvent
[in] The lparam for the SAPI bookmark event, and can be any value the application wants returned with the bookmark event (e.g., unique identifier, data pointer, NULL, etc.).

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Options has a bad value.
FAILED(hr) | Appropriate error message.

Remarks

If Options is set to SPBO_PAUSE, the SPEVENT wParam variable will be set to SPREF_AutoPause.

An application that wants to implement display a recognition progress/latency meter could use ISpRecoContext::Bookmark with SP_STREAMPOS_REALTIME, and update the UI when each bookmark is received. See also ISpRecognizer::GetStatus

An application that wants to pause the SR engine to perform specific processing could use ISpRecoContext::Bookmark with SPBO_PAUSE SP_STREAMPOS_ASAP, which will pause the SR engine automatically, and asynchronously for the application. The application should call ISpRecoContext::Resume to resume the recognition process. See also ISpRecoGrammar::SetRuleState regarding "auto-pause" rules.

It is possible to bookmark a stream position before starting a stream. If there is currently no stream and the caller specifies an offset of zero (or as soon as possible) or SP_STREAMPOS_REALTIME (indicating immediately for a live audio device) the bookmark fires immediately. In both cases the application gets the bookmark as soon as the stream is created. Otherwise, the bookmark is delayed until the next stream reaches the specified offset.

Example

The following code snippet illustrates the use of ISpRecoContext::Bookmark with an "auto-pause" bookmark.

// Declare local identifiers:
HRESULT	                   hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;
CComPtr<ISpRecoGrammar>    cpRecoGrammar;

// Set up the recognition context and grammar.
// ...

// Start listening for recognitions.
hr = cpRecoGrammar->SetRuleState(NULL, NULL, SPRS_ACTIVE_WITH_AUTO_PAUSE);

if (SUCCEEDED(hr))
{
   // Pause recognition context.
   hr = cpRecoContext->Bookmark(SPBO_PAUSE, SP_STREAMPOS_ASAP, NULL);
}

// Get the bookmark event in a CSpEvent object.
// ...

// Assert that recognition context paused after the "auto-pause" bookmark was sent.
_ASSERT(spEvent.IsPaused());

// Because the context was paused from the "auto-pause" rule,
// it must now be reactivated to recognize the second rule.
hr = cpRecoContext->Resume(NULL);

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoContext::SetAdaptationData (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::SetAdaptationData

ISpRecoContext::SetAdaptationData passes a block of text to the SR engine which can be used to adapt the active language models.

HRESULT SetAdaptationData(
   LPCWSTR       *pAdaptationData,
   const ULONG    cch
);

Parameters

pAdaptationData
[in] The string to adapt.
cch
[in] The number of characters in pAdaptationData.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pAdaptationData is invalid or cch equals zero.
E_OUTOFMEMORY | Exceeded available memory.
SPERR_SR_ENGINE_EXCEPTION | An exception was thrown by the SR engine.
FAILED(hr) | Appropriate error message.

Remarks

An application can improve recognition accuracy for dictating uncommon words, or uncommon word groupings, by training the SR engine for the new words, or word groupings, by creating or obtaining typical text and send the results to the engine using ::SetAdaptationData.

For example, a word processing application train the engine on previously created text documents. Similarly, an e-mail or collaboration application could train the SR engine on previously sent e-mail or collaborated documents. After training, the SR engine could perform better within specific domains of information, and improve the application's and SAPI's personalization experience.

The SAPI middleware component (and Microsoft) do not store this information - instead it is passed directly to the SR engine. The SR engine (vendor) determines what to do with the string data, including how the data is persisted and for how long. Some SR engines may require a significant amount of time to process the string data, so the application may want to break up the data in smaller chunks to send individually.

Applications that use SetAdaptationData should break the data into small (1K or less) blocks, call SetAdaptationData, and then wait for an SPEI_ADAPTATION event before sending the next small block of data. Passing a large string in pAdaptationData to this method can cause unpredictable results.

When the SR engine is ready to receive more string data to adapt its language model, it can fire the SPEI_ADAPTATION event to the application.

Example

The following code snippet illustrates the use of ISpRecoContext::SetAdaptationData.

// Declare local identifiers:
HRESULT	                   hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;
USHORT                     iCountOfDataChunk = 0;
WCHAR                      *ppwszAdaptationData[5];
const USHORT               PROCESSING_WAIT_TIME = 500;

// Get "training" data and break it into manageable
// chunks (for example, an array of strings).
// ...

// Set interest in the adaptation event.
hr = cpRecoContext->SetInterest(SPFEI(SPEI_ADAPTATION), SPFEI(SPEI_ADAPTATION));

if (SUCCEEDED(hr))
{
   // Adapting to each chunk of data--
   for (int i = 0; i < iCountOfDataChunk; i ++)
   {

      // Send each chunk of data to the engine.
      hr = cpRecoContext->SetAdaptationData(ppwszAdaptationData[i], wcslen(ppwszAdaptationData[i]));

      if (SUCCEEDED(hr))
      {
         // Wait for the engine to ask for more data.
         hr = cpRecoContext->WaitForNotifyEvent(PROCESSING_WAIT_TIME);

         if (SUCCEEDED(hr))
         {
         }
      }
   }
   // SR Engine has adapted its language model to data.
}


ISpRecoContext::Pause (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::Pause

ISpRecoContext::Pause pauses the engine object to synchronize with the SR engine.

The SR engine pauses at its synchronization point to allow grammars and rule states to be changed freely. The engine remains paused until the Resume method is called.

The caller must call Resume once for every call that is made to Pause.

HRESULT Pause(
   DWORD   dwFlags
);

Parameters

dwFlags
[in] Reserved, must be zero.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | dwFlags is not set to zero.

Remarks (when using ISpMMSysAudio as audio input)

Pausing the SR engine will stop recognition, but input audio will continue to be collected and stored by SAPI in an audio buffer. After the application is done with the state change, it should call ISpRecoContext::Resume. SAPI will automatically feed the buffered audio data into the SR engine, ensuring that no real-time audio data is lost and that the user experience is not interrupted.

However, the SAPI audio buffer has a static limit to prevent large amounts of system memory from being consumed by SAPI applications or SR engines. Therefore, Pause should be used by the SR engine for very short periods of time for state changes (e.g., updating grammar, or rule states). Pausing the SR engine will affect all recognition contexts connected to that SR engine including other Speech applications currently running.

If the SR engine is paused too long, and the audio buffer is filled, a buffer overflow will occur. The application can detect this error by setting an event interest in SPEI_END_SR_STREAM (see SPEVENTENUM), and checking the LPARAM of the SPEVENT structure (see CSpEvent::EndStreamResult).

SAPI will automatically attempt to restart the SR Engine's recognition thread once the final Resume has been called. Consequently, the audio data collected between the point when the buffer overflow occurred, and when the stream was reactivated, will be completely lost. This would result in a less than optimal user experience, and have a negative effect on all running speech applications, the SR engine, and SAPI.

The following code snippet illustrates the use of ISpRecoContext::Pause

// Declare local identifiers:
HRESULT	                   hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;

// Set up the recognition context.
// ...

// Pause the context so that event notifications are not received.
hr = cpRecoContext->Pause(NULL);

if (SUCCEEDED(hr))
{
   // Quickly perform the processing - see the
   // Remarks section in ISpRecoContext::Pause.
   // ...

   hr = cpRecoContext->Resume(NULL);
}

// Applications will start receiving event notifications again.
if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoContext::Resume (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::Resume

ISpRecoContext::Resume releases the SR engine from the paused state and restarts the recognition process.

HRESULT  Resume (
  DWORD dwReserved
);

Parameters

dwReserved
[in] Reserved, must be zero.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | dwFlags is not set to zero.

Remarks

This method must be called after a call to ISpRecoContext::Pause, a bookmark event occurs that pauses the recognition engine, or an auto-pause rule is recognized (see ISpRecoGrammar::SetRuleState).

The caller must call Resume once for every call that is made to ISpRecoContext::Pause.

Example

The following code snippet illustrates the use of ISpRecoContext::Resume after a call to ISpRecoContext::Pause

// Declare local identifiers:
HRESULT	                   hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;

// Set up the recognition context.
// ...

// Pause the context so that event notifications are not received.
hr = cpRecoContext->Pause(NULL);

if (SUCCEEDED(hr))
{
   // Quickly perform the processing - see the
   // Remarks section in ISpRecoContext::Pause.
   // ...

   hr = cpRecoContext->Resume(NULL);
}

// Applications will start receiving event notifications again.
if (SUCCEEDED(hr))
{
   // Do stuff here.
}

The following code snippet illustrates the use of ISpRecoContext::Resume with an "auto-pause" rule.

// Declare local identifiers:
HRESULT	                   hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;
CComPtr<ISpRecoGrammar>    cpRecoGrammar;
const WCHAR                *MY_AUTOPAUSE_RULE = L"Rule1";
const WCHAR                *MY_SECOND_RULE = L"Rule2";

// Set up the recognition context and grammar.
// ...

// Activate a top-level rule as an "auto-pause" rule.
hr = cpRecoGrammar->SetRuleState(MY_AUTOPAUSE_RULE, NULL, SPRS_ACTIVE_WITH_AUTO_PAUSE);

if (SUCCEEDED(hr))
{
   // Get the recognition event for MY_AUTOPAUSE_RULE in a CSpEvent object.
   // ...
}

// Assert that the recognition context paused
// after the "auto-pause" rule was recognized.
_ASSERT(spEvent.IsPaused());

// Deactivate the "auto-pause" rule.
hr = cpRecoGrammar->SetRuleState(MY_AUTOPAUSE_RULE, NULL, SPRS_INACTIVE);

if (SUCCEEDED(hr))
{
   // Activate the second rule.
   hr = cpRecoGrammar->SetRuleState(MY_SECOND_RULE, NULL, SPRS_ACTIVE);
}

if (SUCCEEDED(hr))
{
   // Because the context was paused from the "auto-pause" rule,
   // it must now be reactivated to recognize the second rule.
   hr = cpRecoContext->Resume(NULL);
}

if (SUCCEEDED(hr))
{
   // Get the second recognition...
}


ISpRecoContext::SetVoice (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::SetVoice

ISpRecoContext::SetVoice sets the associated ISpVoice to an object.

HRESULT SetVoice(
   ISpVoice   *pVoice,
   BOOL        fAllowFormatChanges
);

Parameters

pVoice
[in] The voice interface to be associated. If NULL, the currently associated Voice is Released.
fAllowFormatChanges
[in] Boolean allowing the voice format alteration by the engine. See Remarks section.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pVoice is invalid or bad.
FAILED(hr) | Appropriate error message.

Remarks

If fAllowFormatChanges is TRUE, the Voice's output format will be changed to be the same format as the associated SR engine's audio input format (see ISpRecognizer). However, if this voice object has already been bound to a stream which has specific format, the voice's format will not be changed to the SR engine's audio input format even if fAllowFormatChanges is true.

Using the same audio format for input and output source is useful for sound cards that do not support full-duplex audio (i.e., input format must match output format). If the input format quality is lower than the output format quality, the output format quality will be reduced to equal the input quality.

After calling ISpRecoContext::SetVoice, an application that calls ISpRecoContext::GetVoice will retrieve the originally "set" ISpVoice interface pointer.

Example

The following code snippet illustrates the use of ISpRecoContext::SetVoice and "barge-in" setup.

// Declare local identifiers:
HRESULT	                   hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;
CComPtr<ISpVoice>          cpVoice;

// Create a shared recognition context.
hr = cpRecoContext.CoCreateInstance(CLSID_SpSharedRecoContext);

if (SUCCEEDED(hr))
{
   // Create a voice.
   hr = cpVoice.CoCreateInstance(CLSID_SpVoice);
}

if (SUCCEEDED(hr))
{
   // Associate the voice with the context
   // (with same audio format as context).
   hr = cpRecoContext->SetVoice(cpVoice, TRUE);
}

if (SUCCEEDED(hr))
{
   // Tell the associated Voice to stop speaking when
   // the SR Engine hears a recognizable sound.
   hr = cpRecoContext->SetVoicePurgeEvent(SPFEI(SPEI_SOUND_START));
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoContext::GetVoice (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::GetVoice

ISpRecoContext::GetVoice retrieves a reference to an ISpVoice object that is associated with the ISpRecoContext object.

HRESULT GetVoice(
   ISpVoice   **ppVoice
);

Parameters

ppVoice
[in] Address of the ISpVoice interface. IUnknown::Release must be called on the ISpVoice interface when finished.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Invalid pointer.
FAILED(hr) | Appropriate error message.

Remarks

If an application previously called ISpRecoContext::SetVoice on the same ISpRecoContext object, the Voice interface retrieved from GetVoice will match that of the SetVoice call. Release must still call the ISpVoice reference for each GetVoice call, even though the interface pointer is the same.

The output format of the ISpVoice will be the same format as the associated audio input format of the SR engine (see ISpRecognizer. Using the same audio format for input and output source is useful for sound cards that do not support full-duplex audio (i.e., input format must match output format). If the input format quality is lower than the output format quality, the output format quality will be down-sampled to the lower quality.

Applications implementing a "barge-in" type functionality will need to tie the Voice object to the SR object. Applications can also use ISpRecoContext::GetVoice (see ISpRecoContext::SetVoicePurgeEvent).

Example

The following code snippet illustrates the use of ISpRecoContext::GetVoice and "barge-in" setup

// Declare local identifiers:
HRESULT	                   hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;
CComPtr<ISpVoice>          cpVoice;

// Create a shared recognition context.
hr = cpRecoContext.CoCreateInstance(CLSID_SpSharedRecoContext);

if (SUCCEEDED(hr))
{
   // Create a voice from the context (with
   // same audio format as context)
   hr = cpRecoContext->GetVoice(&cpVoice);
}

if (SUCCEEDED(hr))
{
   // Tell the associated Voice to stop speaking when
   // the SR Engine hears a recognizable sound.
   hr = cpRecoContext->SetVoicePurgeEvent(SPFEI(SPEI_SOUND_START));
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoContext::SetVoicePurgeEvent (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::SetVoicePurgeEvent

ISpRecoContext::SetVoicePurgeEvent sets the SR engine events that stop audio output, and purges the current speaking queue.

HRESULT SetVoicePurgeEvent(
   ULONGLONG   ullEventInterest
);

Parameters

ullEventInterest
[in] The set of flags indicating the event interest(s). The event interest(s) must be in the set of speech recognition events (i.e., between SPEI_MIN_SR and SPEI_MAX_SR) (see SPEVENTENUM and SPFEI_ALL_SR_EVENTS)

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more of the event interests set is not allowed.
FAILED(hr) | Appropriate error message.

Remarks

The ISpRecoContext event interest will be updated to include the Voice Purge Events (see ISpEventSource::SetInterest).

To find the current Voice Purge Event(s), use ISpRecoContext::GetVoicePurgeEvent

Applications can call SetVoicePurgeEvent when implementing "barge-in" type functionality. For example, when a user calls a telephony server, and the server uses TTS Voice prompts, the Voice should stop speaking when the user is speaking. The application would want the associated Voice object of the ISpRecoContext (see ISpRecoContext::GetVoice) to stop and purge when the SR engine hears a sound (see SPEI_SOUND_START).

Example

The following code snippet illustrates the use of ISpRecoContext::SetVoicePurgeEvent and "barge-in" setup

// Declare local identifiers:
HRESULT	                   hr = S_OK;
CComPtr<ISpRecoContext>    cpRecoContext;
CComPtr<ISpVoice>          cpVoice;

// Create a shared recognition context.
hr = cpRecoContext.CoCreateInstance(CLSID_SpSharedRecoContext);

if (SUCCEEDED(hr))
{
   // Create a voice from the context (with
   // same audio format as context).
   hr = cpRecoContext->GetVoice(&cpVoice);
}

if (SUCCEEDED(hr))
{
   // Tell the associated Voice to stop speaking when
   // the SR Engine hears a recognizable sound.
   hr = cpRecoContext->SetVoicePurgeEvent(SPFEI(SPEI_SOUND_START));
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoContext::GetVoicePurgeEvent (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::GetVoicePurgeEvent

ISpRecoContext::GetVoicePurgeEvent retrieves the set of SR engine events that stop audio output, and purges the current speaking queue. The events are set by ISpRecoContext::SetVoicePurgeEvent.

HRESULT GetVoicePurgeEvent(
   ULONGLONG   *pullEventInterest
);

Parameters

pullEventInterest
[out] The set of flags indicating the event interests. The event interests will be a member of the SR event set (see SPFEI_ALL_SR_EVENTS).

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pullEventInterest is invalid or bad.
FAILED(hr) | Appropriate error message.


ISpRecoContext::SetContextState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::SetContextState

ISpRecoContext::SetContextState sets the state of the recognition context.

HRESULT SetContextState(
   SPCONTEXTSTATE   eContextState
);

Parameters

eContextState
[in] The SPCONTEXTSTATE enumeration sequence specifying the recognition context state.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | eContextState is not one of the correct types.
FAILED(hr) | Appropriate error message.

Remarks

The default recognition context state for an ISpRecoContext object is SPCS_ENABLED.

Applications can use ISpRecoContext::SetContextState to toggle sets of grammars. For example, a multi-document interface application that uses a different ISpRecoContext object for each document could toggle the context states as each document gained and lost the focus.

Applications can use ISpRecoContext::GetContextState to query the context state.


ISpRecoContext::GetContextState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext::GetContextState

ISpRecoContext::GetContextState retrieves the state of the recognition context.

HRESULT GetContextState(
   SPCONTEXTSTATE   *peContextState
);

Parameters

peContextState
[out] Address of the SPCONTEXTSTATE enumeration that receives the context state information.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | One of the pointers is invalid or bad.
FAILED(hr) | Appropriate error message.

Remarks

The default recognition context state for an ISpRecoContext object is SPCS_ENABLED.

Applications can use ISpRecoContext::SetContextState to set the context state.


ISpRecoContext2 (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext2

New in SAPI 5.3

Extends the ISpRecoContext interface.

Methods in Vtable Order

ISpRecoContext2 Methods | Description
SetGrammarOptions | Specifies the kinds of CFGs that can be loaded into a grammar object.
GetGrammarOptions | Returns the options that the current grammar supports.
SetAdaptationData2 | Passes a block of text to the SR engine which can be used to adapt the active language models. It extends the functionality of the ISpRecoContext2::SetAdaptationData function.


ISpRecoContext2::SetGrammarOptions (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext2::SetGrammarOptions

ISpRecoContext2::SetGrammarOptions specifies the kinds of CFGs that can be loaded into a grammar object.

HRESULT SetGrammarOptions(
   DWORD   eGrammarOptions
);

Parameters

eGrammarOptions
Controls what kinds of CFGs can be loaded into the grammar object.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Invalid parameter.
FAILED(hr) | Appropriate error message.


ISpRecoContext2::GetGrammarOptions (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext2::GetGrammarOptions

ISpRecoContext2::GetGrammarOptions returns the options that the current grammar supports.

HRESULT GetGrammarOptions(
   DWORD   *peOptions
);

Parameters

peOptions
Returns the current grammar options.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | peOptions is invalid.
E_FAILED(hr) | Appropriate error message.


ISpRecoContext2::SetAdaptationData2 (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext2::SetAdaptationData2

ISpRecoContext2::SetAdaptationData2 passes a block of text to the SR engine which can be used to adapt the active language models and extends the functionality of the ISpRecoContext2::SetAdaptationData function.

HRESULT SetAdaptationData2(
   LPCWSTR                  pAdaptationData,
   ULONG                    cch,
   LPCWSTR                  pTopicName,
   DWORD                    eAdaptationSettings,
   SPADAPTATIONRELEVANCE    eRelevance
);

Parameters

pAdaptationData
The text data to adapt to.
cch
The length of pAdaptationData.
pTopicName
The dictation topic name the adaptation applies to.
eAdaptationSettings
A value or values from the SPADAPTATIONSETTINGS enumeration.
eRelevance
A value from the SPADAPTATIONRELEVANCE enumeration.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Invalid parameter.


ISpRecoGrammar (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar

The ISpRecoGrammar interface enables applications to manage the words and phrases that the SR engine will recognize.

A single SpRecognizer object can have multiple SpRecoContext objects associated with it. And similarly, a single SpRecoContext object can have multiple SpRecoGrammar objects associated with it. Using a one-to-many relationship with SpRecoContext objects and SpRecoGrammar objects allows applications to separate types of recognizable phrases and content into separate objects for clearer application logic. Each SpRecoGrammar object can also have a context-free grammar (CFG) and a dictation grammar loaded simultaneously (e.g., use the CFG if possible, but back off to dictation if CFG fails to parse).

See Designing Grammar Rules for examples of how to create context-free grammars.

Methods in Vtable Order

ISpRecoGrammar Methods | Description
ISpGrammarBuilder interface | Inherits from ISpGrammarBuilder and all those methods are accessible from an ISpRecoGrammar object.
GetGrammarId | Retrieves the grammar identifier associated with the application.
GetRecoContext | Retrieves the context object that created this grammar.
LoadCmdFromFile | Loads a command and control grammar from a file.
LoadCmdFromObject | Loads a command and control grammar from a COM object.
LoadCmdFromResource | Loads a command and control grammar from a Win32 resource.
LoadCmdFromMemory | Loads a command and control grammar from memory.
LoadCmdFromProprietaryGrammar | Loads an engine proprietary format command and control grammar.
SetRuleState | Activates or deactivates a rule by its rule name.
SetRuleIdState | Activates or deactivates a rule by its rule ID.
LoadDictation | Loads and initializes a dictation topic.
UnloadDictation | Unloads the active dictation topic from the grammar.
SetDictationState | Sets a dictation state to active or inactive.
SetWordSequenceData | Sets a word sequence buffer in the SR engine.
SetTextSelection | Sets the current text selection and insertion point information.
IsPronounceable | Determines if the word has a pronunciation.
SetGrammarState | Sets the grammar state.
SaveCmd | Allows applications using dynamic grammars to save the current grammar state to a stream.
GetGrammarState | Retrieves recognition grammar state information.


ISpRecoGrammar::GetGrammarId (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::GetGrammarId

ISpRecoGrammar::GetGrammarId retrieves the identifier associated with the grammar when the grammar was created.

The grammar ID is set by the application by calling ISpRecoContext::CreateGrammar.

HRESULT GetGrammarId(
   ULONGLONG   *pullGrammarId
);

Parameters

pullGrammarId
[out] Address of a ULONGLONG variable to receive the grammar ID.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pullGrammarId is invalid or bad.

Remarks

The grammar ID will be set in the SPPHRASE object when a recognition is sent to the application (see ISpPhrase::GetPhrase).


ISpRecoGrammar::GetRecoContext (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::GetRecoContext

ISpRecoGrammar::GetRecoContext retrieves the ISpRecoContext object that created this grammar. If this method succeeds, the application using this method must call Release() on the SpRecoContext object returned.

HRESULT GetRecoContext(
   ISpRecoContext   **ppRecoCtxt
);

Parameters

ppRecoCtxt
[out] Address of a pointer to an ISpRecoContext interface that receives the recognition context object pointer.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppRecoCtxt is invalid or bad.


ISpRecoGrammar::LoadCmdFromFile (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::LoadCmdFromFile

ISpRecoGrammar::LoadCmdFromFile loads a SAPI 5 grammar from a file. The file can either be a compiled or uncompiled grammar file. To modify the rules of the grammar after it has been loaded, specify SPLO_DYNAMIC for the Options parameter, otherwise specify the SPLO_STATIC flag.

HRESULT LoadCmdFromFile(
    LPCWSTR        *pszFileName,
    SPLOADOPTIONS   Options
);

Parameters

pszFileName
[in, string] The name of the file containing the command and control grammar. SAPI 5 supports loading of compiled and static grammars using URL.
Options
[in] Flag of type SPLOADOPTIONS indicating whether the grammar will be modified dynamically.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszFileName is invalid or bad. Alternatively, Options is neither SPLO_STATIC nor SPLO_DYNAMIC.
FAILED(hr) | Appropriate error message.


ISpRecoGrammar::LoadCmdFromObject (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::LoadCmdFromObject

ISpRecoGrammar::LoadCmdFromObject loads a CFG from a COM object. The COM object must be located inside of a Windows DLL.

HRESULT LoadCmdFromObject(
   REFCLSID        rcid,
   LPCWSTR        *pszGrammarName,
   SPLOADOPTIONS   Options
);

Parameters

rcid
[in] The reference class ID of the object containing the command.
pszGrammarName
[in, string] The grammar name of the object containing the command.
Options
[in] Flag of type SPLOADOPTIONS indicating whether the file should be loaded statically or dynamically.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszGrammarName is invalid or bad. Alternatively, Options is neither SPLO_STATIC nor SPLO_DYNAMIC.
FAILED(hr) | Appropriate error message.

Remarks

When an application calls ::LoadCmdFromObject, the currently loaded CFG or proprietary grammar will be unloaded.


ISpRecoGrammar::LoadCmdFromResource (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::LoadCmdFromResource

ISpRecoGrammar::LoadCmdFromResource loads a command and control grammar from a Win32 resource.

HRESULT LoadCmdFromResource(
   HMODULE         hModule,
   LPCWSTR        *pszResourceName,
   LPCWSTR        *pszResourceType,
   WORD            wLanguage,
   SPLOADOPTIONS   Options
);

Parameters

hModule
[in] Handle to the module whose file name is being requested. If this parameter is NULL, it passes back the path for the file containing the current process.
pszResourceName
[in, string] The name of the resource.
pszResourceType
[in, string] The type of the resource.
wLanguage
[in] The language ID.
Options
[in] Flag of type SPLOADOPTIONS indicating whether the file should be loaded statically or dynamically.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Either pszResourceName or pszResourceType is invalid or bad. It may also indicate hModule could not be found. Alternatively, Options is neither SPLO_STATIC nor SPLO_DYNAMIC.
FAILED(hr) | Appropriate error message.

Remarks

When an application calls ::LoadCmdFromResource, the currently loaded context-free grammar or proprietary grammar will be unloaded.

The CFG resource must be a compiled SAPI 5 binary version of a context-free grammar.

Example

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
CComPtr<ISpRecoContext>      cpRecoContext;
HMODULE                      hModule;
ULONGLONG                    ullGramId = 1;

// Create a new grammar object.
hr = cpRecoContext->CreateGrammar(ullGramId, &cpRecoGrammar);

if (SUCCEEDED(hr))
{
   // Load a CFG resource named SRGRAMMAR from the current
   // module (hModule needs to be initialized first).
   hr = cpRecoGrammar->LoadCmdFromResource(hModule,
           (const WCHAR*)MAKEINTRESOURCE(IDC_COFFEE),
           L"SRGRAMMAR",
           ::SpGetUserDefaultUILanguage(),
           SPLO_STATIC);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoGrammar::LoadCmdFromMemory (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::LoadCmdFromMemory

ISpRecoGrammar::LoadCmdFromMemory loads a compiled CFG binary from memory.

HRESULT LoadCmdFromMemory(
   const SPBINARYGRAMMAR   *pBinaryData,
   SPLOADOPTIONS            Options
);

Parameters

pBinaryData
[in] The serialized header buffer of type SPBINARYGRAMMAR.
Options
[in] Flag of type SPLOADOPTIONS indicating whether the file should be loaded statically or dynamically.

Remarks

When an application calls ::LoadCmdFromMemory, the currently loaded CFG or proprietary grammar will be unloaded.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Either pBinaryData or one of its members is invalid or bad. It may also indicate pBinaryData->FormatId is not SPGDF_ContextFree. Alternatively, Options is neither SPLO_STATIC nor SPLO_DYNAMIC.
FAILED(hr) | Appropriate error message.

Example

The following code snippet illustrates how to use ISpRecoGrammar::LoadCmdFromMemory to serialize the CFG from one SpRecoGrammar object and deserialize it into another SpRecoGrammar object.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
CComPtr<ISpRecoGrammar>      cpReloadedGrammar;
CComPtr<ISpRecoContext>      cpRecoContext;
CComPtr<IStream>             cpHStream;
HGLOBAL                      hGrammar;

// Build and use a SpRecoGrammar object...

// Create a Win32 global stream.
hr = ::CreateStreamOnHGlobal(NULL, true, &cpHStream);

if (SUCCEEDED(hr))
{
   // Save the current grammar to the global stream.
   hr = cpRecoGrammar->SaveCmd(cpHStream, NULL);
}

if (SUCCEEDED(hr))
{
   // Create the second grammar to deserialize into.
   hr = cpRecoContext->CreateGrammar(0, &cpReloadedGrammar);
}

if (SUCCEEDED(hr))
{
   // Get a handle to the stream with the serialized grammar.
   ::GetHGlobalFromStream(cpHStream, &hGrammar);
}

// Deserialize the CFG into a new grammar object.
hr = cpReloadedGrammar->LoadCmdFromMemory((SPBINARYGRAMMAR *)::GlobalLock(hGrammar), SPLO_DYNAMIC);

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoGrammar::LoadCmdFromProprietaryGrammar (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::LoadCmdFromProprietaryGrammar

ISpRecoGrammar::LoadCmdFromProprietaryGrammar loads a proprietary grammar.

HRESULT LoadCmdFromProprietaryGrammar(
   REFGUID         rguidParam,
   LPCWSTR        *pszStringParam,
   const void     *pvDataParam,
   ULONG           cbDataSize,
   SPLOADOPTIONS   Options
);

Parameters

rguidParam
[in] Unique identifier of the grammar. The GUID will be used by the application and the SR engine to uniquely identify the SR engine for verifying support.
pszStringParam
[in, string] The null-terminated string command. The string can be used by the application and the SR engine to specify which part of a grammar to utilize.
pvDataParam
[in] Additional information for the process. SAPI will handle the marshaling of the data to the SR engine.
cbDataSize
[in] The size, in bytes, of pvDataParam. SAPI will handle the marshaling of the data to the SR engine.
Options
[in] Flag of type SPLOADOPTIONS indicating whether the file should be loaded statically or dynamically. This value must be SPLO_STATIC.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszStringParam or pvDataParam is invalid or bad. Alternatively, Options is not SPLO_STATIC.
FAILED(hr) | Appropriate error message.

Remarks

When an application calls ::LoadCmdFromProprietaryGrammar, the currently loaded CFG or proprietary will be unloaded.

Applications should use ::LoadCmdFromProprietaryGrammar when using a proprietary grammar format that the SR engine supports. If the current SR engine does not support the proprietary grammar format (specified using rguidParam and pszStringParam), the SR engine may return E_NOTIMPL.

Example

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
CComPtr<ISpRecoContext>      cpRecoContext;
ULONGLONG                    ullGramId = 1;
GUID                         rguidParam;

// Create a new grammar object.
hr = cpRecoContext->CreateGrammar(ullGramId, &cpRecoGrammar);

if (SUCCEEDED(hr))
{
   // Load a proprietary grammar.
   hr = cpRecoGrammar->LoadCmdFromProprietaryGrammar(rguidParam, L"Rule1", NULL, NULL, SPLO_STATIC);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoGrammar::SetRuleState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::SetRuleState

ISpRecoGrammar::SetRuleState activates or deactivates a rule by its rule name.

HRESULT SetRuleState(
   LPCWSTR       pszName,
   void          *pReserved,
   SPRULESTATE    NewState
);

Parameters

pszName
[in, string] Address of a null-terminated string containing the rule name. If NULL and the grammar is in SAPI 5 format, all rules with attribute SPRAF_TopLevel and SPRAF_Active and set (at rule creation time) are affected.
pReserved
Reserved. Do not use; must be NULL.
NewState
[in] Flag of type SPRULESTATE indicating the new rule state. See Remarks section.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszName is invalid or bad. Alternatively, pReserved is non-NULL.
SP_STREAM_UNINITIALIZED | ISpRecognizer::SetInput has not been called with the InProc recognizer
SPERR_UNINITIALIZED | The object has not been properly initialized.
SPERR_UNSUPPORTED_FORMAT | Audio format is bad or is not recognized. Alternatively, the device driver may be busy by another application and cannot be accessed.
SPERR_NOT_TOPLEVEL_RULE | The rule pszName exists, but is not a top-level rule.
FAILED(hr) | Appropriate error message.

Remarks

The rule name is specified in the XML grammar (using the rule NAME tag), or when ISpGrammarBuilder::GetRule is called.

An application can use the SPRS_ACTIVE_WITH_AUTO_PAUSE state to pause the engine after each CFG recognition is sent. The application must reactivate the SR engine (see ISpRecoContext::Resume) to prevent the loss of input audio data (see SPERR_AUDIO_BUFFER_OVERFLOW).

By default, the recognizer state (SPRECOSTATE) is SPRST_ACTIVE, and the recognition will begin as soon as one or more rule are activated. Consequently, an application should not activate the rule state until it is prepared to receive recognitions. An application can also disable the SpRecoContext object (see ISpRecoContext::SetContextState) or SpRecoGrammar objects (see ISpRecoGrammar::SetGrammarState) to prevent recognitions from being fired for active rules.

If the recognizer state is SPRST_ACTIVE, SAPI will first attempt to open the audio input stream when dictation (or a rule) is activated. Consequently, if the audio device is already in use by another application, or the stream fails to open, the failure code will be returned using ::SetRuleState. The application should handle this failure gracefully.

If an application uses an InProc recognizer, it must call ISpRecognizer::SetInput with a non-NULL setting before the recognizer will return recognitions, regardless of how many rules are active.

Example

The following snippet loads a grammar, activate a single rule ("playcard") and then immediately deactivates it.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoContext>      cpRecoContext;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
ULONGLONG                    ullGramId = 1;

// Create a grammar object.
hr = cpRecoContext->CreateGrammar(ullGramId, &cpRecoGrammar);

if (SUCCEEDED(hr))
{
   // Activate the rule.
   hr = cpRecoGrammar->SetRuleState(L"playcard", NULL, SPRS_ACTIVE);
}

if (SUCCEEDED(hr))
{
   // Deactivate the rule.
   hr = cpRecoGrammar->SetRuleState(L"playcard", NULL, SPRS_INACTIVE);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoGrammar::SetRuleIdState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::SetRuleIdState

ISpRecoGrammar::SetRuleIdState activates or deactivates a rule by its rule ID.

HRESULT SetRuleIdState(
   ULONG         ulRuleId,
   SPRULESTATE   NewState
);

Parameters

ulRuleId
[in] Value specifying the grammar rule identifier. If zero, all rules with attribute SPRAF_TopLevel and SPRAF_Active and set (at rule creation time) are affected.
NewState
[in] Flag of type SPRULESTATE indicating the new rule state.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | dwRuleId is invalid.
SP_STREAM_UNINITIALIZED | ISpRecognizer::SetInput has not been called with the InProc recognizer.
SPERR_UNINITIALIZED | The object has not been properly initialized.
SPERR_UNSUPPORTED_FORMAT | Audio format is bad or is not recognized. Alternatively, the device driver may be busy by another application and cannot be accessed.
SPERR_DEVICE_BUSY | The audio
SPERR_NOT_TOPLEVEL_RULE | The rule ID ulRuleId exists, but is not a top-level rule.
FAILED(hr) | Appropriate error message.

Remarks

An application can use the SPRS_ACTIVE_WITH_AUTO_PAUSE state to pause the engine after each dictation recognition is sent. The application must reactivate the SR engine (see ISpRecoContext::Resume) to prevent the loss of input audio data (see SPERR_AUDIO_BUFFER_OVERFLOW).

The rule ID is specified in the XML grammar (using the rule ID tag), or when ISpGrammarBuilder::GetRule is called.

By default, the recognizer state (SPRECOSTATE) is SPRST_ACTIVE, which means that recognition will begin as soon as dictation is activated. Consequently, an application should not activate the dictation state until it is prepared to receive recognitions. An application can also disable the SpRecoContext object (see ISpRecoContext::SetContextState) or SpRecoGrammar objects (see ISpRecoGrammar::SetGrammarState) to prevent recognitions from being fired for active dictation topics.

If the recognizer state is SPRST_ACTIVE, SAPI will first attempt to open the audio input stream when a rule (or dictation) is activated. Consequently, if the audio device is already in use by another application, or the stream fails to open, the failure code will be returned using ::SetRuleIdState. The application should handle this failure gracefully.

If an application uses an InProc recognizer, it must call ISpRecognizer::SetInput with a non-NULL setting before the recognizer will return recognitions, regardless of the dictation topic state.

Example

The following code snippet illustrates the use of ISpRecoGrammar::SetRuleIdState by programmatically creating a rule and activating it

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
SPSTATEHANDLE                hState;

// Create a new rule.
hr = cpRecoGrammar->GetRule(L"Travel", 1, SPRAF_TopLevel | SPRAF_Active, TRUE, &hState);

if (SUCCEEDED(hr))
{
   // ... Add word transitions ...

   // Activate the rule by its Id.
   hr = cpRecoGrammar->SetRuleIdState(1, SPRS_ACTIVE);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoGrammar::LoadDictation (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::LoadDictation

ISpRecoGrammar::LoadDictation loads a dictation topic into the SpRecoGrammar object and the SR engine.

HRESULT LoadDictation(
   LPCWSTR       *pszTopicName,
   SPLOADOPTIONS  Options
);

Parameters

pszTopicName
[in, optional, string] The null-terminated string containing the topic name. If NULL, the general dictation is loaded. See Remarks section.
Options
[in] Flag of type SPLOADOPTIONS indicating whether the file should be loaded statically or dynamically. This value must be SPLO_STATIC.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszTopicName is invalid or bad. Alternatively, Options is not SPLO_STATIC.
FAILED(hr) | Appropriate error message.

Remarks

SAPI currently defines one specialized dictation topic: SPTOPIC_SPELLING. SR engines are not required to support specialized dictation topic (including spelling).

See the SR engine vendor for information on what specialized dictation topics if any are supported.

Example

The following code snippet illustrates the use of ISpRecoGrammar::LoadDictation to load a spelling topic and activate it.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
CComPtr<ISpRecoContext>      cpRecoContext;
ULONGLONG                    ullGramId = 1;

// Create a grammar object.
hr = cpRecoContext->CreateGrammar(ullGramId, &cpRecoGrammar);

if (SUCCEEDED(hr))
{
   // Load the general dictation topic.
   hr = cpRecoGrammar->LoadDictation(NULL, SPLO_STATIC);
}

if (SUCCEEDED(hr))
{
   // Activate the dictation topic to receive recognitions.
   hr = cpRecoGrammar->SetDictationState(SPRS_ACTIVE);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoGrammar::UnloadDictation (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::UnloadDictation

ISpRecoGrammar::UnloadDictation unloads the active dictation topic from the grammar.

HRESULT  UnloadDictation  ( void );

Parameters

None.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED(hr) | Appropriate error message.

Remarks

If an application uses a CFG with dictation tags, and then unloads the dictation grammar component, the dictation tags will default to the generic dictation topic (see ISpRecoGrammar::LoadDictation).


ISpRecoGrammar::SetDictationState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::SetDictationState

ISpRecoGrammar::SetDictationState sets the dictation topic state.

The dictation topic is specified by calling ISpRecoGrammar::LoadDictation.

HRESULT SetDictationState(
   SPRULESTATE   NewState
);

Parameters

NewState
[in] Flag of type SPRULESTATE indicating the new state of dictation. See Remarks section

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | NewState is not an acceptable value.
SP_STREAM_UNINITIALIZED | ISpRecognizer::SetInput has not been called with the InProc SR engine
SPERR_UNINITIALIZED | A dictation is not currently loaded.
SPERR_UNSUPPORTED_FORMAT | Audio format is bad or is not recognized. Alternatively, the device driver may be busy by another application and cannot be accessed.
FAILED(hr) | Appropriate error message.

Remarks

An application can use the SPRS_ACTIVE_WITH_AUTO_PAUSE state to pause the engine after each dictation recognition is sent. The application must reactivate the SR engine (see ISpRecoContext::Resume) to prevent the loss of input audio data (see SPERR_AUDIO_BUFFER_OVERFLOW).

By default, the recognizer state (SPRECOSTATE) is SPRST_ACTIVE, which means that recognition will begin as soon as dictation is activated. Consequently, an application should not activate the dictation state until it is prepared to receive recognitions. An application can also disable the SpRecoContext object (see ISpRecoContext::SetContextState) or SpRecoGrammar objects (see ISpRecoGrammar::SetGrammarState) to prevent recognitions from being fired for active dictation topics.

If the recognizer state is SPRST_ACTIVE, SAPI will first attempt to open the audio input stream when dictation (or a rule) is activated. Consequently, if the audio device is already in use by another application, or the stream fails to open, the failure code will be returned using ::SetDictationState. The application should handle this failure gracefully.

If an application uses an InProc recognizer, it must call ISpRecognizer::SetInput with a non-NULL setting before the recognizer will return recognitions, regardless of the dictation topic state.

Example

The following code snippet illustrates the use of ISpRecoGrammar::SetDictationState to load a spelling topic and activate it.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
CComPtr<ISpRecoContext>      cpRecoContext;
ULONGLONG                    ullGramId = 1;

// Create a grammar object.
hr = cpRecoContext->CreateGrammar(ullGramId, &cpRecoGrammar);

if (SUCCEEDED(hr))
{
   // Load the general dictation topic.
   hr = cpRecoGrammar->LoadDictation(NULL, SPLO_STATIC);
}

if (SUCCEEDED(hr))
{
   // Activate the dictation topic to receive recognitions.
   hr = cpRecoGrammar->SetDictationState(SPRS_ACTIVE);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoGrammar::SetWordSequenceData (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::SetWordSequenceData

ISpRecoGrammar::SetWordSequenceData sets a word sequence buffer in the SR engine.
The command and control grammar can refer to any sub-sequence of words in this buffer using the <TEXTBUFFER> tag, or the SPRULETRANS_TEXTBUFFER special transition type in ISpGrammarBuilder::AddRuleTransition().

HRESULT SetWordSequenceData(
   [annotation("__in_ecount_opt(cchText)")] const WCHAR   *pText,
   ULONG                                                   cchText,
   const  SPTEXTSELECTIONINFO                             *pInfo
);

Parameters

pText
[in] Buffer containing the text to search for possible word sequences. The buffer is double-NULL terminated. The whole buffer could be separated into different groups by '\0'. Any sub-sequence of words in the same group is recognizable, any sub-sequence of words across different groups is not recognizable. The SR engines determine where to break words and when to normalize text for better performance. For example, if the buffer displays: "please play\0this new game\0\0", "please play" is recognizable, while "this new game" is not recognizable.
cchText
[in] The number of characters (WCHAR) in pText, including null terminators. Because pText should be a double-null-terminated string, the value of cchText should include any internal null terminators and the ending double-null terminators.
pInfo
[optional, in] Address of the SPTEXTSELECTIONINFO structure that contains the selection information. If NULL, the SR engine will use the entire contents of pText.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
FAILED(hr) | Appropriate error message.

Remarks

An application that has a text box could enable the user to speak commands into the text box to edit the text. One way to design this functionality would be to create a CFG which supports such commands as "cut the text *", "bold the text *", or "italicize the words *". The grammar would then use a TEXTBUFFER tag in place of the * which would enable the SR engine to recognize the text buffer information. At run time, the application would update the SR engine's view of the text buffer using ::SetWordSequenceData. So if a user had the text "hello world" in the text box, the SR engine could recognize "bold the text world".

See also ISpRecoGrammar::SetTextSelection for information on how to update the text selection information independent of the word sequence data.

The SR engine must support text buffer features. Check for the presence of the TextBuffer attribute for the SR engine. Microsoft SR ASR engines support these features although there is no requirement that other manufacturers engines need to. See Recognizers in Object Tokens and Registry Settings for more information.

Example

The following code snippet illustrates how an application could send a text buffer to the SR engine using ISpRecoGrammar::SetWordSequenceData.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoContext>      cpRecoContext;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
SPTEXTSELECTIONINFO          tsi;
DWORD                        cch = 0;
WCHAR                        *pwszCoMem = L"";
WCHAR                        *pwszCoMem2;

// Place the contents of text buffer into pwszCoMem
// and the length of the text into cch:
tsi.ulStartActiveOffset = 0;
tsi.cchActiveChars = cch;
tsi.ulStartSelection = 0;
tsi.cchSelection = cch;

pwszCoMem2 = (WCHAR *)CoTaskMemAlloc(sizeof(WCHAR) * (cch + 2));

if (SUCCEEDED(hr) && pwszCoMem2)
{
   // SetWordSequenceData requires double NULL terminator:
   memcpy(pwszCoMem2, pwszCoMem, sizeof(WCHAR) * cch);
   pwszCoMem2[cch] = L'\0';
   pwszCoMem2[cch+1] = L'\0';

   // Set the text buffer data.
   hr = cpRecoGrammar->SetWordSequenceData(pwszCoMem2, cch + 2, NULL);
}

if (SUCCEEDED(hr))
{
   // Set the text selection information.
   hr = cpRecoGrammar->SetTextSelection(&tsi);
}

if (SUCCEEDED(hr))
{
   // The SR engine is now capable of recognizing
   // the contents of the text buffer.
}

// Release system resources:
CoTaskMemFree(pwszCoMem2);
CoTaskMemFree(pwszCoMem);


ISpRecoGrammar::SetTextSelection (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::SetTextSelection

ISpRecoGrammar::SetTextSelection sets the current text selection and insertion point information.

HRESULT SetTextSelection(
   const   SPTEXTSELECTIONINFO  *pInfo
);

Parameters

pInfo
[in] Address of the SPTEXTSELECTIONINFO structure that contains the text selection and insertion point information.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
FAILED(hr) | Appropriate error message.

Remarks

An application that has a text box could enable the user to speak commands into the text box to edit the text. One way to design this functionality would be to create a CFG which supports such commands as "cut the text *", "bold the text *", or "italicize the words *". The grammar would then use a TEXTBUFFER tag in place of the * which would enable the SR engine to recognize the text buffer information. At run time, the application would update the SR engine's view of the text buffer using ISpRecoGrammar::SetWordSequenceData. When the user highlights a selection of text and the text selection using ::SetTextSelection.

If a user had the text "hello world" in the text box and no text highlighted, the SR engine could recognize "bold the text world". If the user highlighted "hello", and the application changed the active text selection only contain "hello", "bold the text world" would fail to recognize.

The application should change the active text selection when the text highlight changes, rather than the entire word sequence data, to ensure the SR engine has a textual context to help the recognition language model.

See also ISpRecoGrammar::SetWordSequenceData for information on how to set the text data.

The SR engine must support text buffer features. Check for the presence of the TextBuffer attribute in the SR engine. Microsoft SR ASR engines support these features although there is no requirement that other manufacturers engines need to. See Recognizers in Object Tokens and Registry Settings for more information.

Example

The following code snippet illustrates how to use ISpRecoGrammar::SetTextSelection after sending a text buffer to the SR engine using ISpRecoGrammar::SetWordSequenceData.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoContext>      cpRecoContext;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
SPTEXTSELECTIONINFO          tsi;
DWORD                        cch = 0;
WCHAR                        *pwszCoMem = L"";
WCHAR                        *pwszCoMem2;

// Place the contents of text buffer into pwszCoMem
// and the length of the text into cch:
tsi.ulStartActiveOffset = 0;
tsi.cchActiveChars = cch;
tsi.ulStartSelection = 0;
tsi.cchSelection = cch;

pwszCoMem2 = (WCHAR *)CoTaskMemAlloc(sizeof(WCHAR) * (cch + 2));

if (SUCCEEDED(hr) && pwszCoMem2)
{
   // SetWordSequenceData requires double NULL terminator:
   memcpy(pwszCoMem2, pwszCoMem, sizeof(WCHAR) * cch);
   pwszCoMem2[cch] = L'\0';
   pwszCoMem2[cch+1] = L'\0';

   // Set the text buffer data.
   hr = cpRecoGrammar->SetWordSequenceData(pwszCoMem2, cch + 2, NULL);
}

if (SUCCEEDED(hr))
{
   // Set the text selection information.
   hr = cpRecoGrammar->SetTextSelection(&tsi);
}

if (SUCCEEDED(hr))
{
   // The SR engine is now capable of recognizing
   // the contents of the text buffer.
}

// Release system resources:
CoTaskMemFree(pwszCoMem2);
CoTaskMemFree(pwszCoMem);


ISpRecoGrammar::IsPronounceable (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::IsPronounceable

ISpRecoGrammar::IsPronounceable calls the SR engine object to determine if the word has a pronunciation.

HRESULT IsPronounceable(
   LPCWSTR                *pszWord,
   SPWORDPRONOUNCEABLE    *pfPronounceable
);

Parameters

pszWord
[in, string] The word to test. Length must be equal to or less than SP_MAX_WORD_LENGTH.
pfPronounceable
[out] Flag, from among the following list, indicating the if the word is pronounceable by the SR engine. See Remarks section.
Value | Description
SPWP_UNKNOWN_WORD_UNPRONOUNCEABLE | The word is not pronounceable by the SR engine, and is not located in the lexicon and/or the engine's dictionary.
SPWP_UNKNOWN_WORD_PRONOUNCEABLE | The word is pronounceable by the SR engine, but is not located in the lexicon and/or the engine's dictionary.
SPWP_KNOWN_WORD_PRONOUNCEABLE | The word is pronounceable by the SR engine, and is located in the lexicon and/or the engine's dictionary.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Either pszWord or pfPronounceable is invalid or bad.
FAILED (hr) | Appropriate error message.

Remarks

The exact implementation and usage for the SR engine's dictionary and pronounceable words may vary between engines. For example, an SR engine may attempt to pronounce all words passed using ::IsPronounceable, even if it is not located in the lexicon or the dictionary, it would rarely or never, return SPWP_UNKNOWN_WORD_UNPRONOUNCEABLE.

Typically, there are two scenarios when an application might use the method ::IsPronounceable.

If an application is using a number of specialized or uncommon words (e.g., legal, medical, or scientific terms), the application may want to verify that the words are contained in either the lexicon (see also ISpLexicon) or the SR engine's dictionary. If the words are not contained in the lexicon or the dictionary (even if they are pronounceable), the application can add them to the lexicon to improve the chances of a successful recognition.

An application may also want to verify that the SR engine will actually recognize the words in a CFG (even though loading the CFG succeeded). If the SR engine returns SPWP_UNKNOWN_WORD_UNPRONOUNCEABLE, the application can update the lexicon pronunciation entry (see ISpLexicon).

Example

The following code snippet illustrates the use of ISpRecoGrammar:IsPronounceable. The words used are examples only, as the pronounceability by different SR engines may vary. See Remarks section.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
SPWORDPRONOUNCEABLE          wordPronounceable;

// Check if a common word is pronounceable.
hr = cpRecoGrammar->IsPronounceable(L"hello", &wordPronounceable);

if (SUCCEEDED(hr))
{
   // wordPronounceable is probably equal to SPWP_KNOWN_WORD_PRONOUNCEABLE.

   // Check if an uncommon or imaginary word is pronounceable.
   hr = cpRecoGrammar->IsPronounceable(L"snork", &wordPronounceable);
}

if (SUCCEEDED(hr))
{
   // wordPronounceable is probably equal to SPWP_UNKNOWN_WORD_PRONOUNCEABLE.

   // Check if a non-word or imaginary word is unpronounceable.
   hr = cpRecoGrammar->IsPronounceable(L"lpdzsd", &wordPronounceable);
}

if (SUCCEEDED(hr))
{
   // wordPronounceable is probably equal to SPWP_UNKNOWN_WORD_UNPRONOUNCEABLE.
}


ISpRecoGrammar::SetGrammarState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::SetGrammarState

ISpRecoGrammar::SetGrammarState sets the grammar state.

HRESULT SetGrammarState(
   SPGRAMMARSTATE   eGrammarState
);

Parameters

eGrammarState
[in] Flag of type SPGRAMMARSTATE indicating the new state of the grammar.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | eGrammarState is not a valid state.
FAILED(hr) | Appropriate error message.

Remarks

If eGrammarState is SPGS_DISABLED, the speech platform will retain the current rule activation state, so that when the grammar state is set to SPGS_ENABLED, it restores the grammar rules back to each of the original activation states. While the grammar is set to SPGS_DISABLED, the application can still activate and deactivate rule. The effect is not communicated to the SR engine (but retained by the speech platform) until the grammar is enabled again.

If eGrammarState is SPGS_EXCLUSIVE, the speech platform will disable all other grammars in the system, unless another grammar is already exclusive. Activation and deactivation commands are buffered for all other grammars until the exclusive grammar is set to SPGS_ENABLED again.

The default grammar state is SPGS_ENABLED, meaning the grammar can receive recognitions.

Applications can use the grammar state to control whether it will receive recognitions for rules in that SpRecoGrammar object. For example, an application create a new SpRecoGrammar object, set the grammar state to SPGS_DISABLED, dynamically generate the rules, and finally set the grammar state to SPFS_ENABLED when grammar construction is completed.

See also ISpRecoGrammar::GetGrammarState.

Example

The following code snippet illustrates the use of ISpRecoGrammar::SetGrammarState to set the state of an grammar

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
CComPtr<ISpRecoContext>      cpRecoContext;
ULONGLONG                    ullGramId = 1;

// Create a new grammar object.
hr = cpRecoContext->CreateGrammar(ullGramId, &cpRecoGrammar);

if (SUCCEEDED(hr))
{
   // Disable the grammar so that recognitions are not received.
   hr = cpRecoGrammar->SetGrammarState(SPGS_DISABLED);
}

if (SUCCEEDED(hr))
{
   // ... Build the grammar ...

   // Activate the grammar so applications start receiving recognitions.
   hr = cpRecoGrammar->SetGrammarState(SPGS_ENABLED);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoGrammar::SaveCmd (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::SaveCmd

ISpRecoGrammar::SaveCmd allows applications using dynamic grammars to save the current grammar state to a stream.

HRESULT SaveCmd(
   IStream                                   *pSaveStream,
   [annotation ("__deref_opt_out")]LPWSTR   **ppCoMemErrorText
);

Parameters

pSaveStream
[in] The stream to save the compiler binary grammar into.
ppCoMemErrorText
[out] Optional parameter of a null-terminated string containing error messages that occurred during the save operation.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pSaveStream is invalid or bad.
SPERR_NOT_DYNAMIC_GRAMMAR | Command was loaded but compiler is not available.
SPERR_UNINITIALIZED | Compiler is not available.
E_POINTER | ppCoMemErrorText is invalid or bad.
FAILED (hr) | Appropriate error message.

Remarks

Applications can use ::SaveCmd to serialize grammar changes that were made at run time for use at a later time. See also ISpRecoGrammar::LoadCmdFromMemory.

Example

The following code snippet illustrates how to use ISpRecoGrammar::SaveCmd to serialize the CFG from one SpRecoGrammar object and deserialize it into another SpRecoGrammar object.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
CComPtr<ISpRecoGrammar>      cpReloadedGrammar;
CComPtr<ISpRecoContext>      cpRecoContext;
CComPtr<IStream>             cpHStream;
HGLOBAL                      hGrammar;

// Build and use a SpRecoGrammar object...

// Create a Win32 global stream.
hr = ::CreateStreamOnHGlobal(NULL, true, &cpHStream);

if (SUCCEEDED(hr))
{
   // Save the current grammar to the global stream.
   hr = cpRecoGrammar->SaveCmd(cpHStream, NULL);
}

if (SUCCEEDED(hr))
{
   // Create the second grammar to deserialize into.
   hr = cpRecoContext->CreateGrammar(0, &cpReloadedGrammar);
}

if (SUCCEEDED(hr))
{
   // Get a handle to the stream with the serialized grammar.
   ::GetHGlobalFromStream(cpHStream, &hGrammar);
}

// Deserialize the CFG into a new grammar object.
hr = cpReloadedGrammar->LoadCmdFromMemory((SPBINARYGRAMMAR *)::GlobalLock(hGrammar), SPLO_DYNAMIC);

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoGrammar::GetGrammarState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar::GetGrammarState

ISpRecoGrammar::GetGrammarState retrieves the current state of the recognition grammar.

The default grammar state is SPGS_ENABLED.

See also ISpRecoGrammar::SetGrammarState

HRESULT GetGrammarState(
  SPGRAMMARSTATE   *peGrammarState
);

Parameters

peGrammarState
[out] Address of the SPGRAMMARSTATE enumeration that receives the grammar state information.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | One of the pointers is invalid or bad.
FAILED(hr) | Appropriate error message.

Example

The following code snippet illustrates the use of ISpRecoGrammar::GetGrammarState to query the default state of an SpRecoGrammar object.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoGrammar>      cpRecoGrammar;
CComPtr<ISpRecoContext>      cpRecoContext;
ULONGLONG                    ullGrammarId = 0;
SPGRAMMARSTATE               grammarState;

// Create a new grammar object.
hr = cpRecoContext->CreateGrammar(ullGrammarId, &cpRecoGrammar);

if (SUCCEEDED(hr))
{
   // Query the default grammar state.
   hr = cpRecoGrammar->GetGrammarState(&grammarState);
}

if (SUCCEEDED(hr))
{
   // ASSERT that grammarState = SPGS_ENABLED.
}


ISpRecoGrammar2 (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar2

New in SAPI 5.3

Extends the ISpRecoGrammar interface.

Methods in Vtable Order

ISpRecoGrammar2 Methods | Description
SetGrammarLoader | Is used to pass a pointer to an ISpeechResourceLoader interface into SAPI to override SAPI's default grammar loading function.
SetSMLSecurityManager | Lets a SAPI application manage its own security policy.
GetRules | Is used to discover the list of public rules in the grammar.
LoadCmdFromFile2 | Loads a SAPI 5 grammar from a file. This is an extended version of the ISpRecoGrammar::LoadCmdFromFile method.
LoadCmdFromMemory2 | Loads a compiled CFG binary from memory. This is an extended version of the ISpRecoGrammar::LoadCmdFromMemory method.
SetRulePriority | Sets the priority on the specified rule.
SetRuleWeight | Sets the weight on the specified rule.
SetDictationWeight | Sets the weight on the dictation rule.


ISpRecoGrammar2::SetGrammarLoader (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar2::SetGrammarLoader

ISpRecoGrammar2::SetGrammarLoader is used to pass a pointer to an ISpeechResourceLoader interface into SAPI to override SAPI's default grammar loading function. Applications that wish to perform grammar loading, rather than leave this to SAPI, can do so by implementing ISpeechResourceLoader.

HRESULT SetGrammarLoader(
   ISpeechResourceLoader    *pLoader
);

Parameters

pLoader
The pointer to the ISpeechResourceLoader interface implemented by an application.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pLoader is invalid.
SPERR_NOT_SUPPORTED_FOR_SHARED_RECOGNIZER | The method called is not supported for the shared recognizer.
E_NOTIMPL | The interface is not implemented.


ISpRecoGrammar2::SetSMLSecurityManager (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar2::SetSMLSecurityManager

ISpRecoGrammar2::SetSMLSecurityManager lets a SAPI application manage its own security policy.

By default, SAPI uses Windows' URLMON to determine the security rights of semantic interpretation scripts in SRGS grammars. However, an application may desire to override this with its own security policy, by implementing their own IInternetSecurityManager interface. IInternetSecurityManager is defined by URLMON.

HRESULT SetSMLSecurityManager(
   IInternetSecurityManager    *pSMLSecurityManager
);

Parameters

pSMLSecurityManager
The pointer to the application's implementation of the IInternetSecurityManager interface.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pSMLSecurityManager is invalid.
SPERR_NOT_SUPPORTED_FOR_SHARED_RECOGNIZER | The method called is not supported for the shared recognizer.
E_NOTIMPL | The interface is not implemented.


ISpRecoGrammar2::GetRules (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar2::GetRules

ISpRecoGrammar2::GetRules is used to discover the list of public rules in the grammar.

HRESULT GetRules(
   SPRULE     **ppCoMemRules,
   UINT        *puNumRules
);

Parameters

ppCoMemRules
Returns an array of SPRULE structures.
puNumRules
Returns the number of SPRULE structures in the ppCoMemRules array.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One of the parameters is invalid.
FAILED(hr) | Appropriate error message.


ISpRecoGrammar2::LoadCmdFromFile2 (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar2::LoadCmdFromFile2

ISpRecoGrammar2::LoadCmdFromFile2 loads a SAPI 5 grammar from a file and extends the ISpRecoGrammar::LoadCmdFromFile function.

HRESULT LoadCmdFromFile2(
   LPCWSTR           pszFileName,
   SPLOADOPTIONS     Options,
   LPCWSTR           pszSharingUri,
   LPCWSTR           pszBaseUri
);

Parameters

pszFileName
The file name of the grammar.
Options
Flag of type SPLOADOPTIONS indicating whether the grammar will be modified dynamically.
pszSharingUri
Indicates that it is a dynamic shared grammar. Other grammars in the same recognizer can reference this grammar at runtime using this URI.
pszBaseUri
The base path that any relative rule references within the grammar are resolved against.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One of the parameters is invalid.
FAILED(hr) | Appropriate error message.


ISpRecoGrammar2::LoadCmdFromMemory2 (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar2::LoadCmdFromMemory2

ISpRecoGrammar2::LoadCmdFromMemory2 loads a compiled CFG binary from memory and extends the ISpRecoGrammar::LoadCmdFromMemory function.

HRESULT LoadCmdFromMemory2(
   const SPBINARYGRAMMAR    *pGrammar,
   SPLOADOPTIONS             Options,
   LPCWSTR                   pszSharingUri,
   LPCWSTR                   pszBaseUri
);

Parameters

pGrammar
A pointer to the grammar in memory.
Options
Flag of type SPLOADOPTIONS indicating whether the grammar will be modified dynamically.
pszSharingUri
Indicates that it is a dynamic shared grammar. Other grammars in the same recognizer can reference this grammar at runtime using this URI.
pszBaseUri
The base path that any relative rule references within the grammar are resolved against.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One of the parameters is invalid.
FAILED(hr) | Appropriate error message.


ISpRecoGrammar2::SetRulePriority (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar2::SetRulePriority

ISpRecoGrammar2::SetRulePriority sets the priority on the specified rule.

HRESULT SetRulePriority(
   LPCWSTR    pszRuleName,
   ULONG      ulRuleId,
   int        nRulePriority
);

Parameters

pszRuleName
The name of the rule.
ulRuleId
The ID number of the rule.
nRulePriority
The priority to be assigned to the rule (between -128 and + 127). When a given utterance satisfies more than one rule, the recognizer applies the rule with the highest priority. When an utterance satisfies several rules with the same priority, or several rules with no priority, the recognizer applies the most recently activated rule.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One of the parameters is invalid.
FAILED(hr) | Appropriate error message.


ISpRecoContext2::SetRuleWeight (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoContext2::SetRuleWeight

ISpRecoContext2::SetRuleWeight sets the weight on the specified rule.

HRESULT SetRuleWeight(
   LPCWSTR    pszRuleName,
   ULONG      ulRuleId,
   float      flWeight
);

Parameters

pszRuleName
The name of the rule.
ulRuleId
The ID number of the rule.
flWeight
A floating point number between 0 and 1. A higher number biases the recognizer to favour this rule over another rule when the developer knows that one rule is more likely to be uttered than the other. This is used to tune the accuracy of an application.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One of the parameters is invalid.
FAILED(hr) | Appropriate error message.


ISpRecoGrammar2::SetDictationWeight (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoGrammar2::SetDictationWeight

ISpRecoGrammar2::SetDictationWeight sets the weight on the dictation rule.

HRESULT SetDictationWeight(
   float   flWeight
);

Parameters

flWeight
A floating point number between 0 and 1. A higher number biases the recognizer to favour dictation over CFG rules when the developer knows that dictation is more likely to be uttered than the rule (or vice versa).

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One of the parameters is invalid.
FAILED(hr) | Appropriate error message.


ISpRecoResult (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoResult

The ISpRecoResult interface is used by an application to retrieve information about the SR engine's hypotheses, recognitions, and false recognitions.

The most common use of the ISpRecoResult interface is retrieval of text recognized by the SR engine (see ISpPhrase::GetText). The ISpRecoResult interface also supports the retrieval of the original audio that the SR engine recognized. SAPI can automatically retain the audio for an application using ISpRecoContext::SetAudioOptions.

An application can set interest in SR engine hypotheses by calling ISpEventSource::SetInterest with SPEI_HYPOTHESIS. As each hypothesis event is received, the application can examine the proposed text and update its UI to display dynamic run-time recognition status.

An application can set interest in the SR engine's failed recognitions by calling ISpEventSource::SetInterest with SPEI_FALSE_RECOGNITION. If a false recognition occurs, the application can examine the audio (or even a partial recognition result) to reprocess the recognition or attempt to process the partially recognized text. SAPI does not require that an SR engine send a phrase with the false recognition event.

ISpRecoResult Methods | Description
ISpPhrase | Inherits from ISpPhrase and those methods are accessible from an ISpRecoResult object.
GetResultTimes | Retrieves the time information associated with the result.
GetAlternates | Retrieves an array containing alternate phrases.
GetAudio | Creates an audio stream for a given number of elements.
SpeakAudio | Retrieves and speaks the specified audio.
Serialize | Creates a serialized copy of the recognition result object.
ScaleAudio | Converts the format of the retained audio to a different audio format.
GetRecoContext | Returns the recognition context object that is associated with this result.


ISpRecoResult::GetResultTimes (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoResult::GetResultTimes

ISpRecoResult::GetResultTimes retrieves the time information associated with the result.

HRESULT GetResultTimes(
   SPRECORESULTTIMES   *pTimes
);

Parameters

pTimes
[out] Address of the SPRECORESULTTIMES data structure containing the time information associated with the result.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pTimes is invalid or bad.
SPERR_NOT_FOUND | Interface not found.

Remarks

An application can use ::GetResultTimes to determine the system time that a recognition occurred, the length in seconds of the recognized phrase, and the length of time between when the SR engine began listening and when the recognition occurred.


ISpRecoResult::GetAlternates (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoResult::GetAlternates

ISpRecoResult::GetAlternates retrieves an array of pointers to ISpPhraseAlt objects containing alternate phrases.

HRESULT GetAlternates(
   ULONG           ulStartElement,
   ULONG           cElements,
   ULONG           ulRequestCount,
   ISpPhraseAlt  **ppPhrases,
   ULONG          *pcPhrasesReturned
);

Parameters

ulStartElement
[in] The starting element to consider for the alternates. This is a zero-based value.
cElements
[in] The number of elements to consider. All elements can be requested using the enumeration value SPPR_ALL_ELEMENTS of type SPPHRASERNG.
ulRequestCount
[in] The number of requested alternate phrase elements.
ppPhrases
[out] Address of an array of ISpPhraseAlt interface pointers that contain the alternate phrases. The elements between the start of the ulStartElement element and the end of the ulStartElement and cElements element combined is the portion that will change. The rest of the elements will be included in each alternate phrase.
pcPhrasesReturned
[out] Pointer to a ULONG that receives the actual number of alternate phrases retrieved.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pcPhrasesReturned is an invalid pointer. However, ppPhrases does not contain ulRequestCount allocations.
E_OUTOFMEMORY | Exceeded available memory.
E_INVALIDARG | ulStartElement is not less than the number of elements in the owning interface. However, the number of expected elements exceeds the number of available elements in the owning interface.
S_FALSE | No analyzer is present or there is no driver data.
FAILED(hr) | Appropriate error message.

Example

The following code snippet illustrates the use ISpRecoResult::GetAlternates to retrieve and commit an alternate phrase.

// Declare local identifiers:
HRESULT                    hr = S_OK;
const USHORT               MY_MAX_ALTERNATES = 10;
CComPtr<ISpRecoResult>     cpRecoResult;
CComPtr<ISpPhrase>         cpPhrase;
CComPtr<ISpPhraseAlt>      pcpPhraseAlt[MY_MAX_ALTERNATES];
SPPHRASE                   *pPhrase;
WCHAR                      *pwszText;
WCHAR                      *pwszAlternate;
BOOL                       fMoreAppropriate;
LONG                       ulCount;

// ... Obtain a recognition result object from the recognizer ...

// Get the recognized phrase object.
hr = cpRecoResult->GetPhrase(&pPhrase);

if (SUCCEEDED(hr))
{
   // Get the phrase's text.
   hr = cpPhrase->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &pwszText, NULL);
}

if (SUCCEEDED(hr))
{
   // Check the phrase's text... Assume that
   // the phrase isn't a correct recognition.

   // Get the top MY_MAX_ALTERNATES alternates
   // to the entire recognized phrase.
   hr = cpRecoResult->GetAlternates(pPhrase->Rule.ulFirstElement,
        pPhrase->Rule.ulCountOfElements,
        MY_MAX_ALTERNATES,
        (ISpPhraseAlt**) pcpPhraseAlt,
        &ulCount);
}

if (SUCCEEDED(hr))
{
   // Check each alternate in order of highest likelihood.
   for (int i = 0; i < ulCount; i++)
   {
      hr = pcpPhraseAlt[i]->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &pwszAlternate, NULL);

      if (SUCCEEDED(hr))
      {
         // ... Check if this alternate is more appropriate ...

         // If it is more appropriate, then commit the alternate--
         if (fMoreAppropriate)
         {
            hr = pcpPhraseAlt[i]->Commit();
         }

         if (SUCCEEDED(hr))
         {
            // Release system resources:
            if (pwszAlternate) ::CoTaskMemFree(pwszAlternate);
            if (pwszText) ::CoTaskMemFree(pwszText);
         }
      }
   }
}

// Free the initial phrase object.
if (pPhrase) ::CoTaskMemFree(pPhrase);


ISpRecoResult::GetAudio (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoResult::GetAudio

ISpRecoResult::GetAudio creates an audio stream of the requested words from the audio data in the result object.

HRESULT GetAudio(
   ULONG              ulStartElement,
   ULONG              cElements,
   ISpStreamFormat  **ppStream
);

Parameters

ulStartElement
[in] Value specifying from which element in the result data to start the audio stream.
cElements
[in] Value specifying the total number of words.
ppStream
[out] Address that will receive a pointer to an ISpStreamFormat object containing the audio data requested.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | cElements is zero or the expected number of elements to count exceeds the number available.
E_POINTER | ppStream is an invalid pointer.
SPERR_NO_AUDIO_DATA | This result object does not have any audio data.
FAILED(hr) | Appropriate error message.

Remarks

Even if there are no elements, that is, ulStartElement = 0 and cElements = 0, the audio will still be played. There are "unrecognized" results that have no elements but have audio.

An application can find the time offsets for each element by examining the SPPHRASE object retrieved using ISpRecoResult::GetPhrase.

Example

The following code snippet illustrates the use ISpRecoResult::GetAudio to retrieve the retained audio.

// Declare local identifiers:
HRESULT                       hr = S_OK;
CComPtr<ISpRecoResult>        cpRecoResult;
CComPtr<ISpStreamFormat>      cpStreamFormat;
GUID                          formatId;
WAVEFORMATEX                  *pWaveFormatEx;

// ... Obtain a recognition result object from the recognizer ...
hr = cpRecoResult->GetAudio(0, 0, &cpStreamFormat);

if (SUCCEEDED(hr))
{
   // Check the format of the stream.
   hr = cpStreamFormat->GetFormat(&formatId, &pWaveFormatEx);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoResult::SpeakAudio (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoResult::SpeakAudio

ISpRecoResult::SpeakAudio retrieves and speaks the specified audio. This combines two other methods; first calling ISpRecoResult::GetAudio and then calling ISpVoice::SpeakStream on the parent recognition context.

HRESULT SpeakAudio(
   ULONG    ulStartElement,
   ULONG    cElements,
   DWORD    dwFlags,
   ULONG   *pulStreamNumber
);

Parameters

ulStartElement
[in] Value specifying with which element to start.
cElements
[in] Value specifying the number of elements contained in the stream. A value of zero speaks all elements.
dwFlags
[in] Value indicating the attributes of the text stream. These values are contained in the SPEAKFLAGS enumeration.
pulStreamNumber
[optional, out] Address of a variable containing the stream number information. If NULL, the stream number will not be retrieved.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_NO_AUDIO_DATA | Result does not contain audio data.
E_POINTER | pulStreamNumber is a non-NULL, bad pointer.
FAILED(hr) | Appropriate error message.
Return values may also be those from ISpVoice::SpeakStream.

Remarks

Even if there are no elements, that is, ulStartElement = 0 and cElements = 0, the audio will still be spoken. These are unrecognized results that have no elements, but do have audio.

If the application did not activate retained audio (see ISpRecoContext::SetAudioOptions), or make a previous call to ISpPhrase::Discard and eliminate the retained audio, ::SpeakAudio will fail with SPERR_NO_AUDIO_DATA.

Example

The following code snippet illustrates the use of ISpRecoResult::SpeakAudio.

// Declare local identifiers:
HRESULT                       hr = S_OK;
CComPtr<ISpRecoResult>        cpRecoResult;
ULONG                         ulStreamNum = 1;

// ... Get a recognition result object from the SR engine ...

// Replay the user's spoken audio to the user.
hr = cpRecoResult->SpeakAudio(0, 0, 0, &ulStreamNum);

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoResult::Serialize (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoResult::Serialize

ISpRecoResult::Serialize creates a serialized copy of the recognition result object. The serialized copy can be saved and later restored using ISpRecoContext::DeserializeResult.

HRESULT Serialize(
   SPSERIALIZEDRESULT   **ppCoMemSerializedResult
);

Parameters

ppCoMemSerializedResult
[out] Address of a pointer to the SPSERIALIZEDRESULT structure that receives the serialized result information. Call CoTaskMemFree() to free the memory associated with the serialized result object.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppCoMemSerializedResult is an invalid pointer.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.

Example

The following code snippet illustrates the use ISpRecoResult::Serialize to serialize a result and deserialize it back into an ISpRecoContext object.

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpRecoResult>     cpRecoResult;
CComPtr<ISpRecoResult>     cpRecoResultNew;
CComPtr<IStream>           cpStreamWithResult;
CComPtr<ISpRecoContext>    cpRecoContext;
SPSERIALIZEDRESULT*        pSerializedResult = NULL;
ULONG                      cbWritten = 0;
ULONG                      ulSerializedSize = 0;
LARGE_INTEGER              liseek;
LARGE_INTEGER              li;

// ... Obtain a recognition result object from the recognizer ...
hr = CreateStreamOnHGlobal(NULL, true, &cpStreamWithResult);

if (SUCCEEDED(hr))
{
   // Serialize result to memory.
   hr = cpRecoResult->Serialize(&pSerializedResult);
}

if (SUCCEEDED(hr))
{
   // Serialize to a stream pointer.
   hr = cpStreamWithResult->Write(pSerializedResult, pSerializedResult->ulSerializedSize, &cbWritten);
}

if (SUCCEEDED(hr))
{
   // Free the serialized result.
   if (pSerializedResult) ::CoTaskMemFree(pSerializedResult);

   // Commit the stream changes.
   hr = cpStreamWithResult->Commit(STGC_DEFAULT);
}

if (SUCCEEDED(hr))
{
   // ... Persist stream to disk, network share, etc ...
   // ... Shutdown application ...
   // ... Restart application and get the persisted stream ...

   // Reset the stream seek pointer to the start before deserialization:
   li.QuadPart = 0;
   hr = cpStreamWithResult->Seek(li, STREAM_SEEK_SET, NULL);
}

if (SUCCEEDED(hr))
{
   // Find the size of the stream.
   hr = cpStreamWithResult->Read(&ulSerializedSize, sizeof(ULONG), NULL);
}

if (SUCCEEDED(hr))
{
   // Reset the seek pointer:
   liseek.QuadPart = 0 - sizeof(ULONG);
   hr = cpStreamWithResult->Seek(liseek, STREAM_SEEK_CUR, NULL);
}

if (SUCCEEDED(hr))
{
   // Allocate the memory for the result.
   pSerializedResult = (SPSERIALIZEDRESULT*)::CoTaskMemAlloc(ulSerializedSize);

   // Check pSerializedResult in case out "out-of-memory".

   // Copy the stream into a serialized result object.
   hr = cpStreamWithResult->Read(pSerializedResult, ulSerializedSize, NULL);
}

if (SUCCEEDED(hr))
{
   // Deserialize result from memory.
   hr = cpRecoContext->DeserializeResult(pSerializedResult, &cpRecoResultNew);
}

if (SUCCEEDED(hr))
{
   // Free the pSerializedResult memory.
   if (pSerializedResult) CoTaskMemFree(pSerializedResult);
}

// As long as the same engine was used to generate original
// result object, as is now being used, applications can
// now get alternates for the cpRecoResultNew's phrase.


ISpRecoResult::ScaleAudio (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoResult::ScaleAudio

ISpRecoResult::ScaleAudio converts an existing audio stream into a different audio format.

HRESULT ScaleAudio(
  const GUID           *pAudioFormatId,
  const WAVEFORMATEX   *pWaveFormatEx
);

Parameters

pAudioFormatId
[in] Address of the data format identifier. Typically, this value is SPDFID_WaveFormatEx.
pWaveFormatEx
[in] Address of the WAVEFORMATEX structure that contains the audio format to convert to. This value must be NULL if pAudioFormatId is not specified as SPDFID_WaveForamtEx.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Either pAudioFormatId or pWaveFormatEx is invalid or bad.
SPERR_NO_AUDIO_DATA | Audio stream is unavailable.
SPERR_UNSUPPORTED_FORMAT | The engine format is non-waveformatex and the retained format the same format.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.

Remarks

Use the ISpPhrase::Discard method to completely discard audio data associated with a result object.

The application can also set the default retained audio format for the ISpRecoResult object by calling ISpRecoContext::SetAudioOptions. Calling ::SetAudioOptions will only apply to all subsequent recognitions, not the current ISpRecoResult object.

When performing a scaling with a compressed format, it is possible to introduce small rounding errors, since the content of the audio is not used to perform the conversion.

Scaling between certain compressed formats is not supported by the SAPI format converter (See the Remarks section for ISpStreamFormatConverter).

Example

The following code snippet illustrates the use ISpRecoResult::ScaleAudio to scale the audio to a low quality format before serialization to the disk (to save space).

// Declare local identifiers:
HRESULT                       hr = S_OK;
CComPtr<ISpRecoContext>       cpRecoContext;
CComPtr<ISpRecoResult>        cpRecoResult;
SPSERIALIZEDRESULT*           pSerializedResult = NULL;

// ... Obtain a recognition result object from the recognizer ...

// Create a format helper with a very low quality format.
CSpStreamFormat ScaleFormat(SPSF_8kHz8BitMono, &hr);

if (SUCCEEDED(hr))
{
   hr = cpRecoResult->ScaleAudio(&(ScaleFormat.FormatId()), ScaleFormat.WaveFormatExPtr());
}

if (SUCCEEDED(hr))
{
   // Serialize the result.
   hr = cpRecoResult->Serialize(&pSerializedResult);
}

if (SUCCEEDED(hr))
{
   // Write pSerializedResult to the disk.
}

Remarks

For information about the stream formats supported by SAPI, see SPSTREAMFORMAT.

See the CSpStreamFormat class for information about managing stream formats and WAVEFORMATEX structures.


ISpRecoResult::GetRecoContext (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoResult::GetRecoContext

ISpRecoResult::GetRecoContext returns the recognition context object that is associated with this result.

HRESULT GetRecoContext(
   ISpRecoContext   **ppRecoContext
);

Parameters

ppRecoContext
[out] A pointer that receives the recognition context interface pointer. The caller must call ::Release on the ISpRecoContext references when it is finished.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppRecoContext is invalid or bad.
FAILED(hr) | Appropriate error message.

Example

The following code snippet illustrates the use of ISpRecoResult::GetRecoContext to retrieve a reference to the ISpRecoContext instance that is associated with a recognized phrase and determine the maximum number of CFG alternates that can be generated for it.

// Declare local identifiers:
HRESULT                       hr = S_OK;
CComPtr<ISpRecoContext>       cpRecoContext;
CComPtr<ISpRecoResult>        cpRecoResult;
DWORD                         dwMaxAlternates;

// ... Obtain a recognition result object from the recognizer ...

// Get the associated ISpRecoContext.
hr = cpRecoResult->GetRecoContext(&cpRecoContext);

if (SUCCEEDED(hr))
{
   // Get maximum number of CFG alternates.
   hr = cpRecoContext->GetMaxAlternates(&dwMaxAlternates);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecoResult2 (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoResult2

New in SAPI 5.3

Extends the ISpRecoResult interface.

Methods in Vtable Order

ISpRecoResult2 Methods | Description
CommitAlternate | Instructs the alternate analyzer to update the speech recognition (SR) engine's acoustic and/or language model based on the alternate phrase, without updating the reco result.
CommitText | Commits some new text for recognizer learning.
SetTextFeedback | Provides text to the OS's built-in speech user experience's GUI to display to the user.


ISpRecoResult2::CommitAlternate (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoResult2::CommitAlternate

ISpRecoResult2::CommitAlternate instructs the alternate analyzer to update the speech recognition (SR) engine's acoustic and/or language model based on the alternate phrase, without updating the reco result.

HRESULT CommitAlternate(
   ISpPhraseAlt      *pPhraseAlt,
   ISpRecoResult    **ppNewResult
);

Parameters

pPhraseAlt
The alternate to be used when updating the model.
ppNewResult
The recognizer returns a new result containing the alternate.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One of the parameters is invalid.
SPERR_ENGINE_RESPONSE_INVALID | Arguments or data supplied by the engine are in an invalid format or are inconsistent.
FAILED(hr) | Appropriate error message.


ISpRecoResult2::CommitText (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoResult2::CommitText

ISpRecoResult2::CommitText commits some new text for recognizer learning.

HRESULT CommitText(
   ULONG      ulStartElement,
   ULONG      cElements,
   LPCWSTR    pszCorrectedData,
   DWORD      eCommitFlags
);

Parameters

ulStartElement
The first element to replace.
cElements
The number of elements to replace.
pszCorrectedData
The corrected text.
eCommitFlags
One or more values from the SPCOMMITFLAGS enumeration that indicate the nature of the correction.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One of the parameters is invalid.


ISpRecoResult2::SetTextFeedback (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecoResult2::SetTextFeedback

ISpRecoResult2::SetTextFeedback provides text to the operating system's built-in speech user experience's GUI to display to the user.

HRESULT SetTextFeedback(
   LPCWSTR    pszFeedback,
   BOOL       fSuccessful
);

Parameters

pszFeedback
The text to display.
fSuccessful
Indicates whether the recognition was acted on or rejected.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pszFeedback is invalid.
FAILED(hr) | Appropriate error message.


ISpRecognizer (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer

The ISpRecognizer interface enables applications to control aspects of the speech recognition (SR) engine. Each ISpRecognizer interface represents a single SR engine. The application can connect to each recognizer object one or more recognition contexts, from which the application can control the recognition grammars to be used, start and stop recognition, and receive events and recognition results. The ISpRecognizer interface allows some additional control of the SR engine and its audio input. A standard application may not need to call many of the methods on this interface as SAPI tries to set the engine up sensibly by default.

There are two implementations of the ISpRecognizer and ISpRecoContext in SAPI. One is for recognition "in-process" (InProc), where the SR engine is created in the same process as the application. Only this application can connect to this recognizer. The other implementation is the "shared-recognizer," where the SR engine is created in a separate process. There will only be one shared engine running on a system, and all applications using the shared engine connect to the same recognizer. This allows several speech applications to work simultaneously, and allows the user to speak to any application, as recognition is done from the grammars of all applications. For desktop-based speech applications it is recommended to use the shared recognizer because of the way it allows multiple SAPI applications to work at once. For other types of application, such as recognizing from wave files or a telephony server application where multiple SR engines will be required, the InProc recognizer should be used.

When to Use

Call methods of the ISpRecognizer interface to configure or retrieve the attributes of the SR engine.

Implemented By
  • This interface is implemented by SAPI. Application developers use this interface but do not implement it.
How Created
There are two objects that implement this interface. These are created by applications by creating a COM object with either of the following CLSIDs:
  • SpInprocRecognizer (CLSID_SpInprocRecognizer)
  • SpSharedRecognizer (CLSID_SpSharedRecognizer)

Alternatively, the shared recognizer can be created by creating a SpSharedRecoContext (CLSID_SpSharedRecoContext), and then calling ISpRecoContext::GetRecognizer on this object to get a reference to the SpSharedRecognizer object.

Methods in Vtable Order

ISpRecognizer Methods | Description
ISpProperties | Inherits from ISpProperties and all those methods are accessible from ISpRecognizer.
SetRecognizer | Specifies the SR engine to be used.
GetRecognizer | Retrieves which SR engine is currently being used.
SetInput | Specifies which input stream the SR engine should use.
GetInputObjectToken | Retrieves the input token object for the stream.
GetInputStream | Retrieves the input stream.
CreateRecoContext | Creates a recognition context for this instance of an SR engine.
GetRecoProfile | Retrieves the current recognition profile token.
SetRecoProfile | Sets the recognition profile to be used by the recognizer.
IsSharedInstance | Determines if the recognizer is the shared or InProc implementation.
GetRecoState | Retrieves the state of the recognition engine.
SetRecoState | Sets the state of the recognition engine.
GetStatus | Retrieves current status information for the engine.
GetFormat | Retrieves the format of the current audio input.
IsUISupported | Checks if the SR engine supports a particular user interface component.
DisplayUI | Displays a user interface component.
EmulateRecognition | Emulates a recognition from a text phrase rather than from spoken audio.


ISpRecognizer::SetRecognizer (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::SetRecognizer

ISpRecognizer::SetRecognizer specifies the particular speech recognition engine to be used.

HRESULT SetRecognizer(
   ISpObjectToken   *pEngineToken
);

Parameters

pEngineToken
[in] The object token referring to the speech recognition engine to be used.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pEngineToken is invalid or bad.
SPERR_ENGINE_BUSY | Recognition is currently running or other applications are connected to the shared recognizer.
FAILED(hr) | Appropriate error message.

Remarks

This method allows the application to select a particular engine object token to be used (For example, the method SpFindBestToken could be used to find an engine supporting certain attributes, and the resulting token could be passed to this method).

If this method is not called, SAPI will use the current default SR engine.

If this method is passed NULL, SAPI will switch to the current default SR engine.

This method cannot be called when the current SR engine is already running and processing audio. In addition, when using the shared recognizer, it cannot be called if another application is also using the shared recognizer.


ISpRecognizer::GetRecognizer (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::GetRecognizer

ISpRecognizer::GetRecognizer retrieves the current speech recognition engine being used with this ISpRecognizer.

HRESULT GetRecognizer(
   ISpObjectToken   **ppEngineToken
);

Parameters

ppEngineToken
[out] The object token representing the current speech recognition engine.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppEngineToken is invalid or bad.
FAILED(hr) | Appropriate error message.


ISpRecognizer::SetInput (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::SetInput

ISpRecognizer::SetInput specifies which input stream the SR engine should use.

HRESULT SetInput(
   IUnknown  *pUnkInput,
   BOOL       fAllowFormatChanges
);

Parameters

pUnkInput
[in] The stream object token. See Remarks section.
fAllowFormatChanges
[in] Boolean indicating whether SAPI should try to change the input stream format to the engine's preferred format. This method can normally be set to TRUE; however, when performing both speech recognition and speech output at the simultaneously, some soundcards may require that both input and output are in the same audio format. Setting this to FALSE prevents the audio format on the input device from being changed. Instead, SAPI will try to convert the audio format itself to something the SR engine can use.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pUnkInput is invalid or not a stream.
SPERR_ENGINE_BUSY | The current method cannot be performed while the engine is currently processing audio.
FAILED(hr) | Appropriate error message.

Remarks

This method can be used to switch the input for the recognizer to a wave input stream, a different soundcard device, or to a custom audio object. The pUnkInput parameter can be a pointer to an object token representing an audio input device or a pointer to an actual object implementing ISpStreamFormat.

The input stream object will implement IStream, ISpStreamFormat, and ISpAudio for real-time streams. Applications should not use methods on these interfaces that actually change the state of the audio device or read data from it at the same time that the stream is being used by SAPI. For example, reading data from the application with IStream::Read will prevent the correct data from being passed to the SR engine. Altering the state of the audio using ISpAudio::SetState will put the audio device into an unexpected state and may cause errors. All control of the audio is done by SAPI.

When using the InProc recognizer, SAPI does not automatically setup the audio input. ISpRecognizer::SetInput must be called with a non-NULL pUnkInput to setup and start the audio input stream. Until ISpRecognizer::SetInput is called, methods such as ISpRecoGrammar::SetRuleState will return success code SP_STREAM_UNITIALIZED, but actual recognition will not start.

When using the shared recognizer, SAPI automatically sets up the audio input. However, ISpRecognizer::SetInput may be called with NULL as the pUnkInput parameter to force the recognizer to re-check the default audio input and re-set up the audio input (e.g., the default audio input object changes while recognizing, and the new audio input is to be used).

If the engine is currently processing audio, this call will fail with SPERR_ENGINE_BUSY.

Example

The following code snippet illustrates the use of ISpRecognizer::SetInput.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecognizer>       cpRecognizer;
CComPtr<ISpObjectToken>      cpObjectToken;
CComPtr<ISpAudio>            cpAudio;

// Set up the inproc recognizer audio
// input with an audio input object token.

// Get the default audio input token.
hr = SpGetDefaultTokenFromCategoryId(SPCAT_AUDIOIN, &cpObjectToken);

if (SUCCEEDED(hr))
{
   // Set the audio input to our token.
   hr = cpRecognizer->SetInput(cpObjectToken, TRUE);
}

if (SUCCEEDED(hr))
{
   // Set up the inproc recognizer audio input with an audio input object.

   // Create the default audio input object.
   hr = SpCreateDefaultObjectFromCategoryId(SPCAT_AUDIOIN, &cpAudio);
}

if (SUCCEEDED(hr))
{
   // Set the audio input to our object.
   hr = cpRecognizer->SetInput(cpAudio, TRUE);
}

if (SUCCEEDED(hr))
{
   // Ask the shared recognizer to re-check the default audio input token.
   hr = cpRecognizer->SetInput(NULL, TRUE);
}

if (SUCCEEDED(hr))
{
   // If hr = SPERR_ENGINE_BUSY, then retry later.
}


ISpRecognizer::GetInputObjectToken (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::GetInputObjectToken

ISpRecognizer::GetInputObjectToken retrieves the input token object for the stream currently being used.

GetInputObjectToken will always return the default audio input object token when using a shared recognizer.

HRESULT GetInputObjectToken(
   ISpObjectToken   **ppToken
);

Parameters

ppToken
[out] Gets filled in with the current input object token pointer.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | Function completed successfully, but the input stream object has no object token associated with it.
E_POINTER | ppToken is invalid or bad.
SPERR_UNINITIALIZED | No audio input has yet been set with SetInput (InProc engine only).
FAILED(hr) | Appropriate error message.

Remarks

Applications will not normally need to use this method, but it can be used to find out specific details of the object token that was used to create the audio input stream.

If an application receives feedback from the SR engine that recognition quality is low, (e.g., poor audio signal quality (see SPEI_INTERFERENCE, or that the microphone needs adjustment (see SPEI_REQUEST_UI), it may be helpful to reconfigure the audio input settings. SAPI defines two specific types of audio UI that an audio object token can provide: volume and properties. An application can use ::GetInputObjectToken, ISpObjectToken::IsUISupported, and ISpObjectToken::DisplayUI to display audio UI in an effort to improve speech recognition.

Example

The following code snippet illustrates the use of ISpRecognizer::GetInputObjectToken when displaying audio UI.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecognizer>       cpRecognizer;
CComPtr<ISpTokenUI>          cpTokenUI;
CComPtr<ISpObjectToken>      cpObjectToken;
BOOL                         fSupported;
const WCHAR                  *MY_AUDIO_DIALOG_TITLE = L"Foo Caption";
HWND                         hwndParent;

// Check if the current recognizer has an object token.
hr = cpRecognizer->GetInputObjectToken(&cpObjectToken);

if (SUCCEEDED(hr))
{
   // Get the object token's UI.
   hr = cpObjectToken->QueryInterface(&cpTokenUI);
}

if (SUCCEEDED(hr))
{
   // Check if default audio input object has UI for volume.
   hr = cpTokenUI->IsUISupported(SPDUI_AudioVolume, NULL, NULL, NULL, &fSupported);
}

if (SUCCEEDED(hr))
{
   // If fSupported == TRUE, then default audio input object has UI for Volume.

   // Display the default audio input object's Volume UI (you need
   // to have handle for hwndParent before executing next statement).
   hr = cpTokenUI->DisplayUI(hwndParent, MY_AUDIO_DIALOG_TITLE, SPDUI_AudioVolume, NULL, NULL, cpObjectToken, NULL);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecognizer::GetInputStream (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::GetInputStream

ISpRecognizer::GetInputStream retrieves the input stream that is currently being used.

HRESULT GetInputStream(
   ISpStreamFormat   **ppStream
);

Parameters

ppStream
[out] Address of a pointer to the ISpStreamFormat object that receives the input stream information.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppStream is invalid or bad.
SPERR_NOT_SUPPORTED_FOR_SHARED_RECOGNIZER | Method is not available when using the shared recognizer.
FAILED(hr) | Appropriate error message.

Remarks

Applications will not normally need to use this method, but it can be used to find the specific audio input stream that is being used. This method can be used only on InProc recognizers, not on the shared recognizer.

The returned object will implement IStream, ISpStreamFormat, and ISpAudio for real-time streams. Applications should not use methods on these interfaces that actually change the state of the audio device or read data from it. For example, reading data from the application with IStream::Read will prevent the correct data from being passed to the SR engine. Altering the state of the audio using ISpAudio::SetState will put the audio device into an unexpected state and may cause errors. All control of the audio is done by SAPI.


ISpRecognizer::CreateRecoContext (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::CreateRecoContext

ISpRecognizer::CreateRecoContext creates a recognition context for this instance of an SR engine. The recognition context is used to load recognition grammars, start and stop recognition, and receive events and recognition results.

Each application can have one or more recognition contexts, although normally each application will have only one.

HRESULT CreateRecoContext(
   ISpRecoContext   **ppNewContext
);

Parameters

ppNewContext
[out] Address of a pointer to an ISpRecoContext interface receiving the recognition context.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppNewContext is invalid or bad.
FAILED(hr) | Appropriate error message.


ISpRecognizer::GetRecoProfile (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::GetRecoProfile

ISpRecognizer::GetRecoProfile retrieves the current recognition profile token.

HRESULT GetRecoProfile(
   ISpObjectToken   **ppToken
);

Parameters

ppToken
[out] Address of a pointer of an ISpObjectToken that receives the profile information.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | The ppToken is a bad or invalid pointer.
FAILED(hr) | Appropriate error message.

Remarks

A recognition profile represents a single user and training sessions on the system. The user can create, delete, and set the current profile using Speech properties in Control Panel. SAPI will always create the engine using the current default profile. This method can be used to find which profile is currently being used.

If an application needs to store information in a specific recognition profile, it can use the ISpObjectToken::GetStorageFilename method.

Example

The following code snippet illustrates the use of ISpRecognizer::GetRecoProfile to determine the profile name

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecognizer>       cpRecognizer;
CComPtr<ISpObjectToken>      cpObjectToken;
WCHAR                        *pwszRecoProfileName;

// Get the current recognizer's recognition profile token.
hr = cpRecognizer->GetRecoProfile(&cpObjectToken);

if (SUCCEEDED(hr))
{
   // Get the reco profile name (that is, the default value of the token).
   hr = cpObjectToken->GetStringValue(NULL, &pwszRecoProfileName);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpRecognizer::SetRecoProfile (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::SetRecoProfile

ISpRecognizer::SetRecoProfile sets the recognition profile to be used by the recognizer.

HRESULT SetRecoProfile(
   ISpObjectToken   *pToken
);

Parameters

pToken
[in] Address of an ISpObjectToken object that contains the profile information.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
FAILED(hr) | Appropriate error message.

Remarks

A recognition profile represents a single user and training sessions on the system. The user can create, delete, and set the current profile using Speech properties in Control Panel. SAPI will always create the engine using the current default profile. This method can be used to set the SR engine to use a profile other than the default.

This method should not be called when the engine is currently processing audio. Calling ::SetRecoProfile with an active recognition engine can cause unexpected results, depending on how and when the SR engine reads the profile information.


ISpRecognizer::IsSharedInstance (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::IsSharedInstance

ISpRecognizer::IsSharedInstance determines the recognizer is the shared or InProc implementation.

HRESULT  IsSharedInstance  ( void );

Parameters

None.

Return values

Value | Description
S_OK | Indicates that this instance of the recognition engine is being shared.
S_FALSE | Indicates that this instance of the recognition engine is not being shared.


ISpRecognizer::GetRecoState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::GetRecoState

ISpRecognizer::GetRecoState retrieves the current state of the recognition engine.

HRESULT GetRecoState(
   SPRECOSTATE   *pState
);

Parameters

pState
[out] One of the input state flags contained in the SPRECOSTATE enumeration.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Invalid pointer.
FAILED(hr) | Appropriate error message.

Remarks

This method determines whether audio is currently being read from the audio input stream and passed to the SR engine.

See also ISpRecognizer::SetRecoState

The default recognizer state is SPRST_ACTIVE, which means SAPI will activate the audio input stream only when at least one top-level rule is active.

To be notified when the recognizer state changes (e.g. another application changes the shared SR engine's recognizer state), rather than polling the state with ::GetRecoState, call ISpEventSource::SetInterest with SPEI_RECO_STATE

.


ISpRecognizer::SetRecoState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::SetRecoState

ISpRecognizer::SetRecoState sets the state of the recognition engine.

HRESULT SetRecoState(
   SPRECOSTATE   NewState
);

Parameters

NewState
[in] One of the flags contained in the SPRECOSTATE enumeration.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED(hr) | Appropriate error message.
E_INVALIDARG | One or more parameters are invalid.

Remarks

When using the shared recognizer, the recognizer state is a global setting. If one application changes the recognizer state, it will affect all other applications connected to the shared recognizer. For this reason, applications using a shared recognizer should take great caution before calling SetRecoState.

Changing the recognition state leads to a SPEI_RECO_STATE_CHANGE event for all interested recognition contexts.


ISpRecognizer::GetStatus (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::GetStatus

ISpRecognizer::GetStatus retrieves current status information for the engine.

HRESULT GetStatus(
   SPRECOGNIZERSTATUS   *pStatus
);

Parameters

pStatus
[out] The current status of the engine.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pStatus is invalid or bad.

Remarks

This method provides static information about the SR engine such as the languages it supports. It also provides dynamic information such as current stream position the engine has recognized up to, and if the stream is actively being sent to the engine.

See SPRECOGNIZERSTATUS for further explanation of the status information that can be retrieved.


ISpRecognizer::GetFormat (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::GetFormat

ISpRecognizer::GetFormat retrieves the current input audio format.

HRESULT GetFormat(
   SPSTREAMFORMATTYPE   WaveFormatType,
   GUID                *pFormatId,
   WAVEFORMATEX       **ppCoMemWFEX
);

Parameters

WaveFormatType
[in] One of the wave file format types specified in SPSTREAMFORMATTYPE.
pFormatId
[out] The address of the unique identifier associated with the format type.
ppCoMemWFEX
[out] Address of a pointer to a WAVEFORMATEX structure that receives the format information. This is set only if the input is of a wave format type. The application must free this data with CoTaskMemFree after use.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Invalid pointer.
SPERR_UNINITIALIZED | Audio input not yet set.
FAILED(hr) | Appropriate error message.

Remarks

This method can return either the input format or the engine format. Normally these two values will be the same, but if SAPI is using a format converter to convert the input data from the audio input to the engine format these will be different.


ISpRecognizer::IsUISupported (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::IsUISupported

ISpRecognizer::IsUISupported checks if the underlying speech engine implements a certain type of user-interface component.

[local] HRESULT IsUISupported(
   const WCHAR   *pszTypeOfUI,
   void          *pvExtraData,
   ULONG          cbExtraData,
   BOOL          *pfSupported
);

Parameters

pszTypeOfUI
[in] Address of a pointer to a null-terminated string containing the UI type information.
pvExtraData
[in] Additional information for the call. The SR engine implementer dictates the format and usage of the data provided.
cbExtraData
[in] Size, in bytes, of pvExtraData. The SR engine implementer dictates the format and usage of the data provided.
pfSupported
[out] Address of a variable that receives the value indicating support for the interface. This value is set to TRUE when this interface is supported; otherwise set to FALSE. If this value is TRUE, but the return code is S_FALSE, the UI type (pszTypeOfUI) is supported, but not with the current parameters or run-time environment. Check with the engine implementer to verify run-time requirements.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | The UI is supported but not with the current run-time environment or parameters.
E_INVALIDARG | pfSupported is invalid or bad.
FAILED(hr) | Appropriate error message.

Example

The following code snippet illustrates the use of ISpRecognizer::IsUISupported.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecognizer>       cpRecognizer;
BOOL                         fSupported;

// Ask current recognizer if it supports user training.
hr = cpRecognizer->IsUISupported(SPDUI_UserTraining, NULL, NULL, &fSupported);

if (SUCCEEDED(hr))
{
   // If fSupported = TRUE, then current speech recognizer
   // supports user training; so, do stuff here.
}


ISpRecognizer::DisplayUI (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::DisplayUI

ISpRecognizer::DisplayUI displays the requested UI component from the underlying SR engine.

[local] HRESULT DisplayUI(
   HWND           hwndParent,
   LPCWSTR       *pszTitle,
   LPCWSTR       *pszTypeOfUI,
   void          *pvExtraData,
   ULONG          cbExtraData
);

Parameters

hwndParent
[in] Specifies the handle of the parent window.
pszTitle
[in] Address of a null-terminated string containing the window title. Set this value to NULL to indicate that the SR engine should use its default window title for this UI type.
pszTypeOfUI
[in] Address of a null-terminated string containing the UI type information.
pvExtraData
[in] Additional information for the call. The SR engine implementer dictates the format and use of the data provided.
cbExtraData
[in] Size, in bytes, of the contents of pvExtraData. The SR engine implementer dictates the format and usage of the data provided.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | The UI is supported but not with the current run-time environment or parameters.
FAILED(hr) | Appropriate error message.

Remarks

The current Microsoft SR engine does not send this event.

SAPI 5 speech recognition engines are capable of sending UI requests back to the application using SPEI_REQUEST_UI. For example, if the SR engine is receiving a poor audio input signal, it may request the user to perform Microphone Training. The application can receive these requests by calling ISpRecognizer::SetInterest with SPEI_REQUEST_UI. When the UI request is received, it can call ISpRecognizer::DisplayUI at an appropriate point. The typical SR engine UI requests could be User Training, Microphone Training, and Lexicon Updates. An application can call DisplayUI at any time, and does not necessarily have to wait for a UI request from the SR engine.

To best apply ISpRecognizer::DisplayUI, call ISpRecognizer::IsUISupported with a specific UI type before calling DisplayUI.

The call to DisplayUI is synchronous, so the call will not return until the UI has been closed.


ISpRecognizer::EmulateRecognition (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer::EmulateRecognition

ISpRecognizer::EmulateRecognition emulates a recognition from a specified phrase rather than from spoken content.

HRESULT EmulateRecognition(
   ISpPhrase   *pPhrase
);

Parameters

pPhrase
[in] The phrase to emulate.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | The phrase to be recognized ended before the end of the grammar was reached.
SP_NO_PARSE_FOUND | Function completed successfully but the phrase does not parse through any active rule.
SP_NO_RULES_ACTIVE | Function completed successfully but there are no active rules to parse.
E_POINTER | ppCoMemPhrase is invalid or bad.
SPERR_UNINITIALIZED | Phrase is uninitialized.
E_OUTOFMEMORY | Exceeded available memory.
FAILED(hr) | Appropriate error message.

Remarks

In the case of ambiguous rules or CFG paths, the ::EmulateRecognition method will return an arbitrary rule or path. For example, if a grammar has two ambiguous rules, the first containing the phrase "a b c", and the second containing only a dictation tag (i.e., <DICTATION/>), the rule recognized at run time may not be consistent.

This method can be used for testing applications that use speech recognition by simulating user speech. It can also be used by applications where users have the option to type or speak a command. See the SDK Sample Simple Recognition (Reco.exe) for the function CreatePhraseFromText as an example of using ISpPhraseBuilder.

All the events will be fired back to the application exactly as if a normal recognition had taken place. The result phrase will have the semantic properties set in the same way a real result would. A recognition event will be produced only if the text actually parses through the active rules (if dictation is active, any text will parse). Another application or ISpRecoContext containing an active rule that can parse the text can receive the emulated recognition.


ISpRecognizer2 (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer2

New in SAPI 5.3

Extends the ISpRecognizer interface.

Methods in Vtable Order

ISpRecognizer2 Methods | Description
EmulateRecognitionEx | Emulates a recognition from a specified phrase rather than from spoken content. It extends the functionality of ISpRecognizer::EmulateRecognition.
SetTrainingState | Puts the recognizer into training mode to do acoustic adaptation.
ResetAcousticModelAdaptation | Resets the user's recognition profile to the initial state.


ISpRecognizer2::EmulateRecognitionEx (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer2::EmulateRecognitionEx

ISpRecognizer2::EmulateRecognitionEx emulates a recognition from a specified phrase rather than from spoken content and extends the functionality of ISpRecognizer::EmulateRecognition.

HRESULT EmulateRecognitionEx(
   ISpPhrase   *pPhrase,
   DWORD        dwCompareFlags
);

Parameters

pPhrase
The phrase containing the words to emulate (that is, pretend the user said this string).
dwCompareFlags
Determines how the comparison is to be performed. The values are LINGUISTIC_IGNORECASE, LINGUISTIC_IGNOREDIACRITIC, NORM_IGNORECASE, NORM_IGNOREKANATYPE, NORM_IGNORENONSPACE, NORM_IGNORESYMBOLS, NORM_IGNOREWIDTH, NORM_LINGUISTIC_CASING, and SORT_STRINGSORT. These values are identical to those used for the dwCmpFlags parameter of the CompareString function. For more information, see CompareString.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pPhase is invalid.
SP_NO_PARSE_FOUND | The phrase did not match any active rules.
SP_RECOGNIZER_INACTIVE | Recognition is not currently active, so emulation cannot complete.
FAILED(hr) | Appropriate error message.


ISpRecognizer2::SetTrainingState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer2::SetTrainingState

ISpRecognizer2::SetTrainingState puts the recognizer into training mode to do acoustic adaptation. This is what is happening in the background when you are using the training wizard from the control panel.

When in training mode, the recognizer assumes that what the user said is definitely correct and that it should definitely be used for adaptation. The assumption is that the user is reading from a script and there are no forks in the script.

HRESULT SetTrainingState(
   BOOL    fDoingTraining,
   BOOL    fAdaptFromTrainingData
);

Parameters

fDoingTraining
True to switch training on, false to switch it off.
fAdaptFromTrainingData
Tells the engine whether to actually use the data or discard it. This is only really useful at the end of training (that is, when fDoingTraining is set to false).

Return values

Value | Description
S_OK | Function completed successfully.


ISpRecognizer2::ResetAcousticModelAdaptation (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer2::ResetAcousticModelAdaptation

ISpRecognizer2::ResetAcousticModelAdaptation resets the user's recognition profile to the initial state.

HRESULT ResetAcousticModelAdaptation(void);

Parameters

None

Return values

Value | Description
S_OK | Function completed successfully.


ISpRecognizer3 (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer3

New in Microsoft Speech Platform

Extends the ISpRecognizer interface.

Methods in Vtable Order

ISpRecognizer3 Methods | Description
GetCategory | Gets a category of the specified type.
SetActiveCategory | Sets the active recognizer category to the specified category.
GetActiveCategory | Gets the currently active recognizer category.


ISpRecognizer3::GetCategory (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer3::GetCategory

New in Microsoft Speech Platform

ISpRecognizer3::GetCategory gets a category of the specified type.

HRESULT GetCategory(
   SPCATEGORYTYPE   categoryType,
   ISpRecoCategory        **ppCategory
);

Parameters

categoryType
[in] The category type, a value in the SPCATEGORYTYPE enumeration.
pRecoCategory
[out] A pointer to a memory location that contains the address of an ISpRecoCategory instance.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Memory referenced by ppCategory cannot be written to.
FAILED(hr) | Appropriate error message.


ISpRecognizer3::GetCategory (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer3::SetActiveCategory

New in Microsoft Speech Platform

ISpRecognizer3::SetActiveCategory sets the active recognizer category to the specified category.

HRESULT SetActiveCategory(
      ISpRecoCategory   *pCategory
);

Parameters

pCategory
[in] A pointer to an ISpRecoCategory instance.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pCategory is invalid.
FAILED(hr) | Appropriate error message.

Remarks

Passing a value of NULL for *pCategory places the recognizer in a mode such that it waits for either command or dictation. That is, the recognizer waits for either dictation (free text) or a command such as "start Notepad."


ISpRecognizer3::GetActiveCategory (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpRecognizer3::GetActiveCategory

New in Microsoft Speech Platform

ISpRecognizer3::GetActiveCategory gets the currently active recognizer category.

HRESULT GetActiveCategory(
   ISpRecoCategory  **ppCategory
);

Parameters

ppCategory
[out] A pointer to a memory location that contains the address of an ISpRecoCategory instance.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | The memory that ppCategory points to cannot be written to.
FAILED(hr) | Appropriate error message.

Remarks

A value of NULL for **ppCategory indicates that the recognizer is in both command and dictation mode. That is, the recognizer waits for either dictation (free text) or a command such as "start Notepad."


ISpPhrase (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhrase

This is the main interface used to access information contained in a phrase. Using this interface, applications can retrieve recognition information such as the recognized (or hypothesized) text, the recognized rule, and semantic tag or property information. An application can also serialize the phrase data to a stream to enable persisting of recognitions to the disk, the network, or memory.

Methods in Vtable Order

ISpPhrase Methods | Description
GetPhrase | Retrieves data elements associated with a phrase.
GetSerializedPhrase | Returns the phrase information in serialized form.
GetText | Retrieves elements from a text phrase.
Discard | Discards the requested data from the phrase object.


ISpPhrase::GetPhrase (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhrase::GetPhrase

ISpPhrase::GetPhrase retrieves data elements associated with a phrase.

HRESULT GetPhrase(
   SPPHRASE   **ppCoMemPhrase
);

Parameters

ppCoMemPhrase
[out] Address of a pointer to an SPPHRASE data structure receiving the phrase information. May be NULL if no phrase is recognized. If NULL, no memory is allocated for the structure. It is the caller's responsibility to call CoTaskMemFree to free the object; however, the caller does not need to call CoTaskMemFree on each of the elements in SPPHRASE.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Invalid pointer.
E_OUTOFMEMORY | Exceeded available memory.

Returned data includes all elements associated with this phrase.

Example

The following code snippet illustrates the use of ISpRecoResult::GetPhrase as inherited from ISpPhrase to retrieve the recognized text, and display the rule recognized and the phrase.

// Declare local identifiers:
HRESULT                   hr = S_OK;
CComPtr<ISpRecoResult>    cpRecoResult;
SPPHRASE                  *pPhrase;
WCHAR                     *pwszText;
HWND                      hwndParent;

// ... Obtain a recognition result object from the recognizer ...

// Get the recognized phrase object.
hr = cpRecoResult->GetPhrase(&pPhrase);

if (SUCCEEDED (hr))
{
   // Get the phrase's text.
   hr = cpRecoResult->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &pwszText, NULL);
}

if (SUCCEEDED(hr))
{
   // Display the recognized text and the rule name in a message box.
   MessageBoxW(hwndParent, pwszText, pPhrase->Rule.pszName, MB_OK);
}


ISpPhrase::GetPhrase (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhrase::GetSerializedPhrase

ISpPhrase::GetSerializedPhrase returns the phrase information in serialized form.

HRESULT GetSerializedPhrase(
   SPSERIALIZEDPHRASE   **ppCoMemPhrase
;)

Parameters

ppCoMemPhrase
[out] Address of a pointer which will be initialized to point to the serialized phrase data. The block of memory is created by CoTaskMemAlloc and must be manually freed with CoTaskMemFree when no longer needed.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppCoMemPhrase is invalid or bad.
SPERR_UNINITIALIZED | Phrase is uninitialized.
E_OUTOFMEMORY | Exceeded available memory.

Remarks

The caller passes in the address of a pointer which is initialized to point to a block of memory which is allocated using CoTaskMemAlloc. It is the caller's responsibility to call CoTaskMemFree to free this object. The structure returned is defined to be a SPSERIALIZEDPHRASE. However, the actual size of the block is contained in (*ppCoMemPhrase)->ulSerializedSize. This size includes the size of the SPSERIALIZEDPHRASE structure.

An application that will not need recognition alternates or retained audio and needs to save space, can serialize only the phrase information (e.g., phrase text, rule name, SR engine ID, etc.) by calling ISpPhrase::Discard.

Example

The following code snippet illustrates the use ISpRecoResult::GetSerializedPhrase as inherited from ISpPhrase to serialize only the phrase portion of a result object.

// Declare local identifiers:
HRESULT                   hr = S_OK;
CComPtr<ISpRecoResult>    cpRecoResult;
SPSERIALIZEDPHRASE        *pSerializedPhrase = NULL;

// ... Obtain a recognition result object from the recognizer ...

// Get the recognized serialized phrase object.
hr = cpRecoResult->GetSerializdPhrase(&pSerializedPhrase);

if (SUCCEEDED (hr))
{
   // Do something with it.
}


ISpPhrase::GetText (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhrase::GetText

ISpPhrase::GetText retrieves elements from a text phrase.

HRESULT GetText(
   ULONG                                          ulStart,
   ULONG                                          ulCount,
   BOOL                                           fUseTextReplacements,
   [annotation ("__deref_out")] LPWSTR          **ppszCoMemText,
   [annotation ("__out_ecount_opt(1)")] BYTE     *pbDisplayAttributes
);

Parameters

ulStart
[in] Specifies the first element in the text phrase to retrieve.
ulCount
[in] Specifies the number of elements to retrieve from the text phrase.
fUseTextReplacements
[in] Boolean value that indicates if replacement text should be used. An example of a text replacement is saying "write new check for twenty dollars" and retrieving the replaced text as "write new check for $20".
ppszCoMemText
[out] Address of a pointer to the data structure that contains the display text information. It is the caller's responsibility to call ::CoTaskMemFree to free the memory.
pbDisplayAttributes
[out] Address of the SPDISPLAYATTRIBUTES enumeration that contains the text display attribute information. Text display attribute information can be used by the application to display the text to the user in a reasonable manner. For example, speaking "hello comma world period" includes a trailing period, so the recognition might include SPAF_TWO_TRAILING_SPACES to inform the application without requiring extra text processing logic for the application.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | A phrase that does not contain text or ppszCoMemText is NULL.
E_INVALIDARG | One or more parameters are invalid.
E_POINTER | Invalid pointer.
E_OUTOFMEMORY | Exceeded available memory.

Remarks

The text is the display text of the elements for the phrase and constructs a text string created by CoTaskMemAlloc by applying the pbDisplayAttributes of each SPPHRASEELEMENT.

Example

The following code snippet illustrates the use ISpPhrase::GetText to retrieve parts of the recognized phrase.

// Declare local identifiers:
HRESULT                   hr = S_OK;
CComPtr<ISpRecoResult>    cpRecoResult;
SPPHRASE                  *pPhrase;
WCHAR                     *pwszText;

// ... Obtain a recognition result object from the recognizer ...

// Get the recognized phrase object.
hr = cpRecoResult->GetPhrase(&pPhrase);

if (SUCCEEDED (hr))
{
   // Get the phrase's entire text string, including replacements.
   hr = cpRecoResult->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &pwszText, NULL);
}

if (SUCCEEDED(hr))
{
   // Get the phrase's first 2 words, excluding replacements.
   hr = cpRecoResult->GetText(pPhrase->Rule.ulFirstElement, 2, FALSE, &pwszText, NULL);
}

if (SUCCEEDED (hr))
{
   // Do some more stuff.
}


ISpPhrase::Discard (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhrase::Discard

ISpPhrase::Discard discards the requested data from a phrase object.

HRESULT Discard(
   DWORD   dwValueTypes
;)

Parameters

dwValueTypes
[in] Flags of type SPVALUETYPE indicating elements to discard. Multiple values may be combined.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | dwValueTypes is not a valid value type flag.
FAILED(hr) | Appropriate error message.

Remarks

Applications that have no use for certain types of retained data, and will be persisting or serializing the phrase or result objects, may discard the unnecessary data. For example, an application performing offline transcription may need to retain only the audio and the final result. It can call ::Discard with SPDF_ALTERNATES to eliminate the alternate data (possibly including a large amount of private engine data).

Note that once retained audio is discarded, a call to ISpRecoResult::GetAudio will fail.

Example

The following code snippet illustrates the use of ISpRecoResult::Discard as inherited from ISpPhrase to discard the retained audio.

// Declare local identifiers:
HRESULT                   hr = S_OK;
CComPtr<ISpRecoResult>    cpRecoResult;

// ... Get a recognition result object from the SR engine ...

// Discard audio.
hr = cpRecoResult->Discard(SPDF_AUDIO);

if (SUCCEEDED (hr))
{
   // Serialize the "shrunken" result
   // to the disk or do other stuff.
}


ISpPhrase2 (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhrase2

New in SAPI 5.3

Extends the ISpPhrase interface to provide SML result information and the audio stream containing the utterance corresponding to the result.

Methods in Vtable Order

ISpPhrase2 Methods | Description
GetXMLResult | Returns the retained audio for the phrase.
GetXMLErrorInfo | Provides error information for the phrase in SML (XML) format.
GetAudio | Provides result information for the phrase in SML (XML) format.


ISpPhrase2::GetXMLResult (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhrase2::GetXMLResult

ISpPhrase2::GetXMLResult provides result information for the phrase in SML (XML) format.

HRESULT GetXMLResult(
   LPWSTR               *ppszCoMemXMLResult,
   SPXMLRESULTOPTIONS    Options
);

Parameters

ppszCoMemXMLResult
[out] Returns a string containing the result in SML (XML) format.
Options
Indicates whether to return just the main result or the main result and the alternates.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppszCoMemXMLResult is invalid.
SPERR_SML_GENERATION_FAIL | The SML could not be generated.
E_OUTOFMEMORY | Exceeded available memory.
E_NOTIMPL | Engine does not support this functionality.


ISpPhrase2::GetXMLErrorInfo (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhrase2::GetXMLErrorInfo

ISpPhrase2::GetXMLErrorInfo provides error information for the phrase in SML (XML) format.

HRESULT GetXMLErrorInfo(
   SPSEMANTICERRORINFO   *pSemanticErrorInfo
);

Parameters

pSemanticErrorInfo
Indicates where an error occurred in semantic processing.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pSemanticErrorInfo is invalid.
E_OUTOFMEMORY | Exceeded available memory.
S_FALSE | Information could not be returned because no script error occurred.
E_NOTIMPL | Engine does not support functionality.


ISpPhrase2::GetAudio (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhrase2::GetAudio

ISpPhrase2::GetAudio returns the retained audio for the phrase.

HRESULT GetAudio(
   ULONG                ulStartElement,
   ULONG                cElements,
   ISPStreamFormat    **ppStream
);

Parameters

ulStartElement
Index of the first spphrase element to return audio for.
cElements
The number of elements to return audio for.
ppStream
The returned audio.

Return values

Value | Description
S_OK | Function completed successfully.
E_NOTIMPL | Not supported because the retained audio is in a different format from the engine's format.

Remarks

This function should only be used on phrases that are being passed to the engine as part of alternates generation.


ISpPhraseAlt (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhraseAlt

The ISpPhraseAlt interface is implemented on a phrase alternate object that can be obtained by calling ISpRecoResult::GetAlternates. The ISpPhraseAlt object is the interface that enables applications to retrieve alternate phrase information from an SR engine, and to update the SR engine's language model to reflect committed alternate changes.

Methods in Vtable Order

ISpPhraseAlt Methods | Description
ISpPhrase | Inherits from ISpPhrase and those methods are accessible from an ISpPhraseAlt object.
GetAltInfo | Retrieves data elements associated with an alternate phrase.
Commit | Replaces a section of the parent phrase to which this alternate corresponds.


ISpPhraseAlt::GetAltInfo (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhraseAlt::GetAltInfo

ISpPhraseAlt::GetAltInfo retrieves data elements associated with an alternate phrase.

HRESULT GetAltInfo(
   ISpPhrase   **ppParent,
   ULONG        *pulStartElementInParent,
   ULONG        *pcElementsInParent,
   ULONG        *pcElementsInAlt
);

Parameters

ppParent
[out] Address to store the pointer to the parent SpPhrase object.
pulStartElementInParent
[out] Address to store the starting element position within the parent phrase that this alternate applies to.
pcElementsInParent
[out] Address to store the number of elements within the parent that this alternate replaces.
pcElementsInAlt
[out] Address to store the number of elements that the alternate contains.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | At least one of the parameters is invalid or bad.
SPERR_NOT_FOUND | The alternate is not associated with a valid parent phrase object.


ISpPhraseAlt::Commit (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhraseAlt::Commit

ISpPhraseAlt::Commit replaces a section of the parent phrase to which the alternate corresponds.

HRESULT  Commit  ( void );

Parameters

None

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_NOT_FOUND | The alternate object is not related to a valid parent phrase object.

Remarks

After an alternate has been committed, the parent phrase will be modified to reflect the substitution.

Upon committing the alternate phrase, the SR engine also has the ability to update its language model to improve future recognitions of the same or similar phrases.

Example

The following code snippet illustrates the use ISpPhraseAlt::Commit to commit an alternate phrase.

// Declare local identifiers:
HRESULT                    hr = S_OK;
const USHORT               MY_MAX_ALTERNATES = 10;
CComPtr<ISpRecoResult>     cpRecoResult;
CComPtr<ISpPhrase>         cpPhrase;
CComPtr<ISpPhraseAlt>      pcpPhraseAlt[MY_MAX_ALTERNATES];
SPPHRASE                   *pPhrase;
WCHAR                      *pwszText;
WCHAR                      *pwszAlternate;
BOOL                       fMoreAppropriate;
LONG                       lCount;

// ... Obtain a recognition result object from the recognizer ...

// Get the recognized phrase object.
hr = cpRecoResult->GetPhrase(&pPhrase);

if (SUCCEEDED(hr))
{
   // Get the phrase's text.
   hr = cpPhrase->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &pwszText, NULL);
}

if (SUCCEEDED(hr))
{
   // Check the phrase's text... Assume that
   // the phrase isn't a correct recognition.

   // Get the top MY_MAX_ALTERNATES alternates
   // to the entire recognized phrase.
   hr = cpRecoResult->GetAlternates(pPhrase->Rule.ulFirstElement,
        pPhrase->Rule.lCountOfElements,
        MY_MAX_ALTERNATES,
        pcpPhraseAlt,
        &lCount);
}

if (SUCCEEDED(hr))
{
   // Check each alternate in order of highest likelihood.
   for (int i = 0; i < lCount; i++)
   {
      hr = pcpPhraseAlt[i]->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &pwszAlternate, NULL);

      if (SUCCEEDED(hr))
      {
         // ... Check if this alternate is more appropriate ...

         // If it is more appropriate, then commit the alternate--
         if (fMoreAppropriate)
         {
            hr = pcpPhraseAlt[i]->Commit();
         }

         if (SUCCEEDED(hr))
         {
            // Release system resources:
            if (pwszAlternate) ::CoTaskMemFree(pwszAlternate);
            if (pwszText) ::CoTaskMemFree(pwszText);
         }
      }
   }
}

// Free the initial phrase object.
if (pPhrase) ::CoTaskMemFree(pPhrase);


ISpPhraseBuilder (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhraseBuilder

The ISpPhraseBuilder interface inherits from ISpPhrase.

Methods in Vtable Order

ISpPhraseBuilder Methods | Description
InitFromPhrase | Initializes from a phrase.
InitFromSerializedPhrase | Initializes a phrase from a serialized phrase.
AddElements | Adds a copy of the given element to the end of this object's element list.
AddRules | Adds phrase rules to the phrase object.
AddProperties | Adds property entries to the phrase object.
AddReplacements | Adds one or more text replacements to the phrase.


ISpPhraseBuilder::InitFromPhrase (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhraseBuilder::InitFromPhrase

ISpPhraseBuilder::InitFromPhrase initializes from a phrase.

HRESULT InitFromPhrase(
   const   SPPHRASE   *pSrcPhrase
);

Parameters

pSrcPhrase
Address of a SPPHRASE data structure containing the phrase information. If pSrcPhrase is NULL, the object is reset to its initial state.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pSrcPhrase or pSrcPhrase->Rule.pNextSibling is invalid or bad. Alternatively, pSrcPhrase->LangID may be zero or pSrcPhrase->cbSize does not indicate the same size as pSrcPhrase.
FAILED(hr) | Appropriate error message.

Example

The following code snippet demonstrates creating and initializing from a phrase.

// Declare local identifiers:
HRESULT                    hr = S_OK;
CComPtr<ISpPhraseBuilder>  cpPhraseBuilder;
CComPtr<ISpPhrase>         cpPhrase;
SPPHRASE                   Phrase;

hr = cpPhraseBuilder.CoCreateInstance(CLSID_SpPhraseBuilder);

if (SUCCEEDED(hr))
{
   // Initialize the Phrase data structure.
   hr = cpPhraseBuilder->InitFromPhrase(&Phrase);
}

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


ISpPhraseBuilder::InitFromSerializedPhrase (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhraseBuilder::InitFromSerializedPhrase

ISpPhraseBuilder::InitFromSerializedPhrase initializes a phrase from a serialized phrase.

HRESULT InitFromSerializedPhrase(
   const   SPSERIALIZEDPHRASE   *pPhrase
);

Parameters

pPhrase
Address of the SPSERIALIZEDPHRASE structure that contains the phrase information.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pSrcPhrase or pSrcPhrase->cbSerializedSize is invalid or bad.
FAILED(hr) | Appropriate error message.

Remarks

Before passing a serialized phrase into this function, first make certain that the size of the buffer being passed is equal to pPhrase->ulSerializedSize.

Example

The following code fragment demonstrates the use of InitFromSerializedPhrase.

// Declare local identifiers:
HRESULT                      hr = S_OK;
CComPtr<ISpRecoResult>       RecoResult;
CComPtr<ISpPhraseBuilder>    cpPhraseBuilder;
CComPtr<ISpStream>           cpStream;
SPSERIALIZEDPHRASE           *pSerializedPhrase=NULL;
LARGE_INTEGER                liZero = {0,0};
ULONG                        ulSerializedSize = 0;
LARGE_INTEGER                liseek;

// Bind audio stream to specified file (note
// that SerializedPhrase.sp is a dummy file).
hr = SPBindToFile(L"SerializedPhrase.sp", SPFM_OPEN_READONLY, &cpStream, NULL, NULL, SPFEI_ALL_EVENTS);

if (SUCCEEDED(hr))
{
   hr = cpStream->Seek(liZero, STREAM_SEEK_SET, NULL);
}

if (SUCCEEDED(hr))
{
   hr = cpStream->Read(&ulSerializedSize, sizeof(ULONG), NULL);
}

if (SUCCEEDED(hr))
{
   // Need to seek back and read the whole chunk of data in:
   liseek.QuadPart  -= sizeof(ULONG);
   hr = cpStream->Seek(liseek, STREAM_SEEK_CUR, NULL);
}

if (SUCCEEDED(hr))
{
   pSerializedPhrase = (SPSERIALIZEDPHRASE*)::CoTaskMemAlloc(ulSerializedSize);
}

if (SUCCEEDED(hr) && pSerializedPhrase)
{
   hr = cpStream->Read(pSerializedPhrase, ulSerializedSize, NULL);
}

if (SUCCEEDED(hr) && pSerializedPhrase)
{
   hr = cpPhraseBuilder.CoCreateInstance(CLSID_SpPhraseBuilder);
}

if (SUCCEEDED(hr))
{
   hr = cpPhraseBuilder->InitFromSerializedPhrase(pSerializedPhrase);
}

if (SUCCEEDED(hr))
{
   ::CoTaskMemFree(pSerializedPhrase);
}


ISpPhraseBuilder::AddElements (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhraseBuilder::AddElements

ISpPhraseBuilder::AddElements adds a copy of the given element to the end of this object's element list.

HRESULT AddElements(
   ULONG                    cElements,
   const SPPHRASEELEMENT   *pElement
);

Parameters

cElements
Specifies the number of phrase elements to add.
pElement
Address of the array of SPPHRASEELEMENT data structures containing the phrase elements to add.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
SPERR_UNINITIALIZED | The object has not been properly initialized.
FAILED(hr) | Appropriate error message.


ISpPhraseBuilder::AddRules (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhraseBuilder::AddRules

ISpPhraseBuilder::AddRules adds phrase rules to the phrase object.

HRESULT AddRules(
  const SPPHRASERULEHANDLE   hParent,
  const SPPHRASERULE        *pRule,
  SPPHRASERULEHANDLE        *phNewRule
);

Parameters

hParent
[in] Handle to the parent phrase rule.
pRule
[in] Address of the SPPHRASERULE structure that contains the phrase rule information.
phNewRule
[out] Address of the handle of SPPHRASERULEHANDLE that contains the new phrase rule information.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Invalid pointer.
SPERR_UNINITIALIZED | The object has not been properly initialized.
FAILED(hr) | Appropriate error message.


ISpPhraseBuilder::AddProperties (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhraseBuilder::AddProperties

ISpPhraseBuilder::AddProperties adds property entries to the phrase object.

HRESULT AddProperties(
   const SPPHRASEPROPERTYHANDLE hParent,
   const SPPHRASEPROPERTY      *pProperty,
   SPPHRASEPROPERTYHANDLE      *phNewProperty
);

Parameters

hParent
[in] Handle to the parent phrase element.
pProperty
[in] Address of the SPPHRASEPROPERTY structure that contains the property information.
phNewProperty
[out] Address of the handle of SPPHRASEPROPERTY that contains the new property information.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
E_POINTER | Invalid pointer.
SPERR_UNINITIALIZED | The object has not been properly initialized.
SPERR_ALREADY_INITIALIZED | The object has already been initialized.
FAILED(hr) | Appropriate error message.


ISpPhraseBuilder::AddReplacements (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpPhraseBuilder::AddReplacements

ISpPhraseBuilder::AddReplacements adds one or more text replacements to the phrase.

HRESULT AddReplacements(
   ULONG                        cReplacements,
   const SPPHRASEREPLACEMENT   *pReplacements
);

Parameters

cReplacements
The number of replacement phrase elements.
pReplacements
Address of the array of SPPHRASEREPLACEMENT structures containing the phrase element replacement information.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
SPERR_UNINITIALIZED | The object has not been properly initialized.
FAILED(hr) | Appropriate error message.


ISpSerializeState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpSerializeState

New in SAPI 5.3

Enables applications to to save and restore the recognizer's internal state.

The ISpSerializeState interface allows an application to get the recognizer's internal state, which can then be stored and fed back into the recognizer at a later stage. The state includes adaptation to noise levels and voice characteristics. This is useful, for example, when recognizing discrete recorded files that are known to all come from the same session.

Methods in Vtable Order

ISpSerializeState Methods | Description
GetSerializedState | Gets serialized data from the engine, thus allowing its current state to be stored and later restored for later speech data from the same source.
SetSerializedState | Sets previously stored serialized data, thus allowing an engine state to be reproduced.


ISpSerializeState::GetSerializedState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpSerializeState::GetSerializedState

ISpSerializeState::GetSerializedState gets serialized data from the engine, thus allowing its current state to be stored and later restored for later speech data from the same source.

HRESULT GetSerializedState(
   BYTE     **ppbData,
   ULONG     *pulSize,
   DWORD      dwReserved
);

Parameters

ppbData
Pointer to the buffer that is to hold the serialized data.
pulSize
Size of the buffer, in bytes.
dwReserved
Reserved for future use.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | A parameter is invalid.
FAILED(hr) | Appropriate error message.


ISpSerializeState::SetSerializedState (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpSerializeState::SetSerializedState

ISpSerializeState::SetSerializedState sets previously stored serialized data, thus allowing an engine state to be reproduced.

HRESULT SetSerializedState(
   BYTE     *pbData,
   ULONG     ulSize,
   DWORD     dwReserved
);

Parameters

pbData
Pointer to the buffer that holds the previously stored serialized data.
ulSize
Size of the buffer, in bytes.
dwReserved
Reserved for future use. Currently, the only valid value for this parameter is 0. Any other value results in an error.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | A parameter is invalid.
FAILED(hr) | Appropriate error message.


ISpXMLRecoResult (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpXMLRecoResult

New in SAPI 5.3

Defines the semantic results of speech recognition.

Recognition results are returned in Semantic Markup Language (SML), an XML format defined in the W3C document Semantic Interpretation for Speech Recognition.

Methods in Vtable Order

ISpXMLRecoResult Methods | Description
GetXMLResult | Returns the recognition result as Semantic Markup Language (SML).
GetXMLErrorInfo | Is used to discover the details of an error that occurred during semantic processing.


ISpXMLRecoResult::GetXMLResult (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpXMLRecoResult::GetXMLResult

ISpXMLRecoResult::GetXMLResult returns the result as Semantic Markup Language (SML).

Recognition results are returned in Semantic Markup Language (SML), an XML format defined in the W3C document Semantic Interpretation for Speech Recognition.

HRESULT GetXMLResult(
   LPWSTR                *ppszCoMemXMLResult,
   SPXMLRESULTOPTIONS     Options
);

Parameters

ppszCoMemXMLResult
[out] The SML will be placed in this string.
Options
Used to specify whether the primary result or the alternate results should be returned.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppszCoMemXMLResult is invalid.
S_FALSE | An empty false reco (no elements) or hypothesis occurred.
E_NOTIMPL | Engine does not support functionality.


ISpXMLRecoResult::GetXMLErrorInfo (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpXMLRecoResult::GetXMLErrorInfo

ISpXMLRecoResult::GetXMLErrorInfo is used to discover the details of an error that occurred during semantic processing.

HRESULT GetXMLErrorInfo(
   SPSEMANTICERRORINFO   *pSemanticErrorInfo
);

Parameters

pSemanticErrorInfo
A structure that will be populated with details of the error.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | Information could not be returned because no script error occurred.
E_NOTIMPL | Engine does not support functionality.


ISpProperties (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpProperties

ISpProperties sets and retrieves property attribute information.

This interface is currently implemented only by the SR engine (ISpRecognizer), and can be used for setting SR engine properties (see SAPI 5.0 SR Properties White Paper).

Methods in Vtable Order

ISpProperties Methods | Description
SetPropertyNum | Sets a numeric property corresponding to the specified name.
GetPropertyNum | Retrieves a numeric value specified by the named key.
SetPropertyString | Sets a text property corresponding to the specified name.
GetPropertyString | Retrieves the string value corresponding to the specified key name.


ISpProperties::SetPropertyNum (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpProperties::SetPropertyNum

ISpProperties::SetPropertyNum sets a numeric property corresponding to the specified name.

HRESULT SetPropertyNum(
   LPCWSTR       *pName,
   LONG           lValue
 );

Parameters

pName
[in] Null-terminated string containing the property name. Valid values are listed in the SR Properties section of the SAPI 5.0 SR Properties White Paper.
lValue
[in] The property value to set.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | SR engine does not support specified property name.
E_INVALIDARG | One or more parameters are invalid.
FAILED(hr) | SR engine returned specific error.

Remarks

If the SR engine supports the property, SAPI will fire a property-changed event (see SPEI_PROPERTY_NUM_CHANGE) to all interested recognizer contexts (ISpRecoContext). Broadcasting the corresponding event notifies any recognizer contexts that had interests in the property (see CSpEvent::PropertyName and CSpEvent::PropertyNumValue).


ISpProperties::GetPropertyNum (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpProperties::GetPropertyNum

ISpProperties::GetPropertyNum retrieves a numeric value specified by the named key.

HRESULT GetPropertyNum(
   LPCWSTR       *pName,
   LONG          *plValue
);

Parameters

pName
[in] String containing the property name. Valid values are listed in the SR Properties section of the SAPI 5.0 SR Properties White Paper.
plValue
[out] Address to store the property value.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | SR engine does not support specified property name.
E_INVALIDARG | One or more parameters are invalid.
E_POINTER | Value pointer is invalid.
FAILED(hr) | SR engine returned specific error.


ISpProperties::SetPropertyString (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpProperties::SetPropertyString

ISpProperties::SetPropertyString sets a text property corresponding to the specified name.

HRESULT SetPropertyString(
   LPCWSTR                                            *pName,
   [annotation("__deref_out"), out, string] LPCWSTR   *pValue
);

Parameters

pName
[in, string] Null-terminated string containing the property name.
pValue
[in, string] Null-terminated string containing the property value.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | SR engine does not support specified property name.
E_INVALIDARG | One or more parameters are invalid.
FAILED(hr) | SR engine returned specific error.

Remarks

If the SR engine supports the property, SAPI will fire a property-changed event (see SPEI_PROPERTY_STRING_CHANGE) to all interested recognizer contexts (ISpRecoContext). Broadcasting the corresponding event notifies any recognizer contexts that had interests in the property (see CSpEvent::PropertyName and CSpEvent::PropertyStringValue).


ISpProperties::GetPropertyString (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpProperties::GetPropertyString

ISpProperties::GetPropertyString retrieves the string value corresponding to the specified key name.

HRESULT GetPropertyString(
   LPCWSTR       *pName,
   WCHAR        **ppCoMemValue
);

Parameters

pName
[in] Null-terminated string containing the property name. Valid values are listed in the SR Properties section of the SAPI 5.0 SR Properties White Paper.
ppCoMemValue
[out] Address to store the pointer to the string value.
The caller must call CoTaskMemFree() to free the string pointer.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | SR engine does not support specified property name.
E_INVALIDARG | One or more parameters are invalid.
E_POINTER | Value pointer is invalid.
FAILED(hr) | SR engine returned specific error.


SAPI text-to-speech (Microsoft Speech Platform)

 Microsoft Speech Platform

Text-to-speech engine interfaces (API-level)

The following section covers:

  • TTS Overview
  • TTS Engine Characteristics
  • Text Synthesis
  • ISpVoice


ISpVoice (Microsoft Speech Platform)

 Microsoft Speech Platform

Text-to-Speech Overview

ISpVoice Introduction

The central SAPI API for text-to-speech (TTS) is ISpVoice. Using this interface, applications can add TTS support such as speaking text, modifying speech characteristics, changing voices, as well as responding to real-time events while speaking. In fact, most applications should need only this single interface to accomplish everything that is needed for basic TTS support.

Applications obtain access to ISpVoice interface methods by creating a COM object. As the name implies, an ISpVoice object is simply a single instance of a specific TTS voice. Every ISpVoice object is an individual voice. Even if two different ISpVoice objects select the same base voice (for example "Mike"), each of the two voices can be changed and modified independently of the other.

Speaking

When an application first creates an ISpVoice object, the object initializes to the default voice (set in Speech properties of Control Panel). This means that the new object is immediately ready to speak text, no special initialization is needed. At this point, applications can use Speak or SpeakStream to speak any Unicode text data.

Synchronous vs. Asynchronous Speaking

The two speaking functions can generate speech either synchronously (function does not return until text has completely spoken) or asynchronously (function returns immediately but continues speaking as a background process). Asynchronous operation is chosen if the application needs to do something else (highlight text, paint animation, monitor controls, etc.) while speaking. Otherwise, the simplest case is to speak synchronously.

Getting Status Information

During asynchronous speech, applications can get current status information (text position, speech done state, bookmarks, etc.) in one of two ways. The simplest way is to periodically poll the ISpVoice object using the GetStatus method. The other way is to initialize the ISpVoice object so that it sends real-time events to the application as they happen.

Flow Control

As a convenience, most TTS applications allow users to temporarily suspend speech output. The Pause and Resume methods are typically called in response to a user initiated action.

Modifying Voice Attributes

Often with TTS, voice output needs to be modified from its default setting. There are two ways to do this is; either by calling certain ISpVoice API methods, or by embedding special Extended Markup Language (XML) tags within the spoken text. Typically, the API functions are used as global settings that affect the speech independent of current selected voice or document that is spoken. While the XML tags are usually used in much narrower scope, affecting only the spoken style in a single document.

Audio Output

Although usually the default for desktop applications, audio output for TTS is not restricted to hardware sound card destinations. SAPI TTS supports, either directly or indirectly, just about any audio configuration an application may require. Whether the destination is a PC sound card, buffer in memory, or a special telephony hardware, ISpVoice has several audio control methods to change the audio path from its default configuration.

ISpVoice Methods

Speaking Text
Speak | Speaks a text string or file.
SpeakStream | Speaks a text stream or plays an audio (WAV) stream.
Real-time Status
GetStatus | Returns current speech and event status information.
WaitUntilDone | Delays until either the voice has completed speaking or the specified time interval has elapsed.
SpeakCompleteEvent | Returns an event handle that will be signaled when speech is done.
Flow Control
Pause | Pauses the output speech at the nearest alert boundary.
Resume | Resumes speaking.
Skip | Skips ahead or backward to a new input text position while speaking.
Changing Voice Attributes
SetRate | Sets the speaking rate in real time.
GetRate | Returns the current speaking rate.
SetVolume | Sets the speech volume level in real time.
GetVolume | Returns the current speech volume level.
SetVoice | Sets the identity of the voice used for synthesis.
GetVoice | Retrieves the object token that identifies the current voice.
Real-time Event Management (inherited from ISpEventSource)
SetInterest | Sets the type of events to queue.
GetEvents | Returns the queued events.
GetInfo | Returns information about the event queue.
SetNotifySink | Sets up the instance to make free-threaded calls through ISpNotifySink::Notify.
SetNotifyWindowMessage | Sets a window handle to receive notifications as window messages.
SetNotifyCallbackFunction | Sets a callback function to receive notifications.
SetNotifyCallbackInterface | Sets an object to receive notifications.
SetNotifyWin32Event | Sets up a Win32 event object to be used by this instance for notifications.
WaitForNotifyEvent | A blocking call which waits for a notification.
GetNotifyEventHandle | Retrieves Win32 event handle associated with this notify source.

Audio Output Control
SetOutput | Sets the current output object. A value of NULL may be used to select the default audio device.
GetOutputStream | Retrieves a pointer to the current output stream.
GetOutputObjectToken | Retrieves the object token for the current output object.
Miscellaneous
SetPriority | Sets the priority for the voice.
GetPriority | Retrieves the current voice priority level.
SetAlertBoundary | Specifies which event should be used as the insertion point for alerts.
GetAlertBoundary | Retrieves the event that is currently being used as the insertion point for alerts.
IsUISupported | Determines if the specified type of UI is supported.
DisplayUI | Displays the requested UI.
SetSyncSpeakTimeout | Sets the timeout interval in milliseconds after which, synchronous Speak and SpeakStream calls to this instance of the voice will timeout.
GetSyncSpeakTimeout | Retrieves the timeout interval for synchronous speech operations for this ISpVoice instance.


TTS Engine Characteristics (Microsoft Speech Platform)

 Microsoft Speech Platform

TTS Engine Characteristics

Engines use the three characteristics of Volume, Pitch, and Rate to partially define speech traits. At the application level, setting these values is simple; you need only set them to a given number. However, implementation of these traits is more complex for the engine.

Volume

At the application level, volume is a number from zero to 100 where 100 is the maximum value for a voice. It is a linear progression and a value of 50 represents half of the loudest permitted. The increments should be the range divided by 100.

Pitch adjustment

The value can range from -10 to +10. A value of zero sets a voice to speak at its default pitch. A value of -10 sets a voice to speak at three-fourths of its default pitch. A value of +10 sets a voice to speak at four-thirds of its default pitch. Each increment between -10 and +10 is logarithmically distributed such that incrementing or decrementing by 1 is multiplying or dividing the pitch by the 24th root of 2 (about 1.03). Values outside of the -10 and +10 range will be passed to an engine. However, SAPI 5-compliant engines may not support such extremes and may clip the pitch to the maximum or minimum the engine supports. Values of -24 and +24 must lower and raise pitch by 1 octave respectively. All incrementing or decrementing by 1 must multiply or divide the pitch by the 24th root of 2.

Rate adjustment

The value can range from -10 to +10. A value of zero sets a voice to speak at its default rate. A value of -10 sets a voice to speak at one-third of its default rate. A value of +10 sets a voice to speak at three times its default rate. Each increment between -10 and +10 is logarithmically distributed such that incrementing or decrementing by 1 is multiplying or dividing the rate by the 10th root of 3 (about 1.1). Values more extreme than -10 and +10 will be passed to an engine. However, SAPI 5-compliant engines may not support such extremes and may clip the rate to the maximum or minimum rate the engine supports.


Text synthesis (Microsoft Speech Platform)

 Microsoft Speech Platform

Text synthesis

SAPI 5 uses the Extensible Markup Language (XML) to define text synthesis characteristics and application configuration settings.

A text-to-speech (TTS) engine that uses synthesis generates sounds similar to those created by the human voice and applies various filters to simulate throat length, mouth cavity, lip shape, and tongue position. Although the voice produced through text synthesis often sounds less human than a voice produced by diphone concatenation, it is possible to obtain different qualities of voice through modifying TTS configuration settings. SAPI 5-compliant TTS engines can achieve improved synthesized text-to-speech voice qualities using XML to control the configuration settings for text synthesis.

The following section covers:

  • Synthesis markup
  • English Context tag definitions
  • Chinese Context tag definitions
  • Japanese Context tag definitions


Synthesis markup (Microsoft Speech Platform)

 Microsoft Speech Platform

Synthesis Markup

SAPI 5 synthesis markup is the collection of XML tags inserted into text to modify the speech synthesis of that text. These XML tags, which provide functionality such as volume control and word emphasis, are inserted into text passed into ISpVoice::Speak and text streams of format SPDFID_XML which are then passed into ISpVoice::SpeakStream. By default, the SAPI XML parser auto-detects XML. In the case of an invalid XML structure, a speak error may be returned to the application. SAPI is not intended to be used to validate the XML structure, as it is the responisbility of the developer to validate the XML with an XML validation tool. Please see ISpVoice for more information.

SAPI 5 synthesis markup is an application of XML. Every XML element consists of a start tag <Some_tag> and an end tag </Some_tag> with a case-insensitive tag name and contents between these tags. If the element is empty, it has no contents <Some_tag></Some_tag> and the start tag and the end tag might be the same <Some_tag/>. More information about XML and the XML specification is available at: http://www.w3.org/TR/1998/REC-xml-19980210.html.

The following section covers:

  • SAPI 5 XML tags
  • Attributes
  • Contents
  • Relationship to HTML web pages and SABLE

SAPI 5 XML tags

XML tags in SAPI 5 follow a defined structure program scope and implementation. SAPI 5 XML tags have a specific purpose and affect the input text in a predetermined manner.

The SAPI 5 XML tags are divided into four different scope categories.

  1. Non-scoped
  2. Scoped
  3. Global
  4. Scoped/Global

The modification and properties can be controlled through the use of XML tags.

Attributes
Attributes of an XML element appear inside the start tag. Each attribute is in the form of a name, followed by an equal character, followed by a quoted string value. An attribute of a given name may only appear once in a start tag. Exact details on what characters may appear between quotes can be found at http://www.w3.org/TR/REC-xml#NT-AttValue.

Briefly, the literal string cannot contain a less than character "<" if the string is surrounded by single quotation marks, it cannot contain a single quotation mark. If the string is surrounded by double quotation marks it cannot contain a double quotation mark. Furthermore, all ampersands (&) can be used only in an entity reference such as &amp; and "&gt;". When a literal string is parsed, the resulting replacement text will resolve all entity references such as "&gt;" into its corresponding text, such as ">".

In this specification, only the resulting replacement text needs to be defined for attribute value strings. The XML specification defines the exact file syntax details. Character references allow entity references in ASCII characters to specify replacement text which has unprintable characters such as extended Unicode characters. The entity reference "&#x0259;" specifies the single Unicode character for the International Phonetic Alphabet symbol for a mid-central unrounded vowel. See http://www.w3.org/TR/1998/REC-xml-19980210#sec-references for details.

The <LANG> and <VOICE> XML tags are specific to the Microsoft engines and provide support for language and dialect attributes for a given voice.

The following is an example of what 409;9 refers to and how to correctly use it in XML tags:

<LANG LANGID="409">This is the US English language</LANG>
<LANG LANGID="9">This is the English Language</LANG>
<VOICE REQUIRED="language=409">This is the required voice for the US English language</VOICE>
<VOICE REQUIRED="language=9">This is the required voice that speaks in any dialect of the English language</VOICE>

A speak error will occur when entering voice attribute information as it appears in the Windows Registry:

For example:

<LANG LANGID="409;9">Speak this text with the US English language</LANG>
<VOICE REQUIRED="language=409;9">Require a voice be used that speaks the US English language</VOICE>

In the Windows Registry, the language attribute for the Microsoft SAPI 5 English voices is labeled as '409;9' The '409' attribute information indicates the voice is specifically US English, and '9' refers to the English language. This language labeling convention for voices may not be followed by all engine manufacturers. For example, the LH voices may use '409' to indicate an English voice, while Microsoft uses '409;9' to specify the voice is specifically US English.

For example:

409;9 = US English
809;9 = British English

Start RegEdit and expand the tree view pane to the following registry key location:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens

Select one of the available voices and view the corresponding attribute information.

The following is an example of the MSMary voice attributes:

Contents
The contents of an element consist of text or sub-elements. With these definitions, the XML specification defines the exact file syntax details.

Relationship to HTML web pages and SABLE

The XML format that SAPI 5 uses is NOT placed inside web pages. Web page authors who want to mark up sections of HTML text so that it is synthesized correctly, should use the W3C Aural Cascading Style Sheets (ACSS). More information is available at: http://www.w3.org/TR/WD-acss

SAPI applications that are synthesizing text from a web page will "render" HTML+ACSS into SAPI's synthesis markup format. Programs apply a default ACSS file when synthesizing web pages that do not have an associated ACSS file.

SAPI 5 synthesis markup format is similar to the format published by the SABLE Consortium. However, this format and SABLE version 1.0 are not interoperable. At this time, it's not determined if they will become partially interoperable in the future. More information about the SABLE specification is available at: http://www.bell-labs.com/project/tts/sable.html.

return to the top of this page Back to top


English Context tag definitions (Microsoft Speech Platform)

 Microsoft Speech Platform

English Context tag definitions

The CONTEXT tag specifies the normalization of a block of text. This specification defines the SAPI predefined attributes (ID) for the CONTEXT tag. These IDs are strings. SAPI does not perform any parameter validation on the string passed to the engine, hence, the application can specify engine-specific normalization IDs to the engine. Engine-specific strings begin with the engine vendor's name to avoid confusion between engines.

For example:

<CONTEXT ID = "MS_My_Context"> text </CONTEXT>

The exact implementation of some of these values is dependent on the engine used in SAPI 5. In order to force a certain normalization, application developers can choose to normalize the text, or use another SAPI tag or engine-specific ID. Each context tag can contain more than one string.

For example:

<CONTEXT ID = "date_mdy"> 12/21/99 11/21/99 10/21/99 </CONTEXT>
would be normalized to "December twenty first nineteen ninety nine November twenty first nineteen ninety nine October twenty first nineteen ninety nine."

The following predefined context types are covered in this section:

  • Date
  • Time
  • Number
  • Phone_Number
  • Currency
  • Web
  • E-mail
  • Address

Date

This context specifies that the number passed to the engine is a date. Dates will generally have the format of number [delimiter] number [delimiter] number or number [delimiter] number where the delimiter can be a '.', '/' or '-', and numbers are typically between 01 and 12 for months, 01 and 31 for days. A year is generally a two or four-digit number.
The following are valid string types:

date_mdy
This will normalize the date so that the first group of numbers is the month, the second group is the day, and the third group is the year. In the case where the year is a two-digit number, the engine reads it as a two-digit number or a four-digit number.

For example:

<context ID = "date_mdy">12/21/99</context>
will be normalized to "December twenty first ninety nine"
or "December twenty first nineteen ninety nine"

<context ID = "date_mdy">12/21/1999</context>
will be normalized to "December twenty first nineteen ninety nine"

return to the top of this page Back to top

date_dmy
This will normalize the date so that the first group of numbers is the day, the second group is the month, and the third group is the year. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is represented as a four-digit year.

For example:

<context ID = "date_dmy">21.12.99</context>
will be normalized to "December twenty first ninety nine"
or "December twenty first nineteen ninety nine"

<context ID = "date_ dmy">21-12-1999</context>
will be normalized to "December twenty first nineteen ninety nine"

return to the top of this page Back to top

date_ymd
This will normalize the date so that the first group of numbers is the year, the second group is the month, and the third group is the day. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is represented as a four-digit year.

For example:

<context ID = "date_ymd">99-12-21</context>
will be normalized to "December twenty first ninety nine"
or "December twenty first nineteen ninety nine"

<context ID = "date_ ymd">1999.12.21</context>
will be normalized to "December twenty first nineteen ninety nine"

return to the top of this page Back to top

date_ym
This will normalize the date so that the first group of numbers is the year, and the second group is the month. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is represented as a four-digit year.

For example:

<context ID = "date_ym">99-12</context>
will be normalized to "December ninety nine"
or "December nineteen ninety nine"
<context ID = "date_ ym">1999.12</context>
will be normalized to "December nineteen ninety nine"

return to the top of this page Back to top

date_my
This will normalize the date so that the first group of numbers is the month, and the second group is the year. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is represented as a four-digit year.

For example:

<context ID = "date_my">12/99</context>
will be normalized to "December ninety nine"
or "December nineteen ninety nine"

<context ID = "date_my">12/1999</context>
will be normalized to "December nineteen ninety nine"

return to the top of this page Back to top

date_dm
This will normalize the date so that the first group of numbers is the day and the second group is the month.

For example:

<context ID = "date_dm">21.12</context>
will be normalized to "December twenty first"

return to the top of this page Back to top

date_md
This will normalize the date so that the first group of numbers is the month and the second group is the day.

For example:

<context ID = "date_md">12/21</context>
will be normalized to "December twenty first"

return to the top of this page Back to top

date_year
This will normalize the date so that the number is read as a year.

For example:

<context ID = "date_year">1999</context>
will be normalized to "nineteen ninety nine"

<context ID = "date_year">2001</context>
will be normalized to "Two thousand one"

return to the top of this page Back to top

Time

This context specifies that the number passed to the engine is a time. Times will generally have the format of number [delimiter] number [delimiter] number or number [delimiter] number where the delimiter is ':' or ' ' ' or ' " ' and numbers are typically between 01 and 24 for hours, 01 and 59 for minutes and seconds.

When a zero is present in numbers between 01 and 09, the engine can ignore this, or normalize it as "oh". The engine can place an "and" in the normalized time. The valid string types are:

For example:

<context ID = "time">12:30</context>
will be normalized to "twelve thirty"

<context ID = "time">01:21</context>
is normalized as "one twenty one"
or "oh one twenty one"

<context ID = "time">1'21"</context>
is normalized as "one minute twenty one seconds"
or "one minute and twenty one seconds"

return to the top of this page Back to top

Number

number_cardinal
The text is normalized as a number using the regular format of ones, tens, etc. The engine can place "and" in the normalized text.

For example:

<context ID = "number_cardinal">3432</context>
will be normalized to "three thousand four hundred thirty two"

<context ID = "number_cardinal">3432</context>
will be normalized to "three thousand four hundred and thirty two"

return to the top of this page Back to top

number_digit
The text is normalized digit by digit.

For example:

<context ID = "number_digit">3432</context>
will be normalized to "three four three two"

return to the top of this page Back to top

number_fraction
The text is normalized as a fraction.

For example:

<context ID = "number_fraction">3/15</context>
will be normalized to "three fifteenths" or "three over fifteen"

return to the top of this page Back to top

number_decimal
The text is normalized as a decimal value.

For example:

<context ID = "number_decimal">423.1243</context>
will be normalized to "four hundred and twenty three point one two four three"

return to the top of this page Back to top

Phone_Number
The text is normalized as a phone number. The exact implementation of this is left to the engine developer and may be defined in a future release of SAPI.

return to the top of this page Back to top

Currency
The text is normalized as a currency. The exact implementation of this is left to the engine developer and may be defined in a future release of SAPI.

For example:

<context ID = "currency">$34.90</context>
will be normalized to "thirty four dollars and ninety cents"

return to the top of this page Back to top

Web

The text is normalized as a URL. The exact implementation of this is left to the engine developer and may be defined in a future release of SAPI.

web_url

For example:

<context ID = "web_url">www.Microsoft.com</context>
will be normalized to "is normalized to "w w w dot Microsoft dot com"

return to the top of this page Back to top

E-mail

The text is normalized as e-mail. The exact implementation of this is left to the engine developer and may be defined in a future release of SAPI.

E-mail_address
The text is normalized as an e-mail address. The exact implementation of this is left to the engine developer and may be defined in a future release of SAPI.

For example:

<context ID = "E-mail_Address">someone@microsoft.com</context>
is normalized to "Someone at Microsoft dot com"

return to the top of this page Back to top

Address

The text is normalized as an address. The exact implementation of this is left to the engine developer and may be defined in a future release of SAPI.

For example:

<context ID = "address">One Microsoft Way, Redmond, WA, 98052</context>
will be normalized to "One Microsoft Way Redmond Washington nine eight zero five two"

address_postal
The text is normalized as a postal address. The exact implementation of this is left to the engine developer and may be defined in a future release of SAPI.

For example:

<context ID = "address_postal">A2C 4X5</context>
will be normalized to "A 2 C 4 X 5"

return to the top of this page Back to top


Chinese Context tag definitions (Microsoft Speech Platform)

Chinese Context tag definitions

The CONTEXT tag specifies the normalization of a block of text. The context tag ID attribute contains the text string specifying the type of normalization to apply to the text block. The ID attribute of the Chinese engine specific context tags begin with "CHS_". CONTEXT tag ID attribute strings that do not begin with quot;CHS_" use English context text normalization.

For example:
<CONTEXT ID = "CHS_My_Context"> 12/21/99 </CONTEXT>

Each context tag can contain more than one string.

For example:
<CONTEXT ID = "date_mdy"> 12/21/99 11/21/99 10/21/99 </CONTEXT>
is normalized to "Nine nine Nian twelve Yue twenty-one Ri nine nine Nian eleven Yue twenty-one Ri nine nine Nian ten Yue twenty-one Ri"

The following topics are covered in this section:

  • Date
  • Time
  • Number
  • Phone Number and Postal Address

Date

This context specifies that the number passed to the engine is a date. Dates generally have the format of number [delimiter] number [delimiter] number or number [delimiter] number where the delimiter may be a '.', '/' or '-', and numbers are typically between 01 and 12 for months, 01 and 31 for days. A year is a two- or four-digit number.

If a date format does not fall within the range shown below, the application cannot expect a consistent result and the engine may interpret it freely. The valid string types are:

  • Date_mdy
  • Date_dmy
  • Date_ymd
  • CHS_Date_ymdhm
  • Date_ym
  • Date_md
  • Date_dm
  • Date_year

return to the top of this page Back to top

Date_mdy

The text specifying the date is normalized so that the first group of numbers is the month, the second group is the day and the third group is the year. In the case where the year is a two-digit number, the engine reads it as a two-digit number. In the case where the year is a four-digit number, the engine reads it as a four-digit number.

This a common tag with the English engine.

return to the top of this page Back to top

Date_dmy

The text specifying the date is normalized so that the first group of numbers is the day, the second group is the month and the third group is the year. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is represented as a four-digit year.

This a common tag with the English engine.

return to the top of this page Back to top

Date_ymd

The text specifying the date is normalized so that the first group of numbers is the year, the second group is the month and the third group is the day. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is represented as a four-digit year.

This a common tag with the English engine.

return to the top of this page Back to top

CHS_Date_ymdhm

The text specifying the date is normalized so that the first group of numbers is the year, the second group is the month, the third group is the day, the fourth group is the hour and the fifth group is the minute. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is represented as a four-digit year. The text format for time needs to specify the hour as a number between 00 and 23 (in case of with PM/AM before, between 01 and 12), and the minute as a number between 01 and 59.

This is a Chinese specific context tag.

return to the top of this page Back to top

Date_ym

The text specifying the date is normalized so that the first group of numbers is the year and the second group is the month. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is represented as a four-digit year.

This a common tag with the English engine

return to the top of this page Back to top

Date_my

The text specifying the date is normalized so that the first group of numbers is the month and the second group is the year. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is represented as a four-digit year.

This a common tag with the English engine.

return to the top of this page Back to top

Date_md

The text specifying the date is normalized so that the first group of numbers is the month and the second group is the day.

This a common tag with the English engine.

return to the top of this page Back to top

Date_dm

The text specifying the date is normalized so that the first group of numbers is the day and the second group is the month.

This a common tag with the English engine.

return to the top of this page Back to top

Date_year

The text specifying the date is normalized so that the number is read as a year. This year should be a four-digit number.

This a common tag with the English engine.

return to the top of this page Back to top

Time

This context specifies that the number passed to the engine is a time. Times generally have the format of number [delimiter] number [delimiter] number or number [delimiter] number where the delimiter is ':' and numbers are typically between 00 and 23 for hours (in case of with PM/AM before, it needs to be between 01 and 12), 00 and 59 for minutes and seconds.

  • CHS_time_hms
  • CHS_time_hm

When a zero is present in numbers between 01 and 09, the engine ignores it.

This is a Chinese engine specific context tag.

return to the top of this page Back to top

CHS_time_hms

The text specifying the time is normalized so that the first group of numbers is the hour, the second group is the minute and the third group is the second.

This is a Chinese engine specific context tag.

return to the top of this page Back to top

CHS_time_hm

The text specifying the time is normalized so that the first group of numbers is the hour and the second group is the minute.

This is a Chinese engine specific context tag.

return to the top of this page Back to top

Number

This context specifies how to read the number passed to the engine.

  • number_cardinal
  • number_digit
  • number_fraction
  • number_decimal
  • CHS_number_percentage
  • CHS_number_scientific

number_cardinal

The text is normalized as a number using the regular format of ones, tens, etc.

This a common tag with the English engine.

return to the top of this page Back to top

number_digit

The text is normalized digit by digit.

This a common tag with the English engine.

return to the top of this page Back to top

number_fraction

The text is normalized as a fraction

This a common tag with the English engine.

return to the top of this page Back to top

number_decimal

The text is normalized as a decimal value.

This a common tag with the English engine.

return to the top of this page Back to top

CHS_number_percentage

The text is normalized as a percentage value.

This is a Chinese engine specific context tag.

return to the top of this page Back to top

CHS_number_scientific

The text is normalized as a scientific value.

This is a Chinese engine specific context tag.

return to the top of this page Back to top

Phone_Number/address_postal

The text is normalized as a phone number or address postal.

  • CHS_phone_postal

CHS_phone_postal

The phone number and address postal is almost the same as that of number_cardinal--the only difference is that "1" is read as "yao1"

This is a Chinese engine specific context tag.

return to the top of this page Back to top


Japanese Context tag definitions (Microsoft Speech Platform)

Japanese Context tag definitions

The CONTEXT tag specifies the normalization of a block of text. This specification defines the SAPI predefined attributes (ID) for the CONTEXT tag. These IDs are strings. SAPI does not validate any parameters on the string passed to the engine, and hence, the application can specify engine-specific normalization IDs to the engine. Engine-specific strings begin with the engine vendor's name to avoid confusion between engines.

For example:
<CONTEXT ID = "MS_My_Context"> text </CONTEXT>

The exact implementation of some of these values is dependent on the engine in SAPI 5. In order to force a certain normalization, application developers can choose to normalize the text, or use another SAPI tag or engine-specific ID. Each context tag can contain more than one string.

For example:
<CONTEXT ID = "MS_My_Context"> text1 text2 text3 </CONTEXT>

A clearer example is shown in the following:

example:

The following topics are covered in this section:

  • Date
  • Time
  • Number
  • Phone_Number
  • Currency
  • Web
  • Address

Date

This context specifies that the number passed to the engine is a date. Dates generally have the format of number [delimiter] number [delimiter] number or number [delimiter] number where the delimiter may be a '.', '/' or '-', and numbers are typically between 01 and 12 for months, 01 and 31 for days. A year is generally a two- or four-digit number. If a date format does not fall within the range shown below, the application cannot expect a consistent result and the engine may interpret it freely. The valid string types are:

  • date_mdy
  • date_dmy
  • date_ymd
  • date_ym
  • date_my
  • date_dm
  • date_md
  • date_year

return to the top of this page Back to top

date_mdy

The text specifying the date is normalized so that the first group of numbers is the month, the second group is the day and the third group is the year. In the case where the year is a two-digit number, the engine reads it as a two-digit number or a four-digit number.

return to the top of this page Back to top

date_dmy

The text specifying the date is normalized so that the first group of numbers is the day, the second group is the month and the third group is the year. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is be represented as a four-digit year.

return to the top of this page Back to top

date_ymd

The text specifying the date is normalized so that the first group of numbers is the year, the second group is the month and the third group is the day. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is be represented as a four-digit year.

return to the top of this page Back to top

date_ym

The text specifying the date is normalized so that the first group of numbers is the year and the second group is the month. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is be represented as a four-digit year.

return to the top of this page Back to top

date_my

The text specifying the date is normalized so that the first group of numbers is the month and the second group is the year. In the case where the year is a two-digit number, the engine reads it as a two-digit number. If the year is represented as a four-digit number, it is be represented as a four-digit year.

return to the top of this page Back to top

date_dm

The text specifying the date is normalized so that the first group of numbers is the day and the second group is the month.

return to the top of this page Back to top

date_md

The text specifying the date is normalized so that the first group of numbers is the month and the second group is the day.

return to the top of this page Back to top

date_year

The text specifying the date is normalized so that the number is read as a year.

return to the top of this page Back to top

Time

This context specifies that the number passed to the engine is a time. Times generally have the format of number [delimiter] number [delimiter] number or number [delimiter] number where the delimiter is ':' or ''' or ' " 'and numbers are typically between 01 and 24 for hours, 01 and 59 for minutes and seconds.

When a zero is present in numbers between 01 and 09, the engine can ignore this, or normalize it as "oh". The engine can also place an "and" in the normalized time. The valid string types are:

return to the top of this page Back to top

Number

  • number_cardinal
  • number_digit
  • number_fraction
  • number_decimal

return to the top of this page Back to top

number_cardinal

The text is normalized as a number using the regular format of ones, tens, etc. The engine can place "and" in the normalized text.

return to the top of this page Back to top

number_digit

The text is normalized digit by digit.

return to the top of this page Back to top

number_fraction

The text is normalized as a fraction.

return to the top of this page Back to top

number_decimal

The text is normalized as a decimal value.

return to the top of this page Back to top

Phone_Number

The text is normalized as a phone number. The exact implementation of this is left to the engine developer and may be defined in a future release of SAPI. An example is provided below:

return to the top of this page Back to top

Currency

The text is normalized as a currency. The exact implementation of this is left to the engine developer and may be defined in a future release of SAPI. An example is provided below:

return to the top of this page Back to top

Web

web_url

The text is normalized as a URL. The exact implementation of this is left to the engine developer and may be defined in a future release of SAPI. An example is provided below:

return to the top of this page Back to top

E-mail

E-mail_address

The text is normalized as e-mail. The exact implementation of this is left to the engine developer and may be defined in a future release of SAPI.

return to the top of this page Back to top

Address

The text is normalized as an address. The exact implementation of this is left to the engine developer and may be defined in a future release of SAPI. An example is provided below:

return to the top of this page Back to top


ISpVoice (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice

The ISpVoice interface enables an application to perform text synthesis operations. Applications can speak text strings and text files, or play audio files through this interface. All of these can be done synchronously or asynchronously.

Applications can choose a specific TTS voice using ISpVoice::SetVoice. The state of the voice (for example, rate, pitch, and volume), can be modified using SAPI XML tags that are embedded into the spoken text. Some attributes, like rate and volume, can be changed in real time using ISpVoice::SetRate and ISpVoice::SetVolume. Voices can be set to different priorities using ISpVoice::SetPriority.

ISpVoice inherits from the ISpEventSource interface. An ISpVoice object forwards events back to the application when the corresponding audio data has been rendered to the output device.

Associated Class IDs

The following class IDs (CLSID) may be used with this interface. A complete CLSID listing for all interfaces is in the Class IDs section.

CLSID_SpVoice

Methods in Vtable Order

ISpVoice Methods | Description
ISpEventSource inherited methods | All methods of ISpEventSource are accessible from this interface
SetOutput | Sets the current output object. A value of NULL may be used to select the default audio device.
GetOutputObjectToken | Retrieves the object token for the current audio output object.
GetOutputStream | Retrieves a pointer to the current output stream.
Pause | Pauses the voice at the nearest alert boundary and closes the output device.
Resume | Sets the output device to the RUN state and resumes rendering.
SetVoice | Sets the identity of the voice used for text synthesis. By default, ISpVoice will use the voice information set in Speech properties in Control Panel.
GetVoice | Retrieves the object token that identifies the voice used in text synthesis.
Speak | Speaks the contents of a text string or file.
SpeakStream | Speaks the contents of a stream.
GetStatus | Retrieves the current rendering and event status associated with this ISpVoice instance.
Skip | Causes the voice to skip forward or backward the specified number of items within the text of the current speak call.
SetPriority | Sets the priority for the voice. Normal, Alert, Over.
GetPriority | Retrieves the current voice priority level.
SetAlertBoundary | Specifies which event should be used as the insertion point for alerts.
GetAlertBoundary | Retrieves the event that is currently being used as the insertion point for alerts.
SetRate | Sets the text rendering rate adjustment in real time.
GetRate | Retrieves the current text rendering rate adjustment.
SetVolume | Sets the synthesizer output volume level in real time.
GetVolume | Retrieves the current output volume level of the synthesizer.
WaitUntilDone | Blocks the caller until either the voice has completed speaking or the specified time interval has elapsed.
SetSyncSpeakTimeout | Sets the timeout interval in milliseconds after which, synchronous Speak and SpeakStream calls to this instance of the voice will timeout.
GetSyncSpeakTimeout | Retrieves the timeout interval for synchronous speech operations for this ISpVoice instance.
SpeakCompleteEvent | Returns an event handle that will be signaled when the voice has completed speaking all pending requests.
IsUISupported | Determines if the specified type of UI is supported.
DisplayUI | Displays the requested UI.


ISpVoice::SetOutput (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::SetOutput

ISpVoice::SetOutput sets the current output object. The object may either be a stream, audio device, or an object token for an output audio device. If pUnkOutput is NULL the default audio device will be used.

HRESULT SetOutput(
   IUnknown   *pUnkOutput,
   BOOL        fAllowFormatChanges
);

Parameters

pUnkOutput
[in] IUnknown pointer to output object. The pointer must point to an object that implements ISpStreamFormat (a stream or audio device), or an object that implements ISpObjectToken. If a token is provided, this method will create the object described by the token and use it. If pUnkOutput is NULL, the default audio out device will be used.
fAllowFormatChanges
[in] Flag specifying whether the voice is allowed to change the format of the audio output object to match that of the engine, or a wav stream being spoken. If FALSE, the voice will use the SAPI format converter to translate between the data being rendered and the format of the output object. This should be set to TRUE if using the default audio device and the output format is of no consequence. If pUnkOutput is an ISpStreamFormat object, fAllowFormatChanges is ignored. In this case, the voice instance will render the output audio data in the format of the specified stream to the application.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
SPERR_UNINITIALIZED | pUnkOutput is an uninitialized ISpStream object.
E_OUTOFMEMORY | Exceeded available memory.
Example:

The following is an example of how to enumerate all the available audio output devices registered under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\AudioOutput.

// Declare local identifiers:
HRESULT                        hr = S_OK;
CComPtr<ISpObjectToken>        cpAudioOutToken;
CComPtr<IEnumSpObjectTokens>   cpEnum;
CComPtr<ISpVoice>              cpVoice;
ULONG                          ulCount = 0;

// Create the SAPI voice.
hr = cpVoice.CoCreateInstance(CLSID_SpVoice);

if (SUCCEEDED (hr))
{
   // Enumerate the available audio output devices.
   hr = SpEnumTokens( SPCAT_AUDIOOUT, NULL, NULL, &cpEnum );
}

if (SUCCEEDED (hr))
{
   // Get the number of audio output devices.
   hr = cpEnum->GetCount( &ulCount );
}

// Obtain a list of available audio output tokens,
// set the output to the token, and call Speak.
while (SUCCEEDED(hr) && ulCount--)
{
   if (SUCCEEDED (hr))
   {
      hr = cpEnum->Next( 1, &cpAudioOutToken, NULL );
   }

   if (SUCCEEDED (hr))
   {
      hr = cpVoice->SetOutput( cpAudioOutToken, TRUE );
   }

   if (SUCCEEDED (hr))
   {
      hr = cpVoice->Speak( L"How are you?", SPF_DEFAULT, NULL );
   }
}

if (SUCCEEDED (hr))
{
   // Do more stuff here.
}


ISpVoice::GetOutputObjectToken (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::GetOutputObjectToken

ISpVoice::GetOutputObjectToken retrieves the object token for the current audio output object.

HRESULT GetOutputObjectToken(
   ISpObjectToken   **ppObjectToken
);

Parameters

ppObjectToken
[out] Address of an ISpObjectToken pointer that receives the audio output object token. If the current output is set to an ISpStream object, GetOutputObjectToken will return S_FALSE and ppObjectToken will be NULL.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppObjectToken is invalid.
S_FALSE | The current output stream does not have an object token


ISpVoice::GetOutputStream (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::GetOutputStream

ISpVoice::GetOutputStream retrieves a pointer to the current output stream.

HRESULT GetOutputStream(
   ISpStreamFormat   **ppStream
);

Parameters

ppStream
[out] Address of a pointer to an ISpStreamFormat object that receives the output stream.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppstream is invalid.


ISpVoice::Pause (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::Pause

ISpVoice::Pause pauses the voice at the nearest alert boundary and closes the output device, allowing access to pending speak requests from other voices.

HRESULT  Pause  ( void );

Parameters

None.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED(hr) | Appropriate error message
Remarks:

Calling ISpVoice::Pause while the voice is not speaking increments the pause count and will put the voice into a paused state until ISpVoice::Resume is called the same number of times.

The voice maintains a pause count, so each call to pause must be balanced with a corresponding call to ISpVoice::Resume.

The default alert boundary is at the beginning of each word. See ISpVoice::SetAlertBoundary for details.


ISpVoice::Resume (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::Resume

ISpVoice::Resume sets the output device to the RUN state and resumes rendering.

It decrements the pause count (which is incremented by ISpVoice::Pause) if the voice is currently paused. If the pause count hits zero, Resume attempts to reclaim the output device and resumes rendering. This method has no effect if the voice was not in a paused state.

HRESULT  Resume  ( void );

Parameters

None.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED(hr) | Appropriate error message.


ISpVoice::SetVoice (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::SetVoice

ISpVoice::SetVoice sets the identity of the voice used for text synthesis. ISpVoice normally uses the default voice, which is set through Speech properties in Control Panel.

HRESULT SetVoice(
   ISpObjectToken   *pToken
);

Parameters

pToken
[in] Pointer to token that describes the requested voice. If pToken is NULL, the system default voice is used.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.

Remarks

Changing the voice selection will preserve the same volume and rate levels for an ISpVoice object.

Example

The following is an example to enumerate all the available voices registered under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices.

// Declare local identifiers:
HRESULT                        hr = S_OK;
CComPtr<ISpObjectToken>        cpVoiceToken;
CComPtr<IEnumSpObjectTokens>   cpEnum;
CComPtr<ISpVoice>              cpVoice;
ULONG                          ulCount = 0;

// Create the SAPI voice.
hr = cpVoice.CoCreateInstance(CLSID_SpVoice);

if (SUCCEEDED (hr))
{
   // Enumerate the available voices.
   hr = SpEnumTokens(SPCAT_VOICES, NULL, NULL, &cpEnum);
}

if (SUCCEEDED (hr))
{
   // Get the number of voices.
   hr = cpEnum->GetCount(&ulCount);
}

// Obtain a list of available voice tokens, set
// the voice to the token, and call Speak.
while (SUCCEEDED(hr) && ulCount--)
{
   cpVoiceToken.Release();

   if (SUCCEEDED (hr))
   {
      hr = cpEnum->Next(1, &cpVoiceToken, NULL);
   }

   if (SUCCEEDED (hr))
   {
      hr = cpVoice->SetVoice(cpVoiceToken);
   }

   if (SUCCEEDED (hr))
   {
      hr = cpVoice->Speak( L"How are you?", SPF_DEFAULT, NULL );
   }

}

if (SUCCEEDED (hr))
{
   // Do more stuff here.
}


ISpVoice::GetVoice (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::GetVoice

ISpVoice::GetVoice retrieves the object token that identifies the voice currently in use. If there is not a voice currently in use, this method will return the token for the default voice.

HRESULT GetVoice(
   ISpObjectToken   **ppToken
);

Parameters

ppToken
[out] Pointer which will be set to point to the current voice's object token.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | ppToken is invalid.


ISpVoice::Speak (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::Speak

ISpVoice::Speak speaks the contents of a text string or file.

HRESULT Speak(
   LPCWSTR       *pwcs,
   DWORD          dwFlags,
   ULONG         *pulStreamNumber
);

Parameters

pwcs
[in, string] Pointer to the null-terminated text string (possibly containing XML markup) to be synthesized. This value can be NULL when dwFlags is set to SPF_PURGEBEFORESPEAK indicating that any remaining data to be synthesized should be discarded. If dwFlags is set to SPF_IS_FILENAME, this value should point to a null-terminated, fully qualified path to a file.
dwFlags
[in] Flags used to control the rendering process for this call. The flag values are contained in the SPEAKFLAGS enumeration.
pulStreamNumber
[out] Pointer to a ULONG which receives the current input stream number associated with this Speak request. Each time a string is spoken, an associated stream number is returned. Events queued back to the application related to this string will contain this number. If NULL, no value is passed back.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
E_POINTER | Invalid pointer.
E_OUTOFMEMORY | Exceeded available memory.
SPERR_INVALID_FLAGS | Invalid flags specified for this operation.
SPERR_DEVICE_BUSY | Timeout occurred on synchronous call.

Remarks

Normally, pulStreamNumber will just be 1. If, however, several asynchronous Speak (or SpeakStream) calls are received and must be queued, the stream number will be incremented for each call.

If Speak is called with markup parameters such as Emph, Spell, and Context, that cannot be empty, SAPI does not return an error code. For example, the following example returns S_OK.

hr = cpVoice->Speak(L"<EMPH/>Do it now", SPF_IS_XML, 0);


ISpVoice::SpeakStream (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::SpeakStream

ISpVoice::SpeakStream speaks the contents of a stream.

HRESULT SpeakStream(
   IStream   *pStream,
   DWORD      dwFlags,
   ULONG     *pulStreamNumber
);

Parameters

pStream
[in] Address of an IStream interface containing the input stream. If the ISpStreamFormat interface is not implemented by the input stream, the format type is assumed to be SPDFID_Text.
dwFlags
[in] Flags used to control the rendering process for this call. The flag values are contained in the SPEAKFLAGS enumeration, however the SPF_IS_FILENAME flag is not used for SpeakStream.
pulStreamNumber
[out] Pointer to a ULONG which receives the current input stream number associated with this SpeakStream request. Each time a string is spoken, an associated stream number is returned. Events queued back to the application related to this string will contain this number.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
E_POINTER | Invalid pointer.
E_OUTOFMEMORY | Exceeded available memory.
SPERR_INVALID_FLAGS | Invalid flags specified for this operation.
SPERR_DEVICE_BUSY | Timeout on synchronous call.

Remarks

If the input stream is wave data, it is sent directly to the output object. For more information about connecting an input stream to a voice, see ISpStream::BindToFile.

If the input stream is text data, it is processed by the text-to-speech engine.

Normally, pulStreamNumber will just be 1. If, however, several asynchronous SpeakStream (or Speak) calls are received and must be queued, the stream number will be incremented for each call.


ISpVoice::GetStatus (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::GetStatus

ISpVoice::GetStatus retrieves the current rendering and event status associated with this voice.

HRESULT GetStatus(
   SPVOICESTATUS   *pStatus,
   LPWSTR         **ppszLastBookmark
);

Parameters

pStatus
[out] Pointer to an SPVOICESTATUS structure which receives the status information. This pointer can be NULL if the caller does not want this information.
ppszLastBookmark
[out, string] Pointer to a pointer which receives a CoTaskMemAlloc allocated null-terminated string containing the text of the last bookmark reached. If there is no last bookmark, NULL will be returned. Applications calling this method must call CoTaskMemFree() to free the returned string. This pointer can be NULL if the caller does not want this information.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Invalid pointer.
E_OUTOFMEMORY | Exceeded available memory.

Remarks

Because the SPVOICESTATUS structure is closely associated with audio device status, GetStatus will not return an active status for a voice speaking to an audio output stream.


ISpVoice::Skip (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::Skip

ISpVoice::Skip causes the voice to skip forward or backward the specified number of items within the text of the current speak call.

HRESULT Skip(
   LPCWSTR   *pItemType,
   long       lNumItems,
   ULONG     *pulNumSkipped
);

Parameters

pItemType
[in,string] Specifies the type of item to skip. There are currently two supported types: "SENTENCE" and "MILLISECONDS".
lNumItems
[in] Specifies the number of items to skip in the current speak request. If lNumItems is a positive number, the voice will skip forward, and if it is negative, the voice will skip backward. If lNumItems is 0, the voice will skip back to the beginning of the current item.
pulNumSkipped
[out] Pointer to a ULONG which will be set to the actual number of items skipped.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pItemType is invalid or bad.
E_POINTER | pulNumSkipped is invalid or bad.
SPERR_VOICE_PAUSED | Voice is in a paused state and may not be skipped.


ISpVoice::SetPriority (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::SetPriority

ISpVoice::SetPriority sets the priority for the voice. The default priority is SPVPRI_NORMAL.

HRESULT SetPriority(
   SPVPRIORITY   ePriority
);

Parameters

ePriority
[in] Priority of type SPVPRIORITY associated with the current voice.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | ePriority is not an acceptable priority value.

Remarks

Assuming an output object which implements ISpAudio, speak requests of similar priority voices are queued, and are spoken one at a time in the order they are issued. That is, speak requests from normal priority voices are put in one queue, while speak requests from alert priority voices (with priority SPVPRI_ALERT) are put in another queue.

Alert priority voices take priority over normal voices. If one or more speak requests from alert priority voices are pending, a normal voice that is speaking will be interrupted on the next alert boundary (see ISpVoice::SetAlertBoundary). When all the queued alert priority voice speak requests have been processed, the normal voice will continue.

Voices with the SPVPRI_OVER priority speak over (mix with) all other audio in the system with no synchronization. SPVPRI_OVER priority voices only mix on Windows 2000.

If the output object does not implement ISpAudio, no serialization will occur, and all voices will be treated as if their priority is SPVPRI_OVER.


ISpVoice::GetPriority (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::GetPriority

ISpVoice::GetPriority retrieves the current voice priority level. See ISpVoice::SetPriority for more information on voice priorities.

HRESULT GetPriority(
   SPVPRIORITY   *pePriority
);

Parameters

pePriority
[out] Pointer to priority information of type SPVPRIORITY.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Invalid pointer.


ISpVoice::SetAlertBoundary (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::SetAlertBoundary

ISpVoice::SetAlertBoundary specifies which event should be used as the insertion point for alert priority voice interruptions and ISpVoice::Pause calls.

HRESULT SetAlertBoundary(
   SPEVENTENUM   eBoundary
);

Parameters

eBoundary
[in] SPEVENTENUM enumeration value that specifies which event to use for the alert insertion point. Appropriate events to use for this purpose include SPEI_WORD_BOUNDARY, SPEI_SENTENCE_BOUNDARY, SPEI_PHONEME, SPEI_VISEME, and possibly SPEI_VOICE_CHANGE or SPEI_TTS_BOOKMARK.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | eBoundary is invalid.

Remarks

Events, such as word and sentence boundaries, are queued by the TTS engine during text rendering. Alert priority voices will only be able to interrupt normal priority voices, and pauses will only be able to occur on the specified event boundaries.

The default alert boundary event is SPEI_WORD_BOUNDARY.

See ISpVoice::SetPriority for more details on voice priorities.


ISpVoice::GetAlertBoundary (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::GetAlertBoundary

ISpVoice::GetAlertBoundary retrieves the event that is currently being used as the insertion point for alerts. For more information on alert boundaries, see ISpVoice::SetAlertBoundary.

HRESULT GetAlertBoundary(
   SPEVENTENUM   *peBoundary
);

Parameters

peBoundary
[out] Address of an SPEVENTENUM that receives the event type of the alert boundary.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Invalid pointer.


ISpVoice::SetRate (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::SetRate

ISpVoice::SetRate retrieves the current text rendering rate adjustment. The default rate for a voice is set through Speech properties in Control Panel.

HRESULT SetRate(
   long   RateAdjust
);

Parameters

RateAdjust
[in] Value specifying the speaking rate of the voice. Supported values range from -10 to 10 - values outside this range may be truncated.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.

Remarks

Voices do not all have the same default rate.

The granularity of the rate is engine dependent.

Applications can adjust the rate of a voice either through this function call, or through XML passed to the voice with the input text of a speak call. The voice should combine rate adjustments made in these two ways to arrive at a final rate.


ISpVoice::GetRate (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::GetRate

ISpVoice::GetRate retrieves the current base rate (either the default rate or the last value set by ISpVoice::SetRate).

HRESULT GetRate(
   long   *pRateAdjust
);

Parameters

pRateAdjust
[out] Pointer to a long which receives the base rate.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pRateAdjust is invalid.


ISpVoice::SetVolume (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::SetVolume

ISpVoice::SetVolume sets the synthesizer output volume level of the voice in real time. The default base volume for all voices is 100.

HRESULT SetVolume(
   USHORT 	usVolume
);

Parameters

usVolume
[in] Value containing the requested volume level. Volume levels are specified in percentage values ranging from zero to 100 - values outside this range may be truncated.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.

Remarks

SetVolume affects the volume of synthesized WAV data; it does not affect the volume of the .WAV file that is played back. Volume is specified as a percentage of the maximum volume of the current voice. Different voices may have different maximum volume levels.

Applications can adjust the volume of a voice either through this function call, or through XML grammar passed to the voice with the input text of a speak call. The voice should combine volume adjustments made in these two ways to arrive at a final volume.


ISpVoice::GetVolume (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::GetVolume

ISpVoice::GetVolume retrieves the current output volume level (either the default volume level or the last level set by ISpVoice::SetVolume).

HRESULT GetVolume(
   USHORT   *pusVolume
);

Parameters

pusVolume
[out] Address to receive the current base volume level.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pusVolume is invalid.


ISpVoice::WaitUntilDone (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::WaitUntilDone

ISpVoice::WaitUntilDone blocks the caller until either the voice has completed speaking or the specified time interval has elapsed.

HRESULT WaitUntilDone(
   ULONG   msTimeout
);

Parameters

msTimeout
[in] Timeout period in milliseconds. INFINITE may be used to prevent this method from timing out.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | Wait time interval was exceeded.

Remarks

This call may be used after a single asynchronous Speak (or SpeakStream) call, or after several calls have been queued. In either case it will return only after all pending calls have been completed (or after the specified time interval has elapsed).


ISpVoice::SetSyncSpeakTimeout (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::SetSyncSpeakTimeout

ISpVoice::SetSyncSpeakTimeout sets the timeout interval in milliseconds after which synchronous Speak and SpeakStream calls to this voice will timeout.

HRESULT SetSyncSpeakTimeout(
   ULONG   msTimeout
);

Parameters

msTimeout
[in] Value specifying the timeout interval in milliseconds. The default is 10 seconds. INFINITE may also be used to prevent timeouts.

Return values

Value | Description
S_OK | Function completed successfully.

Remarks:

Timeouts occur when waiting for access to the output object. This means that for a normal priority voice (see ISpVoice::SetPriority for more information on priorities) and an output device which implements ISpAudio, a timeout may occur while waiting to reacquire the output object after an interruption by an alert priority voice. For voices of both normal and alert priorities, a timeout may also occur while waiting to reacquire the output object after the voice has been paused and resumed (see ISpVoice::Pause and ISpVoice::Resume).

Wait times are not accumulated - that is, if a voice waits for n milliseconds to initially acquire the output object, and is then paused and resumed, it will again wait for up to msTimeout milliseconds to reacquire the output object, not msTimeout - n milliseconds.


ISpVoice::GetSyncSpeakTimeout (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::GetSyncSpeakTimeout

ISpVoice::GetSyncSpeakTimeout retrieves the timeout interval for synchronous speech operations for this voice. For more information on timeouts, see ISpVoice::SetSyncSpeakTimeout.

HRESULT GetSyncSpeakTimeout(
   ULONG   *pmsTimeout
);

Parameters

pmsTimeout
[out] Pointer to a ULONG which receives the timeout interval in milliseconds for synchronous speech operations.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | pmsTimeout is invalid.


ISpVoice::SpeakCompleteEvent (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::SpeakCompleteEvent

ISpVoice::SpeakCompleteEvent returns an event handle that will be signaled when the voice has completed speaking all pending requests. This is similar to the functionality provided by ISpVoice::WaitUntilDone, but allows the caller to wait on the event handle.

[local] HANDLE  SpeakCompleteEvent  ( void );

Parameters

None.

Return values

Value | Description
Event Handle | For WAIT operation.

Remarks:

The caller should not call CloseHandle(), nor should the caller ever use the handle after releasing the COM reference to this voice.


ISpVoice::IsUISupported (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::IsUISupported

ISpVoice::IsUISupported checks if the underlying text-to-speech engine's object token supports the requested UI.

[local] HRESULT IsUISupported(
    const WCHAR   *pszTypeOfUI,
    void          *pvExtraData,
    ULONG          cbExtraData,
    BOOL          *pfSupported
);

Parameters

pszTypeOfUI
[in] Address of the null-terminated string containing the UI type that is being queried.
pvExtraData
[in] Pointer to additional information needed for the object. The TTS Engine implementer dictates the format and usage of the data provided.
cbExtraData
[in] Size, in bytes, of the ExtraData. The TTS Engine implementer dictates the format and usage of the data provided.
pfSupported
[out] Flag specifying whether the specified UI is supported. TRUE indicates the UI is supported, and FALSE indicates the UI is not supported. If this value is TRUE, but the return code is S_FALSE, the UI type (pszTypeOfUI) is supported, but not with the current parameters or run-time environment. Check with the engine implementer to verify run-time requirements.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | The UI is supported but not with the current run-time environment or parameters.
E_INVALIDARG | One or more parameters are invalid.
FAILED(hr) | Appropriate error message.

Remarks

See the TTS Engine White Paper for further information on how a TTS Engine should implement UI.

Example

The following code snippet illustrates the use of ISpVoice::IsUISupported.

// Declare local identifiers:
HRESULT	             hr = S_OK;
CComPtr<ISpVoice>    cpVoice;
BOOL                 fSupported;

// Display properties UI for the current TTS engine.
hr = cpVoice->IsUISupported(SPDUI_EngineProperties, NULL, NULL, &fSupported);

if (SUCCEEDED (hr))
{
   // if fSupported == TRUE, then current TTS engine supports properties UI.
}


ISpVoice::DisplayUI (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpVoice::DisplayUI

ISpVoice::DisplayUI displays the UI from the underlying text-to-speech engine's object token.

[local] HRESULT DisplayUI(
    HWND           hwndParent,
    LPCWSTR       *pszTitle,
    LPCWSTR       *pszTypeOfUI,
    void          *pvExtraData,
    ULONG          cbExtraData
);

Parameters

hwndParent
[in] Specifies the parent window handle information.
pszTitle
[in] Address of a null-terminated string containing the window title information. Set this value to NULL to indicate that the TTS engine should use its default window title for this UI type.
pszTypeOfUI
[in] Address of the null-terminated string containing the requested UI type to display.
pvExtraData
[in] Pointer to additional information needed for the object. The TTS Engine implementer dictates the format and usage of the data provided.
cbExtraData
[in] Size, in bytes, of the ExtraData. The TTS Engine implementer dictates the format and usage of the data provided.

Return values

Value | Description
S_OK | Function completed successfully.
S_FALSE | The UI is supported but not with the current run-time environment or parameters.
E_INVALIDARG | One or more parameters are invalid.
FAILED(hr) | Appropriate error message.

Remarks

The best practice for using ISpVoice::DisplayUI is to call ISpVoice::IsUISupported with a specific UI type before calling DisplayUI.

See the TTS Engine White Paper for further information on how a TTS Engine should implement UI.

The call to DisplayUI is synchronous, so the call will not return until the UI has been closed.

Example

The following code snippet illustrates the use of ISpVoice::DisplayUI.

// Declare local identifiers:
HRESULT	             hr = S_OK;
CComPtr<ISpVoice>    cpVoice;
HWND                 hwndParent;

// Display properties UI for the current TTS engine.
hr = cpVoice->DisplayUI(hwndParent, L"My App's Caption", SPDUI_EngineProperties, NULL, NULL);

if (SUCCEEDED (hr))
{
   // Do some more stuff.
}


Structures (Microsoft Speech Platform)

 Microsoft Speech Platform

Structures

The following structures are used with the Microsoft Speech Platform.

  • SPAUDIOBUFFERINFO
  • SPAUDIOSTATUS
  • SPBINARYGRAMMAR
  • SPEVENT
  • SPEVENTEX
  • SPEVENTSOURCEINFO
  • SPNORMALIZATIONLIST
  • SPPHRASE
  • SPPHRASEELEMENT
  • SPPHRASEPROPERTY
  • SPPHRASEREPLACEMENT
  • SPPHRASERULE
  • SPPROPERTYINFO
  • SPRECOCONTEXTSTATUS
  • SPRECOGNIZERSTATUS
  • SPRECORESULTTIMES
  • SPRULE
  • SPSEMANTICERRORINFO
  • SPSERIALIZEDEVENT
  • SPSERIALIZEDEVENT64
  • SPSERIALIZEDPHRASE
  • SPSERIALIZEDRESULT
  • SPSHORTCUTPAIR
  • SPSHORTCUTPAIRLIST
  • SPTEXTSELECTIONINFO
  • SPVCONTEXT
  • SPVOICESTATUS
  • SPVPITCH
  • SPVSTATE
  • SPWORD
  • SPWORDLIST
  • SPWORDPRONUNCIATION
  • SPWORDPRONUNCIATIONLIST
  • WAVEFORMATEX


SPAUDIOBUFFERINFO (Microsoft Speech Platform)

 Microsoft Speech Platform

SPAUDIOBUFFERINFO

SPAUDIOBUFFERINFO contains the audio stream buffer information.

Real-time audio objects (e.g., ISpMMSysAudio or a custom ISpAudio-based audio object) should use a buffer to allow for latency in the audio stream, either during reads or writes. The SPAUDIOBUFFERINFO structure contains elements that define how the buffer should be used at run time (e.g., buffer size, event latency, etc.)

typedef struct SPAUDIOBUFFERINFO
{
    ULONG        ulMsMinNotification;
    ULONG        ulMsBufferSize;
    ULONG        ulMsEventBias;
} SPAUDIOBUFFERINFO;

Members

ulMsMinNotification
The minimum preferred time, in milliseconds, between the actual time an event notification occurs and the ideal time. More CPU resources are needed when the amount of time is shorter; however, the event notifications are more timely. This value must be greater than zero and no more than one quarter the size of the ulMsBuffersize.
A reasonable default is 50ms.
ulMsBufferSize
The size of the audio object's buffer, in milliseconds. For readable audio objects, this is simply a preferred size; readable objects will automatically expand their buffers to accommodate data. For writable audio objects, this is the amount of audio data that will be buffered before a call to Write will block. This value must be greater than or equal to 200 milliseconds.
A reasonable default is 500ms.
ulMsEventBias
The amount of time, in milliseconds, by which event notifications precede the actual occurrence of the events. For example, setting a value of 100 for the event bias would cause all events to be notified 100 milliseconds prior to the audio data being played. This can be useful for applications needing time to animate mouths for TTS voices. This value cannot be larger than ulMsBufferSize.
A reasonable default is 0ms; applications should set ulMsEventBias based on specific circumstances.


SPAUDIOSTATUS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPAUDIOSTATUS

SPAUDIOSTATUS is used to indicate the state of an audio device.

typedef struct SPAUDIOSTATUS
{
    long            cbFreeBuffSpace;
    ULONG           cbNonBlockingIO;
    SPAUDIOSTATE    State;
    ULONGLONG       CurSeekPos;
    ULONGLONG       CurDevicePos;
    DWORD           dwAudioLevel;
    DWORD           dwReserved2;
} SPAUDIOSTATUS;

Members

cbFreeBuffSpace
Size, in bytes, of free space for reading and/or writing in the audio object.
cbNonBlockingIO
The amount of data which can be read from or written to a device without blocking.
State
The state (of type SPAUDIOSTATE) of the audio device.
CurSeekPos
The current seek position, in bytes, within the audio stream. This is the position in the stream where the next read or write will be performed.
CurDevicePos
The current read position, in bytes, of the device. This is the position in the stream where the device is currently reading or writing. For readable streams, this value will always be greater than or equal to CurSeekPos. For writable streams, this value will always be less than or equal to CurSeekPos.
dwAudioLevel
The field dwAudioLevel occupies the space previously called dwReserved1. dwAudioLevel provides the current input audio level. This is not the "volume" (that is, it is input, not output). This is the field used in the microphone meter in the speech control panel.
dwReserved2
Reserved for future expansion.


SPBINARYGRAMMAR (Microsoft Speech Platform)

 Microsoft Speech Platform

SPBINARYGRAMMAR

SPBINARYGRAMMAR contains the grammar size information. A binary grammar is the resulting data after calling ISpGrammarBuilder::Commit().

typedef struct SPBINARYGRAMMAR
{
    ULONG     ulTotalSerializedSize;
} SPBINARYGRAMMAR;

Members

ulTotalSerializedSize
Total size, in bytes, of the serialized grammar.


SPEVENT (Microsoft Speech Platform)

 Microsoft Speech Platform

SPEVENT

SPEVENT contains information about an event. Events are passed from the TTS or SR engines or audio devices back to applications.

typedef struct SPEVENT
{
    WORD         eEventId;
    WORD         elParamType;
    ULONG        ulStreamNum;
    ULONGLONG    ullAudioStreamOffset;
    WPARAM       wParam;
    LPARAM       lParam;
} SPEVENT;

Members

eEventId
The event ID of type SPEVENTENUM.
elParamType
The signature of the associated data in the lParam parameter
The user may need to release associated data after using the event. See SPEVENTLPARAMTYPE for more information about associated data.
ulStreamNum
The stream number associated with the event.
For text-to-speech (i.e., output streams), the stream number is incremented each time a new speak call (e.g. ISpVoice::SpeakStream, ISpVoice::Speak) is made.
For speech recognition (i.e., input streams), the stream is incremented each time an audio stream is opened. Note that a single audio input object can be opened multiple times (e.g., buffer overflow, device error, recognition state change).
ullAudioStreamOffset
The byte offset into the audio stream associated with the event at which the event was fired. For synthesis, the output stream is the synthesized data. For recognition, this indicates the position in the input audio stream.
wParam
The generic word field. For event IDs with the SPFEI_LPARAM_IS_POINTER set, this is the size, in bytes, for the data pointed to by lParam. In some cases, the type of event will change the function of this parameter. See SPEVENTENUM for information about specific events.
See the helper SpClearEvent for more information about releasing objects or memory attached to an event.
lParam
The generic event field. For event IDs with the SPFEI_LPARAM_IS_POINTER set, this points to the data allocated by CoTaskMemAlloc. The caller is responsible for freeing this memory using CoTaskMemFree(). In some cases, the type of event will change the function of this parameter. See SPEVENTENUM for information about specific events.
See the helper SpClearEvent for more information about releasing objects or memory attached to an event.


SPEVENTEX (Microsoft Speech Platform)

 Microsoft Speech Platform

SPEVENTEX

New in SAPI 5.3

SPEVENTEX contains information about an event and extends the SPEVENT structure. Events are passed from the TTS or SR engines or audio devices back to applications.

SPEVENTEX is the same as SPEVENT, with the addition of a field that contains time offset in the audio stream. This is an important additional piece of information because the stream offset itself is not sufficient to calculate the time offset. This is because the stream encoding may be unknown or may have a time-to-data relationship that is non-deterministic (for example, the compressed cepstral format, which is highly lossy).

typedef struct SPEVENTEX
{
    WORD         eEventId;
    WORD         elParamType;
    ULONG        ulStreamNum;
    ULONGLONG    ullAudioStreamOffset;
    WPARAM       wParam;
    LPARAM       lParam;
    ULONGLONG    ullAudioTimeOffset;
} SPEVENTEX;

Members

eEventId
The event ID of type SPEVENTENUM.
elParamType
The signature of the associated data in the lParam parameter
The user may need to release associated data after using the event. See SPEVENTLPARAMTYPE for more information about associated data.
ulStreamNum
The stream number associated with the event.
For text-to-speech (i.e., output streams), the stream number is incremented each time a new speak call (e.g. ISpVoice::SpeakStream, ISpVoice::Speak) is made.
For speech recognition (i.e., input streams), the stream is incremented each time an audio stream is opened. Note that a single audio input object can be opened multiple times (e.g., buffer overflow, device error, recognition state change).
ullAudioStreamOffset
The byte offset into the audio stream associated with the event at which the event was fired. For synthesis, the output stream is the synthesized data. For recognition, this indicates the position in the input audio stream.
wParam
The generic word field. For event IDs with the SPFEI_LPARAM_IS_POINTER set, this is the size, in bytes, for the data pointed to by lParam. In some cases, the type of event will change the function of this parameter. See SPEVENTENUM for information about specific events.
See the helper SpClearEvent for more information about releasing objects or memory attached to an event.
lParam
The generic event field. For event IDs with the SPFEI_LPARAM_IS_POINTER set, this points to the data allocated by CoTaskMemAlloc. The caller is responsible for freeing this memory using CoTaskMemFree(). In some cases, the type of event will change the function of this parameter. See SPEVENTENUM for information about specific events.
See the helper SpClearEvent for more information about releasing objects or memory attached to an event.
ullAudioTimeOffset
The time since the beginning of the audio stream, at which this event occurred.


SPEVENTSOURCEINFO (Microsoft Speech Platform)

 Microsoft Speech Platform

SPEVENTSOURCEINFO

SPEVENTSOURCEINFO is used by ISpEventSource::GetInfo to pass back information about the event source.

Event sources contain a queue, which hold events until a caller retrieves the events using ::GetEvents.

typedef struct SPEVENTSOURCEINFO
{
    ULONGLONG   ullEventInterest;
    ULONGLONG   ullQueuedInterest;
    ULONG       ulCount;
} SPEVENTSOURCEINFO;

Members

ullEventInterest
Set of event Id flags of type SPEVENTENUM defining which events should trigger a notification (e.g. callback, signaled event, window message, etc.).
ullQueuedInterest
Set of event Id flags of type SPEVENTENUM defining which events should be stored in the source's event queue until the caller uses ISpEventSource::GetEvents to remove them.
ulCount
Number of events currently waiting in the event queue.

Remarks

Note that event interest (ullEventInterest) only specifies which events should cause a notification. The queued interest (ullQueuedInterest) specifies which events should be stored in the event queue.

For example, due to graphics performance issues, it might not be optimal for an application to redraw every viseme that occurs. Instead, it would draw the current viseme whenever a viseme event occurs. Instead of storing viseme events in the event queue, the application would set only the event interest to include SPEI_VISEME and not the queued interest. Whenever the TTS engine fires a viseme event, the application would receive a notification, and would then check the current viseme by calling ISpVoice::GetStatus to check the VisemeId.

The queued interest (ullQueuedInterest) always includes the event interest (ullEventInterest) to ensure that a notification is sent whenever an event is queued.

See Also

Helper macro SPFEI for combining SPEVENTENUM flags.


SPNORMALIZATIONLIST (Microsoft Speech Platform)

 Microsoft Speech Platform

SPNORMALIZATIONLIST

New in SAPI 5.3

Contains a list of alternative form normalizations for a word. It is used as a parameter for the ISpEnginePronunciation::Normalize function.

typedef struct SPNORMALIZATIONLIST
{
    ULONG      ulSize;
    WCHAR    **ppszzNormalizedList;
} SPNORMALIZATIONLIST;

Members

ulSize
The size of the structure, in bytes.
ppszzNormalizedList
Contains the list of alternative normalization forms. The application must allocate the SPNORMALIZATIONLIST structure.


SPPHRASE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPPHRASE

SPPHRASE contains information about speech recognition information, including hypotheses, false recognitions, recognitions, and alternate recognitions.

The information in the phrase includes, language, audio and event timing, text (display and lexicon), inverse text replacements, semantic tags (i.e., properties), and depending on the engine, an optional block of engine-specific phrase data.

SAPI typically provides the application with a pointer to a block of memory that has been allocated by CoTaskMemAlloc, which the application must free using CoTaskMemFree when it is finished with the phrase information.

typedef struct SPPHRASE
{
    ULONG                       cbSize;
    LANGID                      LangID;
    WORD                        wReserved;
    ULONGLONG                   ullGrammarID;
    ULONGLONG                   ftStartTime;
    ULONGLONG                   ullAudioStreamPosition;
    ULONG                       ulAudioSizeBytes;
    ULONG                       ulRetainedSizeBytes;
    ULONG                       ulAudioSizeTime;
    SPPHRASERULE                Rule;
    const SPPHRASEPROPERTY     *pProperties;
    const SPPHRASEELEMENT      *pElements;
    ULONG                       cReplacements;
    const SPPHRASEREPLACEMENT  *pReplacements;
    GUID                        SREngineID;
    ULONG                       ulSREnginePrivateDataSize;
    const BYTE                 *pSREnginePrivateData;
    LPWSTR                      pSML;
    SPSEMANTICERRORINFO        *pSemanticErrorInfo;
    SPSEMANTICFORMAT 	        SemanticTagFormat;
} SPPHRASE;

Members

cbSize
The size of this structure in bytes.
LangID
The language ID of the phrase elements.
wReserved
Reserved for future use.
ullGrammarID
ID of the grammar that contains the top-level rule used to recognize this phrase.
ftStartTime
Absolute time for start of phrase audio as a 64-bit value based on the Win32 APIs, SystemTimeToFileTime and GetSystemTime. When an application uses wav file input, SAPI sets the stream position and start time information to zero.
ullAudioStreamPosition
The starting offset of the phrase in bytes relative to the start of the audio stream. If downsampling an audio stream, ullAudioStreamPosition will be the byte position within the original stream.
ulAudioSizeBytes
Size of audio data, in bytes, for this phrase.
ulRetainedSizeBytes
Size, in bytes, of the retained audio data (in the user-specified retained-audio format).
See also ISpRecoContext::SetAudioOptions for more information about specifying the retained audio format
ulAudioSizeTime
Length of phrase audio in 100-nanosecond units.
Rule

Information about the top-level rule (and rule-reference hierarchy) used to recognize this phrase.

pProperties
Pointer to the root of the semantic-tag property tree.
pElements
Pointer to the array of phrase elements (the number of elements is contained in Rule). Each phrase element includes position and text information, including lexical and display forms.
cReplacements
Number of text replacements. Text replacements are generally based on engine-defined Inverse Text Normalization rules (e.g. recognize "five dollars" as "$5").
pReplacements
Pointer to the array of text replacements.
SREngineID

GUID that identifies the particular speech recognition (SR) engine that recognized this phrase.

ulSREnginePrivateDataSize
Size of the engine's private data, in bytes.
pSREnginePrivateData
Pointer to the engine's private data.
Engine private data is specific to each SR engine, and the format and structure of the data is not defined by SAPI.
pSML
Pointer to the SML (the XML containing the reco result).
pSemanticErrorInfo
Points to a structure containing the error information if an error occurred while generating the SML.
SemanticTagFormat
Specifies the value of the tag-format attribute in a grammar. For more information, see SPSEMANTICFORMAT. This member is defined only for Microsoft Speech Platform and later.


SPPHRASEELEMENT (Microsoft Speech Platform)

 Microsoft Speech Platform

SPPHRASEELEMENT

SPPHRASEELEMENT contains the information for a spoken word.

typedef struct SPPHRASEELEMENT
{
    ULONG             ulAudioTimeOffset;
    ULONG             ulAudioSizeTime;
    ULONG             ulAudioStreamOffset;
    ULONG             ulAudioSizeBytes;
    ULONG             ulRetainedStreamOffset;
    ULONG             ulRetainedSizeBytes;
    LPCWSTR          *pszDisplayText;
    LPCWSTR          *pszLexicalForm;
    const SPPHONEID  *pszPronunciation;
    BYTE              bDisplayAttributes;
    char              RequiredConfidence;
    char              ActualConfidence;
    BYTE              Reserved;
    float             SREngineConfidence;
} SPPHRASEELEMENT;

Members

ulAudioTimeOffset
This is the starting offset of the element in 100-nanosecond units of time relative to the start of the phrase.
ulAudioSizeTime
This is the length of the element in 100-nanosecond units of time.
ulAudioStreamOffset
This is the starting offset of the element in bytes relative to the start of the phrase in the original input stream.
ulAudioSizeBytes
This is the size of the element in bytes in the original input stream.
ulRetainedStreamOffset
This is the starting offset of the element in bytes relative to the start of the phrase in the retained audio stream
ulRetainedSizeBytes
This is the size of the element in bytes in the retained audio stream.
pszDisplayText
The display text for this element (e.g., ",").
pszLexicalForm
The lexical form of this element (e.g., "comma" for ",").
pszPronunciation
The pronunciation for this element as a null-terminated array of SPPHONEID.
bDisplayAttributes
A bit field of SPDISPLAYATTRIBUTES defining extra display information which the application should honor when displaying this word.
RequiredConfidence
The required confidence for this element (either SP_LOW_CONFIDENCE, SP_NORMAL_CONFIDENCE, or SP_HIGH_CONFIDENCE). If a word is prefixed with a '-' (minus), the RequiredConfidence is SP_LOW_CONFIDENCE, and '+' (plus) will set this field to SP_HIGH_CONFIDENCE (e.g., "This -is -a +test").
ActualConfidence
The actual confidence for this element (either SP_LOW_CONFIDENCE, SP_NORMAL_CONFIDENCE, or SP_HIGH_CONFIDENCE). This is always at least the RequiredConfidence.
Reserved
Reserved for future use.
SREngineConfidence
The confidence score computed by the SR engine. The value range is engine dependent. It can be used to optimize an application's performance with a specific engine. Using this value will improve the application with a particular speech engine but more than likely will make it worse with other engines and should be used with care. This value is more useful with speaker-independent engines because it allows a large corpus of recorded usage to correctly optimize the overall accuracy of the application.


SPPHRASEPROPERTY (Microsoft Speech Platform)

 Microsoft Speech Platform

SPPHRASEPROPERTY

SPPHRASEPROPERTY stores the information for one semantic property. It can be used to construct a semantic property tree.

See also Designing Grammar Rules for more information about semantic properties.

typedef [restricted, hidden] struct SPPHRASEPROPERTY SPPHRASEPROPERTY;

// For SRGS grammars, this enum indicates how to use the union.
typedef [hidden] enum SPPHRASEPROPERTYUNIONTYPE
{
  SPPPUT_UNUSED = 0,
  SPPPUT_ARRAY_INDEX         // The union contains usArrayIndex.
} SPPHRASEPROPERTYUNIONTYPE

struct SPPHRASEPROPERTY
{
    LPCWSTR                    *pszName;
    ULONG                       ulId;
      union
      {
        ULONG                   ulId;; // For SAPI grammars, indicates the property ID, if specified.
          struct
          {
            byte                bType;
            byte                bReserved;
            unsigned short      usArrayIndex;
          };
      };
    LPCWSTR                    *pszValue;
    VARIANT                     vValue;
    ULONG                       ulFirstElement;
    ULONG                       ulCountOfElements;
    const  SPPHRASEPROPERTY    *pNextSibling;
    const  SPPHRASEPROPERTY    *pFirstChild;
    float                       SREngineConfidence;
    signed char                 Confidence;
};

Members

pszName
Name of the null-terminated string of the semantic property (in the Speech Text Grammar Format set using the PROPNAME attribute).
ulId
The identifier of the semantic property (in the Speech Text Grammar Format set using the PROPID attribute).
bType
SPPHRASEPROPERTYUNIONTYPE indicating how to use the union.
bReserved
Reserved.
usArrayIndex
For W3C grammars, indicates the array index, if this is an array element. Array elements have the name "item".
pszValue
Null-terminated string value of the semantic property (in the Speech Text Grammar Format set using the VALSTR attribute).
vValue
VARIANT value of a semantic property. The type has to be on of the following: VT_BOOL, VT_I4, VT_R4, VT_R8, or VT_BYREF (only for dynamic grammars). This is set using the VAL attribute in the Speech Text Grammar Format.
ulFirstElement
The first spoken element spanned by this property.
ulCountOfElements
The number of spoken elements spanned by this property.
pNextSibling
Pointer to next sibling in property tree.
pFirstChild
Pointer to the first child of this semantic property.
SREngineConfidence
Confidence value for this semantic property computed by the SR engine. The value range is specific to each SR engine.
Confidence
Confidence value for this semantic property computed by SAPI. The value is either SP_LOW_CONFIDENCE, SP_NORMAL_CONFIDENCE, or SP_HIGH_CONFIDENCE.


SPPHRASEREPLACEMENT (Microsoft Speech Platform)

 Microsoft Speech Platform

SPPHRASEREPLACEMENT

SPPHRASEREPLACEMENT replaces the display text of one or more of the spoken words. This is used by speech recognition engines to perform Inverse Text Normalization (ITN). For example the spoken words "twenty" and "three" are replaced by the replacement text "23."

typedef struct tagSPPHRASEREPLACEMENT
{
    BYTE             bDisplayAttributes;
    LPCWSTR         *pszReplacementText;
    ULONG            ulFirstElement;
    ULONG            ulCountOfElements;
} SPPHRASEREPLACEMENT;

Members

bDisplayAttributes
One or more SPDISPLAYATTRIBUTES for the replacement text.
pszReplacementText
Text for the replacement.
ulFirstElement
Offset of the first spoken element to be replaced.
ulCountOfElements
Number of spoken elements to replace.


SPPHRASERULE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPPHRASERULE

SPPHRASERULE contains the information for a rule in a grammar result. SAPI uses the pFirstChild and pNextSibling pointers to represent the parse tree. SPPHRASE.Rule is the root node of the parse tree.

struct tagSPPHRASERULE
{
    LPCWSTR                 *pszName;
    ULONG                   ulId;
    ULONG                   ulFirstElement;
    ULONG                   ulCountOfElements;
    const  SPPHRASERULE    *pNextSibling;
    const  SPPHRASERULE    *pFirstChild;
    float                   SREngineConfidence;
    signed char             Confidence;
 };

Members

pszName
Name of this rule (in Speech Text Grammar Format set using <RULE NAME="MyName">).
ulId
ID of this rule (set using <RULE ID="123">).
ulFirstElement
The index of the first spoken element (word) of this rule.
ulCountOfElements
Number of spoken elements (words) spanned by this rule.
pNextSibling
Pointer to the next sibling in the parse tree.
pFirstChild
Pointer to the first child node in the parse tree.
SREngineConfidence
Confidence for this rule computed by the SR engine. The value is engine dependent and not standardized across multiple SR engines.
Confidence
Confidence for this rule computed by SAPI. The value is either SP_LOW_CONFIDENCE, SP_NORMAL_CONFIDENCE, or SP_HIGH_CONFIDENCE.

Remarks

It is sometimes possible for ulFirstElement to have a value that is larger than the largest possible index for a recognized phrase. This can happen when a rule that can match zero elements is triggered at the end of a phrase. The following example shows a situation for which ulFirstElement can have a value that is out of range for the phrase.

The SRGS rule definitions that follow can match two input phrases: "one large drink" and "one large drink please". If a user speaks the phrase "one large drink", the value of ulCountOfElements for rule1 is 3, the number of words in the phrase. In contrast, the value of ulCountOfElements for rule2 is 0, because this rule matched no words in the input phrase, and the value of ulFirstElement for rule2 is 3, the index that is one higher than that of the last word in the input phrase. For a phrase with three words, the valid indexes are 0, 1, and 2.

<rule id="top" scope="public">
  <ruleref uri ="#rule1">
  <ruleref uri ="#rule2">
</rule>

<rule id="rule1" scope="private">
  <item>one large drink</item>
</rule>

<rule id="rule2" scope="private">
  <item repeat="0-" repeat-prob="0.1">please</item>
</rule>


SPPROPERTYINFO (Microsoft Speech Platform)

 Microsoft Speech Platform

SPPROPERTYINFO

SPPROPERTYINFO contains the information for a semantic property.

typedef struct tagSPPROPERTYINFO
{
    LPCWSTR          *pszName;
    ULONG             ulId;
    LPCWSTR          *pszValue;
    VARIANT           vValue;
} SPPROPERTYINFO;

Members

pszName
Pointer to the null-terminated string that contains the name information of the property. This is set using the PROPNAME attribute in the Speech Text Grammar Format.
ulId
Identifier associated with the property. This is set using the PROPID attribute in the Speech Text Grammar Format.
pszValue
Pointer to the null-terminated string that contains the value information of the property. This is set using the VALSTR attribute in the Speech Text Grammar Format.
vValue
Must be one of the following: VT_BOOL, VT_I4, VT_R4, VT_R8, or VT_BYREF (for dynamic grammars only.) This is set using the VAL attribute in the Speech Text Grammar Format.


SPRECOCONTEXTSTATUS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPRECOCONTEXTSTATUS

typedef struct SPRECOCONTEXTSTATUS
{
    SPINTERFERENCE  eInterference;
    WCHAR           szRequestTypeOfUI[255];
    DWORD           dwReserved1;
    DWORD           dwReserved2;
} SPRECOCONTEXTSTATUS;

Members

eInterference
One of the interference types contained in the SPINTERFERENCE enumeration. An application can check this value for the input audio signal quality.
szRequestTypeOfUI[255]
Specifies the type of UI requested. If the first byte is NULL, no UI is requested. See ISpRecognizer::DisplayUI and SPDUI_* for a list of the SAPI-defined UI types.
dwReserved1
Reserved for future expansion.
dwReserved2
Reserved for future expansion.


SPRECOGNIZERSTATUS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPRECOGNIZERSTATUS

SPRECOGNIZERSTATUS is used to report static information about the recognizer, such as supported languages, and dynamic information about the position in the stream to which the recognizer has recognized.

typedef struct SPRECOGNIZERSTATUS
{
    SPAUDIOSTATUS   AudioStatus;
    ULONGLONG       ullRecognitionStreamPos;
    ULONG           ulStreamNumber;
    ULONG           ulNumActive;
    CLSID           clsidEngine;
    ULONG           cLangIDs;
    LANGID          aLangID[SP_MAX_LANGIDS];
    ULONGLONG       ullRecognitionStreamTime;
} SPRECOGNIZERSTATUS;

Members

AudioStatus
The SPAUDIOSTATUS structure containing the current audio device information.
ullRecognitionStreamPos
The current stream position the engine has recognized to. Stream positions are measured in bytes. This value can be used to check the engine's progress using the audio data.
ulStreamNumber
This value is incremented every time SAPI starts or stops recognition on an engine (see SPEI_START_SR_STREAM and SPEI_END_SR_STREAM). Each time this happens the ullRecognitionStreamPos gets reset to zero. Events fired from the engine have equivalent stream number and position information also.
ulNumActive
The current engine's number of active rules.
clsidEngine
The unique identifier associated with the current engine.
cLangIDs
The number of languages that the current engine supports.
aLangID
Array containing the languages that the current engine supports.
ullRecognitionStreamTime
Returns the current position of the recognizer in the stream in 100 nanosecond units.


SPRECORESULTTIMES (Microsoft Speech Platform)

 Microsoft Speech Platform

SPRECORESULTTIMES

SPRECORESULTTIMES contains the time information for speech recognition. This data structure is used by the ISpRecoResult::GetResultTimes method.

typedef struct SPRECORESULTTIMES
{
    FILETIME    ftStreamTime;
    ULONGLONG   ullLength;
    DWORD       dwTickCount;
    ULONGLONG   ullStart;
} SPRECORESULTTIMES;

Members

ftStreamTime
Absolute time for start of phrase audio as a 64-bit value based on the Win32 APIs, SystemTimeToFileTime and GetSystemTime. When an application uses wav file input, SAPI sets the stream position and start time information to zero.
ullLength
Value containing the length of the phrase specified in 100 nanosecond units.
dwTickCount
Number of milliseconds elapsed from the start of the system to the start of the current result. This variable is set to zero if the wave file input is used.
ullStart
Value containing the total 100 nanosecond units from the start of the stream to the start of the phrase.


SPRULE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPRULE

New in SAPI 5.3

Represents a rule in a collection of run-time grammar rules.

SPRULE is used when fetching all of the rules in a run-time grammar using the ISpRecoGrammar2::GetRules function.

typedef struct SPRULE
{
    LPCWSTR    pszRuleName;
    ULONG      ulRuleId;
    DWORD      dwAttributes;
} SPRULE;

Members

pszRuleName
The name of the rule. This may be an empty string.
ulRuleId
The ID of the rule. This is unique within a grammar.
dwAttributes
A bit field describing the characteristics of the rule. The enum SPCFGRULEATTRIBUTES defines the bit values.


SPSEMANTICERRORINFO (Microsoft Speech Platform)

 Microsoft Speech Platform

SPSEMANTICERRORINFO

New in SAPI 5.3

Represents information about a recognition error.

SPSEMANTICERRORINFO is used with functions of the ISpXMLRecoResult and ISpPhrase2 interfaces to describe errors that occurred while generating semantic results (SML).

typedef struct SPSEMANTICERRORINFO
{
    ULONG      ulLineNumber;
    LPWSTR     pszScriptLine;
    LPWSTR     pszSource;
    LPWSTR     pszDescription;
    HRESULT    hrResultCode;
} SPSEMANTICERRORINFO;

Members

ulLineNumber
The line number where the error occurred.
pszScriptLine
The text of the line where the error occurred.
pszSource
The location of the file in which the error occurred.
pszDescription
A description of the error.
hrResultCode
The code number of the error.


SPSERIALIZEDEVENT (Microsoft Speech Platform)

 Microsoft Speech Platform

SPSERIALIZEDEVENT

SPSERIALIZEDEVENT serializes a SAPI event.

See SPSERIALIZEDEVENT64 for a 64-bit version of the serialized event structure.

See also SPEVENT for further information on the related event variable fields.

typedef struct SPSERIALIZEDEVENT
{
    WORD        eEventId;
    WORD        elParamType;
    ULONG       ulStreamNum;
    ULONGLONG   ullAudioStreamOffset;
    ULONG       SerializedwParam;
    LONG        SerializedlParam;
} SPSERIALIZEDEVENT;

Members

eEventId
The event ID of type SPEVENTENUM.
elParamType
The signature of the lParam parameter of type SPEVENTLPARAMTYPE.
ulStreamNum
The stream number associated with the event.
For text-to-speech (i.e., output streams), the stream number is incremented each time a new speak call (e.g., ISpVoice::SpeakStream, ISpVoice::Speak) is made.
For speech recognition (i.e., input streams), the stream is incremented each time an audio stream is opened. Note that a single audio input object can be opened multiple times (e.g., buffer overflow, device error, recognition state change).
ullAudioStreamOffset
The byte offset into the audio stream associated with the event at which the event was fired. For synthesis, the output stream is the synthesized data. For recognition, this indicates the position in the input audio stream.
SerializedwParam
The wParam value that was included in the event. See SPEVENTENUM for further information on possible wParam values.
SerializedlParam
The lParam value that was included in the event. See SPEVENTENUM for further information on possible lParam values.


SPSERIALIZEDEVENT64 (Microsoft Speech Platform)

 Microsoft Speech Platform

SPSERIALIZEDEVENT64

SPSERIALIZEDEVENT64 serializes a SAPI event.

typedef struct SPSERIALIZEDEVENT64
{
    WORD            eEventId;
    WORD            elParamType;
    ULONG           ulStreamNum;
    ULONGLONG       ullAudioStreamOffset;
    ULONGLONG       SerializedwParam;
    LONGLONG        SerializedlParam;
} SPSERIALIZEDEVENT64;

Members

eEventId
The event ID of type SPEVENTENUM.
elParamType
The signature of the lParam parameter of type SPEVENTLPARAMTYPE.
ulStreamNum
The stream number associated with the event.
For text-to-speech (i.e., output streams), the stream number is incremented each time a new speak call (e.g., ISpVoice::SpeakStream, ISpVoice::Speak) is made.
For speech recognition (i.e., input streams), the stream is incremented each time an audio stream is opened. Note that a single audio input object can be opened multiple times (e.g., buffer overflow, device error, recognition state change).
ullAudioStreamOffset
The byte offset into the audio stream associated with the event at which the event was fired. For synthesis, the output stream is the synthesized data. For recognition, this indicates the position in the input audio stream.
SerializedwParam
The wParam value that was included in the event. The variable uses a 64-bit data type for large addresses and values. See SPEVENTENUM for further information on possible wParam values.
SerializedlParam
The lParam value that was included in the event. The variable uses a 64-bit data type for large addresses and values. See SPEVENTENUM for further information on possible lParam values.

Remarks

The 64 label signifies the use of 64-bit values for the wParam and lParam variables. Normally applications will not need to use 64-bit values, unless large pointers or sizes were stored in the original event structure. See also SPSERIALIZEDEVENT for the non-64-bit version.

See also SPEVENT for further information on the related event variable fields.


SPSERIALIZEDPHRASE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPSERIALIZEDPHRASE

typedef struct tagSPSERIALIZEDPHRASE
{
    ULONG      ulSerializedSize;
} SPSERIALIZEDPHRASE;

Members

ulSerializedSize
Value specifying the size of the serialized phrase in bytes.


SPTEXTSELECTIONINFO (Microsoft Speech Platform)

 Microsoft Speech Platform

SPTEXTSELECTIONINFO

SPTEXTSELECTIONINFO combines test selection information that the SR engine can use to improve the recognition accuracy (using ISpRecoGrammar::SetWordSequenceData() and ISpRecoGrammar::SetTextSelection()).

typedef struct tagSPTEXTSELECTIONINFO
{
    ULONG       ulStartActiveOffset;
    ULONG       cchActiveChars;
    ULONG       ulStartSelection;
    ULONG       cchSelection;
} SPTEXTSELECTIONINFO;

Members

ulStartActiveOffset
Count of characters from the start of the WordSequenceData buffer. The word containing the character pointed to is the first word of the active text selection buffer.
cchActiveChars
Count of characters for the active range of the text selection buffer.
ulStartSelection
Start of the selected text (e.g., the user is selecting part of the previously dictated text that he/she is going to edit or correct).
cchSelection
Count of characters of the user selection.


SPSERIALIZEDRESULT (Microsoft Speech Platform)

 Microsoft Speech Platform

SPSERIALIZEDRESULT

SPSERIALIZEDRESULT contains the phrase size information.

typedef struct SPSERIALIZEDRESULT
{
    ULONG    ulSerializedSize;
} SPSERIALIZEDRESULT;

Members

ulSerializedSize
The size of the entire phrase in bytes, including this ULONG.


SPSHORTCUTPAIR (Microsoft Speech Platform)

 Microsoft Speech Platform

SPSHORTCUTPAIR

New in SAPI 5.3

Describes the pairing of a spoken shortcut phrase with the corresponding text or a node in a linked list of shortcut pairs.

typedef struct SPSHORTCUTPAIR
{
    SPSHORTCUTPAIR     *pNextSHORTCUTPAIR;
    LANGID             *LangID;
    SPSHORTCUTTYPE      shType;
    LPWSTR              pszDisplay;
    LPWSTR              pszSpoken;
} SPSHORTCUTPAIR;

Members

pNextSHORTCUTPAIR
Pointer to the next pair in the linked list or, if it is the end of the list, NULL.
LangID
The language ID of the pair or 0 (meaning default).
shType
The type of shortcut.
pszDisplay
The text to be displayed when the shortcut is spoken.
pszSpoken
The text the recognizer should listen for.


SPSHORTCUTPAIRLIST (Microsoft Speech Platform)

 Microsoft Speech Platform

SPSHORTCUTPAIRLIST

New in SAPI 5.3

Contains the shortcut pair linked list.

typedef struct SPSHORTCUTPAIRLIST
{
    ULONG              ulSize;
    BYTE              *pvBuffer;
    SPSHORTCUTPAIR    *pFirstShortcutPair;
} SPSHORTCUTPAIRLIST;

Members

ulSize
The size of the memory block pointed to by pvBuffer.
pvBuffer
Pointer to the memory block containing the entire list of shortcut pairs. Although this is a linked list, it is packed into one memory allocation to make it easy to free memory.
pFirstShortcutPair
Pointer to the first pair in the list.


SPVCONTEXT (Microsoft Speech Platform)

 Microsoft Speech Platform

SPVCONTEXT

SPVCONTEXT contains strings passed into an ISpVoice::Speak call using a <Context> XML tag.

typedef struct SPVCONTEXT
{
    LPCWSTR   pCategory;
    LPCWSTR   pBefore;
    LPCWSTR   pAfter;
} SPVCONTEXT;

Members

pCategory
String passed in with the ID attribute.
pBefore
String passed in with the Before attribute.
pAfter
String passed in with the After attribute.


SPVOICESTATUS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPVOICESTATUS

SPVOICESTATUS contains voice status information. This structure is returned by ISpVoice::GetStatus.

typedef struct SPVOICESTATUS
{
    ULONG       ulCurrentStream;
    ULONG       ulLastStreamQueued;
    HRESULT     hrLastResult;
    DWORD       dwRunningState;
    ULONG       ulInputWordPos;
    ULONG       ulInputWordLen;
    ULONG       ulInputSentPos;
    ULONG       ulInputSentLen;
    LONG        lBookmarkId;
    SPPHONEID   PhonemeId;
    SPVISEMES   VisemeId;
    DWORD       dwReserved1;
    DWORD       dwReserved2;
} SPVOICESTATUS;

Members

ulCurrentStream
The number of the current stream being synthesized or receiving output (see ISpVoice::Speak for more information on stream numbers).
ulLastStreamQueued
The number of the last stream queued.
hrLastResult
Result of the last Speak or Speakstream call.
dwRunningState
Indicates the status of the voice.. That is, whether it is currently speaking, is done with all pending speak requests, or is currently waiting to speak. The possible flag values are contained in the SPRUNSTATE enumeration. A value of zero indicates that the voice is currently waiting to speak.
ulInputWordPos
Character position within the input text of the word currently being processed.
ulInputWordLen
Length of the word currently being processed.
ulInputSentPos
Character position within the input text of the sentence currently being processed.
ulInputSentLen
Length of the sentence currently being processed.
lBookmarkId
Current bookmark string (in base 10) converted to a long integer. If the string of the current bookmark does not begin with an integer, lBookmarkId will be zero. For example, if the bookmark name is "123Bookmark", the lBookmarkId is "123"; and if the bookmark name is "hello", the lBookmarkId is zero.
PhonemeId
Current phoneme ID - see SAPI Phoneme set
VisemeId
Current viseme ID - see SAPI Viseme set
dwReserved1
Reserved for future expansion.
dwReserved2
Reserved for future expansion.


SPVPITCH (Microsoft Speech Platform)

 Microsoft Speech Platform

SPVPITCH

SPVPITCH contains a long value passed into an ISpVoice::Speak call using a <Pitch> XML tag.

typedef struct SPVPITCH
{
    long   MiddleAdj;
    long   RangeAdj;
} SPVPITCH;
MiddleAdj
Value passed in with the Middle or AbsMiddle attributes. Supported values are -10 to 10 with a value of zero being the default pitch. Values outside of this range may be truncated.
RangeAdj
Reserved for future use.


SPVSTATE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPVSTATE

SPVSTATE contains information about the XML state associated with a text string.

typedef struct SPVSTATE
{
    //--- Action
    SPVACTIONS      eAction;
    //--- Running state values
    LANGID          LangID;
    WORD            wReserved;
    long            EmphAdj;
    long            RateAdj;
    ULONG           Volume;
    SPVPITCH        PitchAdj;
    ULONG           SilenceMSecs;
    SPPHONEID*      pPhoneIds;
    SPPARTOFSPEECH  ePartOfSpeech;
    SPVCONTEXT      Context;
} SPVSTATE;

Members

eAction
Describes the action to be performed with the associated text fragment. The normal action is to Speak (SPVA_Speak) the fragment.
LangID
The language ID associated with this text. Set using the <Lang> XML tag.
wReserved
Reserved for future use.
EmphAdj
Specifies whether the text should be emphasized - zero indicates no emphasis, one indicates emphasis. Set using the <Emph> XML tag.
RateAdj
The rate associated with this text. Set using the <Rate> XML tag. This value should be combined with the baseline rate (either the default, or a value set by ISpVoice::SetRate) to yield the final rate value.
Volume
The volume associated with this text. Set using the <Volume> XML tag. This value should be combined with the baseline volume (either the default, or a value set by ISpVoice::SetVolume) to yield the final volume value.
PitchAdj
The pitch associated with this text. Set using the <Pitch> XML tag.
SilenceMSecs
The length of a silence, in milliseconds, to be inserted into the audio output. SilenceMSecs is always zero unless eAction is SPVA_Silence. Set using the <Silence> XML tag.
pPhoneIds
A pronunciation (possibly associated with text) to be inserted into the audio output. This value is a pointer to a null-terminated array of SPPHONEIDs. Set using the <Pron> XML tag.
ePartOfSpeech
An SPPARTOFSPEECH value to be associated with this text. Set using the <PartOfSp> XML tag.
Context
An SPVCONTEXT to be associated with this text. Set using the <Context> XML tag.


SPWORD (Microsoft Speech Platform)

 Microsoft Speech Platform

SPWORD

SPWORD defines changes to the words in a lexicon and is used with IspLexicon. It is used in connection with SPWORDLIST which in turn is used by ISpLexicon::GetWords and ISpLexicon::GetGenerationChange.

typedef struct SPWORD
{
    struct SPWORD          *pNextWord;
    LANGID                  LangID;
    WORD                    wReserved;
    SPWORDTYPE              eWordType;
    LPWSTR                 *pszWord;
    SPWORDPRONUNCIATION    *pFirstWordPronunciation;
} SPWORD;

Members

pNextWord
Pointer to the next word in the list.
LangID
The language ID of the word.
wReserved
Reserved for future use.
eWordType
Flag of type SPWORDTYPE indicating whether the word has been added or deleted.
pszWord
Pointer to the null-terminated word.
pFirstWordPronunciation
Pointer to the first possible pronunciation of the word.


SPWORDLIST (Microsoft Speech Platform)

 Microsoft Speech Platform

SPWORDLIST

SPWORDLIST receives words currently in the lexicon or that have changed since the last time an engine was checked. It is used in conjunction with ISpLexicon.

typedef struct SPWORDLIST
{
    ULONG      ulSize;
    BYTE      *pvBuffer;
    SPWORD    *pFirstWord;
} SPWORDLIST;

Members

ulSize
The size of the buffer for all of the words, in bytes.
pvBuffer
Pointer to the buffer for all word information or changes.
pFirstWord
Pointer to the first word in the list.

Remarks

This structure is the beginning of a linked list of SPWORD structures and contains the size and actual buffer of all subsequent word operations. It is used with ISpLexicon::GetWords and ISpLexicon::GetGenerationChange.

Call ZeroMemory before using SPWORDLIST to initialize it, and call CoTaskMemFree(spWordList.pvBuffer) to free the buffer allocated during the calls. The pvBuffer need not (and should not) be freed between the calls. ISpLexicon::GetWords and ISpLexicon::GetGenerationChange will reuse the buffer for efficiency and reallocate when necessary.

Examples

The following example is a code fragment demonstrating the use and creation of SPWORDLIST. The code initializes the structure prior to use. Note that the returned SPWORDLIST has a CoTaskMemAllocate buffer attached to it. This should be freed after all operations using the list. If not all words are returned from ISpLexicon::GetWords, the structure should not be wiped and can be passed into subsequent calls to efficiently reuse the allocated memory block.

SPWORDLIST SPWordList;
hr = ZeroMemory(&SPWordList, sizeof(SPWordList));
// Check return value here. Handle error.
hr = S_FALSE;
while (hr == S_FALSE)
{
   hr = pLex->GetWords(eLEXTYPE_USER, &dwGen, &dwCookie, &SPWordList);
   // Do something with the received words.
   // S_FALSE is returned if there are still words remaining to be got and the cookie is updated.
}
// Have finished with the list. Free the enclosed buffer.
::CoTaskMemFree(SPWordList.pvBuffer);

The following helper class will ensure the correct usage of SPWORDLIST.

class CSpWordList : public SPWORDLIST
{
public:
    CSpWordList()
    {
        ZeroMemory(static_cast<SPWORDLIST*>(this), sizeof(SPWORDLIST));
    }
    ~CSpWordList()
    {
        CoTaskMemFree(pvBuffer);
    }
};

Using the helper class, the above sample becomes:

CSpWordList SPWordList;
hr = S_FALSE;
while (hr == S_FALSE)
{
   hr = pLex->GetWords(eLEXTYPE_USER, &dwGen, &dwCookie, &SPWordList);
   // Do something with the received words.
   // S_FALSE is returned if there are still words remaining to be got and the cookie is updated.
}


SPWORDPRONUNCIATION (Microsoft Speech Platform)

 Microsoft Speech Platform

SPWORDPRONUNCIATION

SPWORDPRONUNCIATION is used by ISpLexicon for words with possible variations in pronunciation. SPWORDPRONUNCIATION contains a single pronunciation for a word.

typedef struct SPWORDPRONUNCIATION
{
    struct SPWORDPRONUNCIATION   *pNextWordPronunciation;
    SPLEXICONTYPE                 eLexiconType;
    LANGID                        LangID;
    WORD                          wPronunciationFlags;
    SPPARTOFSPEECH                ePartOfSpeech;
    SPPHONEID                     szPronunciation[1];
} SPWORDPRONUNCIATION;

Members

pNextWordPronunciation
Pointer to the next possible pronunciation. May be NULL.
eLexiconType
Flag of type SPLEXICONTYPE indicating which lexicon this pronunciation and part of speech was obtained from.
LangID
The language identifier.
wPronunciationFlags
Replaces the previous wReserved field and is a bit field defined by SPPRONUNCIATIONFLAGS.
ePartOfSpeech
The part of speech used by this particular variation.
szPronunciation[1]
This is a null-terminated array of SPPHONID elements defining the pronunciation. It runs off the end of the SPWORDPRONUNCIATION structure and is part of data buffer in the containing SPWORDPRONUNCIATIONLIST structure.


SPWORDPRONUNCIATIONLIST (Microsoft Speech Platform)

 Microsoft Speech Platform

SPWORDPRONUNCIATIONLIST

SPWORDPRONUNCIATIONLIST is used with ISpLexicon::GetPronunciations to list possible variations in pronunciation for a given word.

typedef struct SPWORDPRONUNCIATIONLIST
{
    ULONG                   ulSize;
    BYTE                   *pvBuffer;
    SPWORDPRONUNCIATION    *pFirstWordPronunciation;
} SPWORDPRONUNCIATIONLIST;

Members

ulSize
Size of the pronunciation buffer, in bytes.
pvBuffer
Pointer to the buffer for all pronunciations.
pFirstWordPronunciation
Pointer to the first in a linked list of SPWORDPRONUNCIATION structures within pvBuffer.

Remarks

This structure is the start of a linked list of SPWORDPRONUNCIATION structures and contains the size and actual buffer of all subsequent pronunciations.

Call ZeroMemory before using SPWORDPRONUNCIATIONLIST to initialize it, and call CoTaskMemFree(spwordpronlist.pvBuffer) to free the buffer allocated during the calls. The pvBuffer need not (and should not) be freed between the calls. ISpLexicon::GetPronunciations will reuse the buffer for efficiency and reallocate when necessary.

Example

The following example is a code fragment demonstrating the use and creation of SPWORDPRONUNCIATIONLIST.

    SPWORDPRONUNCIATIONLIST spwordpronlist;
    memset(spwordpronlist, 0, sizeof(spwordpronlist));

    pISpLexicon->GetPronunciations(L"resume", 0, 0, &spwordpronlist);
    for (SPWORDPRONUNCIATION *pwordpron = spwordpronlist.pFirstWordPronunciation;
         wordpron != NULL;
         wordpron = pwordpron->pNextWordPronunciation)
    {
        DoSomethingWith(pwordpron->ePartOfSpeech, pwordpron->szPronunciation);
    }

    pISpLexicon->GetPronunciations(L"record", 0, 0, &spwordpronlist);
    // repeat the for loop above to process the pronunciations

    CoTaskMemFree(spwordpronlist.pvBuffer);

The following helper class will ensure the correct usage of SPWORDPRONUNCIATIONLIST.

class CSpPronList : public SPWORDPRONUNCIATIONLIST
{
public:
    CSpPronList()
    {
        ZeroMemory(static_cast<SPWORDPRONUNCIATIONLIST*>(this), sizeof(SPWORDPRONUNCIATIONLIST));
    }
    ~CSpPronList()
    {
        CoTaskMemFree(pvBuffer);
    }
};

Using the helper class, the above sample becomes:

    CSpPronList spwordpronlist;

    pISpLexicon->GetPronunciations(L"resume", 0, 0, &spwordpronlist);
    for (SPWORDPRONUNCIATION *pwordpron = spwordpronlist.pFirstWordPronunciation;
         wordpron != NULL;
         wordpron = pwordpron->pNextWordPronunciation)
    {
        DoSomethingWith(pwordpron->ePartOfSpeech, pwordpron->szPronunciation);
    }

    pISpLexicon->GetPronunciations(L"record", 0, 0, &spwordpronlist);
    // repeat the for loop above to process the pronunciations


WAVEFORMATEX (Microsoft Speech Platform)

 Microsoft Speech Platform

WAVEFORMATEX

WAVEFORMATEX defines the format of waveform-audio data. Only format information common to all waveform-audio data formats is included in this structure. For formats requiring additional information, this structure is included as the first member in another structure, along with the additional information.

typedef struct WAVEFORMATEX
{
    WORD    wFormatTag;
    WORD    nChannels;
    DWORD   nSamplesPerSec;
    DWORD   nAvgBytesPerSec;
    WORD    nBlockAlign;
    WORD    wBitsPerSample;
    WORD    cbSize;
} WAVEFORMATEX;

Members

wFormatTag
Waveform-audio format type. Format tags are registered with Microsoft Corporation for many compression algorithms. A complete list of format tags is located in the Mmsystem.h header file.
nChannels
Number of channels in the waveform-audio data. Monaural data uses one channel and stereo data uses two channels.
nSamplesPerSec
Sample rate, in samples per second (hertz) at which each channel should be played or recorded. If wFormatTag is WAVE_FORMAT_PCM, common values for nSamplesPerSec are 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.
nAvgBytesPerSec
Required average data-transfer rate, in bytes per second, for the format tag. If wFormatTag is WAVE_FORMAT_PCM, nAvgBytesPerSec should be equal to the product of nSamplesPerSec and nBlockAlign. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

Playback and record software can estimate buffer sizes using the nAvgBytesPerSec member.

nBlockAlign
Block alignment, in bytes. The block alignment is the minimum atomic unit of data for the wFormatTag format type. If wFormatTag is WAVE_FORMAT_PCM, nBlockAlign should be equal to the product of nChannels and wBitsPerSample divided by 8 (bits per byte). For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

Playback and record software must process a multiple of nBlockAlign bytes of data at a time. Data written and read from a device must always start at the beginning of a block. For example, it is illegal to start playback of PCM data in the middle of a sample (that is, on a non-block-aligned boundary).

wBitsPerSample
Bits per sample for the wFormatTag format type. If wFormatTag is WAVE_FORMAT_PCM, wBitsPerSample should be equal to 8 or 16. For non-PCM formats, this member must be set according to the manufacturer's specification of the format tag. Note that some compression schemes cannot define a value for wBitsPerSample, so this member can be zero.
cbSize
Size, in bytes, of extra format information appended to the end of the WAVEFORMATEX structure. This information can be used by non-PCM formats to store extra attributes for the wFormatTag. If no extra information is required by the wFormatTag, this member must be set to zero. For WAVE_FORMAT_PCM formats only, this member is ignored.


Enumerations (Microsoft Speech Platform)

 Microsoft Speech Platform

Enumerations

The following enumerations are used with the Microsoft Speech Platform.

  • DISPID_SpeechXMLRecoResult
  • SPADAPTATIONRELEVANCE
  • SPADAPTATIONSETTINGS
  • SPAUDIOOPTIONS
  • SPAUDIOSTATE
  • SPBOOKMARKOPTIONS
  • SPCATEGORYTYPE
  • SPCOMMITFLAGS
  • SPCONTEXTSTATE
  • SPDATAKEYLOCATION
  • SPDISPLAYATTRIBUTES
  • SPEAKFLAGS
  • SPENDSRSTREAMFLAGS
  • SPEVENTENUM
  • SPEVENTLPARAMTYPE
  • SPFILEMODE
  • SPGRAMBUILDCOMMITFLAGS
  • SPGRAMMAROPTIONS
  • SPGRAMMARSTATE
  • SPGRAMMARWORDTYPE
  • SPINTERFERENCE
  • SPLEXICONTYPE
  • SPLOADOPTIONS
  • SPMATCHINGMODE
  • SPPARTOFSPEECH
  • SPPHRASERNG
  • SPPRONUNCIATIONFLAGS
  • SPRECOEVENTFLAGS
  • SPRECOSTATE
  • SPRULESTATE
  • SPRUNSTATE
  • SPSEMANTICFORMAT
  • SPSHORTCUTTYPE
  • SPSTREAMFORMAT
  • SPVACTIONS
  • SPVALUETYPE
  • SPVFEATURE
  • SPVISEMES
  • SPVLIMITS
  • SPVPRIORITY
  • SPWAVEFORMATTYPE
  • SPWORDPRONOUNCEABLE
  • SPWORDTYPE
  • SPXMLRESULTOPTIONS


DISPID_SpeechXMLRecoResult (Microsoft Speech Platform)

 Microsoft Speech Platform

DISPID_SpeechXMLRecoResult

New in SAPI 5.3

DISPID_SpeechXMLRecoResult enumerates the types of V-Table access to XML results.

typedef enum DISPID_SpeechXMLRecoResult
{
    DISPID_SRRGetXMLResult,
    DISPID_SRRGetXMLErrorInfo
} DISPID_SpeechXMLRecoResult;

Elements

DISPID_SRRGetXMLResult
Allows access to result information in SML (XML) format.
DISPID_SRRGetXMLErrorInfo
Allows access to error information in SML (XML) format.


PHONETICALPHABET (Microsoft Speech Platform)

 Microsoft Speech Platform

PHONETICALPHABET

New in SAPI 5.3

PHONETICALPHABET specifies the types of phonetic alphabet supported by SAPI.

typedef enum PHONETICALPHABET
{
    PA_Ipa,
    PA_Ups,
    PA_Sapi,
} PHONETICALPHABET;

Elements

PA_Ipa
Indicates the International Phonetic Alphabet.
PA_Ipa
Indicates the International Phonetic Alphabet.
PA_Ipa
Indicates the SAPI phonetic alphabet.


SPADAPTATIONRELEVANCE (Microsoft Speech Platform)

Microsoft Speech Platform

SPADAPTATIONRELEVANCE

New in SAPI 5.3

SPADAPTATIONRELEVANCE defines levels of bias for adaptation settings.

typedef enum SPADAPTATIONRELEVANCE
{
    SPAR_Unknown,
    SPAR_Low,
    SPAR_Medium,
    SPAR_High
} SPADAPTATIONRELEVANCE;

Elements

SPAR_Unknown
The appropriate bias for the adaptation setting is unknown.
SPAR_Low
The bias for the adaptation setting is set to low.
SPAR_Medium
The bias for the adaptation setting is set to medium.
SPAR_High
The bias for the adaptation setting is set to high.


SPADAPTATIONSETTINGS (Microsoft Speech Platform)

Microsoft Speech Platform

SPADAPTATIONSETTINGS

New in SAPI 5.3

Defines values for the types of adaptation settings.

SPADAPTATIONSETTINGS is a bit-field and hence can be combined into a DWORD using a bit-wise OR.

typedef enum SPADAPTATIONSETTINGS
{
    SPADS_Default,
    SPADS_CurrentRecognizer,
    SPADS_RecoProfile,
    SPADS_Immediate,
    SPADS_Reset,
    SPADS_HighVolumeDataSource
} SPADAPTATIONSETTINGS;

Elements

SPADS_Default
0x0000
SPADS_CurrentRecognizer
The language model adaptation is temporary for the duration that this recognizer instance is loaded in the application.
SPADS_RecoProfile
The adaptation is permanently stored in the user's profile.
SPADS_Immediate
Forces the adaptation to take effect now.
SPADS_Reset
Resets any existing adaptation that is yet to take effect.
SPADS_HighVolumeDataSource
In some cases, adaptation is done with very small amounts of data (a few words). This usually comes directly from corrections made by a user, and therefore is highly likely to be an appropriate adaptation to the general model. However, in other cases adaptation is done with large volumes of data (documents, email, and so on). In these cases, the engine should be a lot more conservative about the adaptation it does. This flag is used to indicate the high volume scenario.


SPAUDIOOPTIONS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPAUDIOOPTIONS

SPAUDIOOPTIONS lists the options for an audio stream.

See also the ISpRecoContext::SetAudioOptions and ISpRecoContext::GetAudioOptions methods.

typedef enum SPAUDIOOPTIONS
{
    SPAO_NONE,
    SPAO_RETAIN_AUDIO
} SPAUDIOOPTIONS;

Elements

SPAO_NONE
Flag indicating no options for the audio stream should be used.
SPAO_RETAIN_AUDIO
Flag indicating the audio stream should be retained (e.g. serialization of recognition object, playback of recognized audio, etc.). See also ISpRecoResult::SpeakAudio and ISpRecoResult::GetAudio.


SPAUDIOSTATE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPAUDIOSTATE

SPAUDIOSTATE sets the audio input or output state to one of four possible states.

Used directly by the ISpAudio::SetState method and as a member of the SPAUDIOSTATUS structure.

typedef enum _SPAUDIOSTATE
{
    SPAS_CLOSED,
    SPAS_STOP,
    SPAS_PAUSE,
    SPAS_RUN
} SPAUDIOSTATE;

Elements

SPAS_CLOSED
Audio is stopped and closed. For multimedia audio input devices (sound cards etc.), the device will be released. It can be opened by other processes and potentially made unavailable to SAPI.
SPAS_STOP
Audio is stopped. For multimedia audio input devices (sound cards etc.), the audio device will not be closed. This guarantees that it can be restarted by SAPI without an intervening process opening it.
SPAS_PAUSE
Audio is paused. Staying in this state for too long a period will cause audio loss.
SPAS_RUN
Audio is enabled.


SPBOOKMARKOPTIONS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPBOOKMARKOPTIONS

SPBOOKMARKOPTIONS is used at the creation of a bookmark to specify whether the bookmark will pause a recognition context.

typedef enum SPBOOKMARKOPTIONS
{
    SPBO_NONE,
    SPBO_PAUSE,
    SPBO_AHEAD,
    SPBO_TIME_UNITS
} SPBOOKMARKOPTIONS;

Members

SPBO_NONE
The recognition context will not be paused when the associated bookmark event occurs.
SPBO_PAUSE
The recognition context will be paused when the associated bookmark event occurs. See also ISpRecoContext::Pause.
SPBO_AHEAD
Allows a book mark to be set relative to and ahead of the current position.
SPBO_TIME_UNITS
Specifies that the value passed to the bookmark method is in 100 nanosecond units. If absent, the value is in bytes.


SPCATEGORYTYPE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPCATEGORYTYPE

New in Microsoft Speech Platform

SPCATEGORYTYPE lists the different states of Speech Recognizer as categories.

typedef enum SPCATEGORYTYPE
{
    SPCT_COMMAND,      // Command category
    SPCT_DICTATION,    // Dictation category
    SPCT_SLEEP,        // Sleep category
    SPCT_SUB_COMMAND,  // Command subcategory
    SPCT_SUB_DICTATION // Dictation subcategory
} SPCATEGORYTYPE;

Elements

SPCT_COMMAND
Flag indicating the command category. This category includes commands such as "Open Notepad."
SPCT_DICTATION
Flag indicating the dictation category. This category indicates that recognized speech should be treated as free text.
SPCT_SLEEP
Flag indicating the sleep category. This category indicates that the recognizer is ignoring all speech except "Start listening."
SPCT_SUB_COMMAND
Flag indicating the command subcategory.
SPCT_SUB_DICTATION
Flag indicating the dictation subcategory. This category includes dictatation subcommands that bring up the correction dialog. For example, saying "Select All" while in dictation mode.


SPCFGRULEATTRIBUTES (Microsoft Speech Platform)

 Microsoft Speech Platform

SPCFGRULEATTRIBUTES

SPCFGRULEATTRIBUTES indicates the attributes of grammar rules, such as whether the rule is top-level, active, etc.

typedef enum SPCFGRULEATTRIBUTES
{
    SPRAF_TopLevel,
    SPRAF_Active,
    SPRAF_Export,
    SPRAF_Import,
    SPRAF_Interpreter,
    SPRAF_Dynamic,
    SPRAF_Root,
    SPRAF_AutoPause,
    SPRAF_UserDelimited
} SPCFGRULEATTRIBUTES;

The SPRAF_AutoPause and SPRAF_UserDelimited flags are only valid at run-time as part of a rule state and are not valid to pass as part of a rule definition.

Elements

SPRAF_TopLevel
Flag specifying that the rule is defined as a top-level rule. Top-level rules are the entry points into the grammar and can be de-/activated programmatically. This can be set using the TOPELVEL attribute in the Speech Text Grammar Format.
SPRAF_Active
Flag specifying that the rule is defined as a top-level rule that is activated by default. These rules can be de-/activated by calling De-/ActivateRule(NULL, 0, ...). This can be set using the TOPLEVEL="ACTIVE" attribute-value pair in the Speech Text Grammar Format.
SPRAF_Export
Flag specifying that the rule is exported and hence can be referred to by a rule in another grammar. This can be set using the EXPORT="YES" attribute-value pair in the Speech Text Grammar Format.
SPRAF_Import
Flag specifying that the rule is imported from another grammar and is therefore not defined in this grammar.
SPRAF_Interpreter
Flag specifying that the rule has an interpreter associated with it.
SPRAF_Dynamic
Flag specifying that the rule is dynamic (can be changed programmatically through the ISpGrammarBuilder interface). Note that the CFG must be loaded with the SPLO_DYNAMIC flag to enable changes at run time.
SPRAF_Root
Flag specifying whether this is the root rule in the grammar. This is only meaningful for SRGS grammars.
SPRAF_AutoPause
Flag specifying the grammar attributes as AutoPause. This flag is only valid at run time as part of a rule state and is not valid to pass as part of a rule definition.
SPRAF_UserDelimited
indicates that the audio will start when the user starts speaking and will end when the user stops speaking.


SPCOMMITFLAGS (Microsoft Speech Platform)

Microsoft Speech Platform

SPCOMMITFLAGS

New in SAPI 5.3

Defines values for the types of recognizer corrections.

SPCOMMITFLAGS is used to indicate the nature of the correction when ISpRecoResult2::CommitText is called to provide new text for recognizer learning.

typedef enum SPCOMMITFLAGS
{
    SPCF_NONE,
    SPCF_ADD_TO_USER_LEXICON,
    SPCF_DEFINITE_CORRECTION
} SPCOMMITFLAGS;

Elements

SPCF_NONE
The correction is just a new word that the user typed.
SPCF_ADD_TO_USER_LEXICON
The correction is a definite correction that should also be added to the user lexicon.
SPCF_DEFINITE_CORRECTION
The correction is a correction of a recognition result returned by the recognizer.


SPCONTEXTSTATE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPCONTEXTSTATE

SPCONTEXTSTATE lists controls for setting and restoring recognition states on a per-context basis.

typedef enum SPCONTEXTSTATE
{
    SPCS_DISABLED,
    SPCS_ENABLED
}   SPCONTEXTSTATE;

Elements

SPCS_DISABLED
Specifies that grammars associated with this recognition context are disabled. When an application sets the context state to SPCS_DISABLED, all rules in all grammars owned by that context are disabled, even if the grammar state is set to exclusive.
SPCS_ENABLED
Specifies that grammars associated with this recognition context are enabled. By default recognition contexts are created with SPCS_ENABLED.


SPDATAKEYLOCATION (Microsoft Speech Platform)

 Microsoft Speech Platform

SPDATAKEYLOCATION

SPDATAKEYLOCATION lists top-level registry keys. It is used for data key locations with ISpObjectTokenCategory::GetDataKey

typedef enum SPDATAKEYLOCATION
{
    SPDKL_DefaultLocation,
    SPDKL_CurrentUser,
    SPDKL_LocalMachine,
    SPDKL_CurrentConfig
} SPDATAKEYLOCATION;

Elements

SPDKL_DefaultLocation
The default location set by ISpObjectTokenCategory.
SPDKL_CurrentUser
The registry key HKEY_CURRENT_USER.
SPDKL_LocalMachine
The registry key HKEY_LOCAL_MACHINE.
SPDKL_CurrentConfig
The registry key HKEY_CURRENT_CONFIG.


SPDISPLAYATTRIBUTES (Microsoft Speech Platform)

 Microsoft Speech Platform

SPDISPLAYATTRIBUTES

SPDISPLAYATTRIBUTES lists the display text of phrase elements. Recognition results contain the recognized text in a format that can be displayed on the screen. The SPDISPLAYATTRIBUTES type is used in the bDisplayAttributes member of SPPHRASEELEMENT to indicate additional display information that the application should honor when displaying a word, such as what to do with leading or trailing spaces.

typedef enum tagSPDISPLYATTRIBUTES
{
    SPAF_ONE_TRAILING_SPACE,
    SPAF_TWO_TRAILING_SPACES,
    SPAF_CONSUME_LEADING_SPACES,
    SPAF_ALL,
    SPAF_USER_SPECIFIED
} SPDISPLAYATTRIBUTES;

Elements

SPAF_ONE_TRAILING_SPACE
Inserts one trailing space, used for most words.
SPAF_TWO_TRAILING_SPACES
Insert two trailing spaces, often used after a sentence final period.
SPAF_CONSUME_LEADING_SPACES
Consume leading space, often used for periods. If this is absent, the word should have a leading space by default.
SPAF_ALL
A combination of all of the above flags.
SPAF_USER_SPECIFIED


SPEAKFLAGS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPEAKFLAGS

SPEAKFLAGS is used to indicate the type of content that has been sent to a TTS engine, using ISpVoice::Speak. This function usesx SPEAKFLAGS types in a bit-field, and the values should be combined with a bitwise OR.

typedef enum SPEAKFLAGS
{
    //--- SpVoice flags
    SPF_DEFAULT,
    SPF_ASYNC,
    SPF_PURGEBEFORESPEAK,
    SPF_IS_FILENAME,
    SPF_IS_XML,
    SPF_IS_NOT_XML,
    SPF_PERSIST_XML,

    //--- Normalizer flags
    SPF_NLP_SPEAK_PUNC,

    //--- TTS Format
    SPF_PARSE_SAPI,
    SPF_PARSE_SSML,
    SPF_PARSE_AUTODETECT

    //--- Masks
    SPF_NLP_MASK,
    SPF_PARSE_MASK,
    SPF_VOICE_MASK,
    SPF_UNUSED_FLAGS
} SPEAKFLAGS;

Elements

SPF_DEFAULT

Specifies that the default settings should be used. The defaults are:

  • Speak the given text string synchronously
  • Not purge pending speak requests
  • Parse the text as XML only if the first character is a left-angle-bracket (<)
  • Not persist global XML state changes across speak calls
  • Not expand punctuation characters into words.

To override this default, use the other flag values given below.

SPF_ASYNC
Specifies that the Speak call should be asynchronous. That is, it will return immediately after the speak request is queued.
SPF_PURGEBEFORESPEAK
Purges all pending speak requests prior to this speak call.
SPF_IS_FILENAME
The string passed to ISpVoice::Speak is a file name, and the file text should be spoken.
SPF_IS_XML
The input text will be parsed for XML markup.
SPF_IS_NOT_XML
The input text will not be parsed for XML markup.
SPF_PERSIST_XML
Global state changes in the XML markup will persist across speak calls.
SPF_NLP_SPEAK_PUNC
Punctuation characters should be expanded into words (e.g. "This is a sentence." would become "This is a sentence period").
SPF_PARSE_SAPI
Force XML parsing As MS SAPI.
SPF_PARSE_SSML
Force XML parsing As W3C SSML.
SPF_PARSE_AUTODETECT
The TTS XML format is auto-detected. This is the default if none of these TTS XML format values are present in the bit-field.
SPF_NLP_MASK
Not used.
SPF_PARSE_MASK
SPF_PARSE_SAPI|SPF_PARSE_SSML.
SPF_VOICE_MASK
This is an existing 5.1 mask, which has every flag bit set. In version 5.3, it has been extended to contain SPF_PARSE_MASK.
SPF_UNUSED_FLAGS
This mask has every unused bit set.


SPENDSRSTREAMFLAGS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPENDSRSTREAMFLAGS

SPENDSRSTREAMFLAGS is used to indicate the state of the input stream object when the end of a speech recognition (SR) input stream has been reached and, thus, enables an application to query for state changes. It is contained in the wParam of SPEVENT or SPEVENTEX when an SPEI_END_SR_STREAM event is raised.

typedef enum SPENDSRSTREAMFLAGS
{
    SPESF_NONE,
    SPESF_STREAM_RELEASED,
    SPESF_EMULATED
} SPENDSRSTREAMFLAGS;

Elements

SPESF_NONE
No flags are associated with the end of stream event.
SPESF_STREAM_RELEASED
The input stream object was released upon reaching the end of the current stream. For example, a wave file is a finite stream of data, and once the end of the stream, and file, is reached, the stream object is released. See also CSpEvent::InputStreamReleased.
SPESF_EMULATED
Indicates that there was no actual audio input stream, but that the input stream was emulated.


SPEVENTENUM (Microsoft Speech Platform)

Microsoft Speech Platform

SPEVENTENUM

SPEVENTENUM lists the events possible from SAPI.

It is recommended that developers use the helper class CSpEvent to easily and clearly decode events.

typedef enum SPEVENTENUM
{
    SPEI_UNDEFINED,

    //--- TTS engine
    SPEI_START_INPUT_STREAM,
    SPEI_END_INPUT_STREAM,
    SPEI_VOICE_CHANGE,
    SPEI_TTS_BOOKMARK,
    SPEI_WORD_BOUNDARY,
    SPEI_PHONEME,
    SPEI_SENTENCE_BOUNDARY,
    SPEI_VISEME,
    SPEI_TTS_AUDIO_LEVEL,

    //--- Engine vendors use these reserved bits
    SPEI_TTS_PRIVATE,
    SPEI_MIN_TTS,
    SPEI_MAX_TTS,

    //--- Speech Recognition
    SPEI_END_SR_STREAM,
    SPEI_SOUND_START,
    SPEI_SOUND_END,
    SPEI_PHRASE_START,
    SPEI_RECOGNITION,
    SPEI_HYPOTHESIS,
    SPEI_SR_BOOKMARK,
    SPEI_PROPERTY_NUM_CHANGE,
    SPEI_PROPERTY_STRING_CHANGE,
    SPEI_FALSE_RECOGNITION,
    SPEI_INTERFERENCE,
    SPEI_REQUEST_UI,
    SPEI_RECO_STATE_CHANGE,
    SPEI_ADAPTATION,
    SPEI_START_SR_STREAM,
    SPEI_RECO_OTHER_CONTEXT,
    SPEI_SR_AUDIO_LEVEL,
    SPEI_SR_RETAINEDAUDIO,

    //--- Engine vendors use this reserved value.
    SPEI_SR_PRIVATE,

    SPEI_ACTIVE_CATEGORY_CHANGED,

    //--- Reserved for system use.
    SPEI_RESERVED5,
    SPEI_RESERVED6,

    SPEI_MIN_SR,
    SPEI_MAX_SR,

    //--- Reserved: Do not use
    SPEI_RESERVED1,
    SPEI_RESERVED2,
    SPEI_RESERVED3
} SPEVENTENUM;

Elements

SPEI_START_INPUT_STREAM
The input stream (text or audio) from a Speak or SpeakStream call has begun synthesizing to the output. The event is fired by SAPI.
SPEI_END_INPUT_STREAM
The input stream (text or audio) from a Speak or SpeakStream call has finished synthesizing to the output. The event is fired by SAPI.
SPEI_VOICE_CHANGE
SAPI fires this event for voice changes within a single input stream of a Speak call. wParam is either zero or the SPF_PERSIST_XML. If the current speak call takes SPF_PERSIST_XML, wparam is SPF_PERSIST_XML. Otherwise, zero. lParam is the current voice object token. elParamType has to be SPET_LPARAM_IS_TOKEN.
SPEI_TTS_BOOKMARK
The bookmark element is used to insert a bookmark into the output stream. If an application specifies interest in bookmark events, it will receive the bookmark events during synthesis. wParam is the current bookmark name (in base 10) converted to a long integer. If name of current bookmark is not an integer, wParam will be zero. lParam is the bookmark string. elParamType has to be SPET_LPARAM_IS_STRING.
SPEI_WORD_BOUNDARY
A word is beginning to synthesize. Markup language (XML) markers are counted in the boundaries and offsets. wParam is the character length of the word in the current input stream being synthesized. lParam is the character position within the current text input stream of the word being synthesized.
SPEI_PHONEME
Phoneme was returned by the TTS engine. The high word of wParam is the duration, in milliseconds, of the current phoneme element. The low word is the id of the next phoneme element. The high word of lparam is the phoneme element feature defined in SPVFEATURE. This value will be zero if the current phoneme element is not a primary stress or emphasis. The low word of lParam is the id for the current phoneme element being synthesized.

When the engine synthesizes a phoneme comprised of more than one phoneme element, it raises an event for each element. For example, when a Japanese TTS engine speaks the phoneme "KYA," which is comprised of the phoneme elements "KI" and "XYA," it raises an SPEI_PHONEME event for each element. Because the element "KI" in this case modifies the sound of the element following it, rather than initiating a sound, the duration of its SPEI_PHONEME event is zero.
SPEI_SENTENCE_BOUNDARY
A sentence is beginning to synthesize. wParam is the character length of the sentence including punctuation in the current input stream being synthesized. lParam is the character position within the current text input stream of the sentence being synthesized.
SPEI_VISEME
Viseme was determined by synthesis engine. The high word of wParam is the duration, in milliseconds, of the current viseme. The low word is for the next viseme of type SPVISEMES. The high word of lParam is the viseme feature defined in SPVFEATURE. This value will be zero if the current viseme is not primary stress or emphasis. The low word of lParam is the current viseme being synthesized.
SPEI_TTS_AUDIO_LEVEL
This event is fired by SAPI. lParam is 0, and wParam is the current audio level from zero to 100.
SPEI_TTS_PRIVATE
Reserved for private/internal use by the TTS Engine.
SPEI_MIN_TTS
Minimum event enumeration value for TTS events.
SPEI_MAX_TTS
Maximum event enumeration value for TTS events.
SPEI_END_SR_STREAM
The SR engine has finished receiving an audio input stream. LPARAM points to the SR engine's final HRESULT code (see CSpEvent::EndStreamResult). WPARAM points to a Boolean value signifying whether the audio input stream object was released (see CSpEvent::InputStreamReleased).
SPEI_SOUND_START
The SR engine determined that audible sound is available through the input stream.
SPEI_SOUND_END
The SR engine has determined that audible sound is no longer available through the input stream, or that the sound stream has been inactive for a period.
SPEI_PHRASE_START
The SR engine is starting to recognize a phrase. Note that this MUST be followed by either an SPEI_FALSE_RECOGNITION or SPEI_RECOGNITION event.
SPEI_RECOGNITION
The SR engine is returning a full recognition - its best guess at a text representation of the audio data. LParam is a pointer to an ISpRecoResult object (see CSpEvent::RecoResult).
SPEI_HYPOTHESIS
The SR engine is returning a partial phrase recognition - effectively its best guess up to that point in the stream. LParam is a pointer to an ISpRecoResult object (see CSpEvent::RecoResult).
SPEI_SR_BOOKMARK
A Bookmark event is returned when the SR engine has processed to the stream position of a bookmark. lParam is an application specified value set using ISpRecoContext::Bookmark. wParam is SPREF_AutoPause if ISpRecoContext::Bookmark was called with SPBO_PAUSE, and NULL otherwise.
SPEI_PROPERTY_NUM_CHANGE
An SR engine supported property was changed. LPARAM is a string pointer to the property name that changed (see CSpEvent::PropertyName]. WPARAM contains the new value (see CSpEvent::PropertyNumValue).
SPEI_PROPERTY_STRING_CHANGE
LPARAM is a string pointer to the property name that changed (see CSpEvent::PropertyName). Immediately following the NULL-termination of the property name is the new property value (see CSpEvent::PropertyStringValue).
SPEI_FALSE_RECOGNITION
Apparent speech without valid recognition. An SR engine can optionally return a result object, which will be referenced by the LPARAM member (see CSpEvent::RecoResult).
SPEI_INTERFERENCE
The SR engine determined that the sound stream has a hindrance and is preventing a successful recognition. lParam is any combination of SPINTERFERENCE flags (See CSpEvent::Interference).
SPEI_REQUEST_UI
The SR engine's request to display a specific user interface. LPARAM is a null-terminated string (see CSpEvent::RequestTypeOfUI).
SPEI_RECO_STATE_CHANGE
The recognizer state has changed. WPARAM is the new recognizer state (see SPRECOSTATE and CSpEvent::RecoState).
SPEI_ADAPTATION
The SR engine is ready to process the adaptation buffer.
SPEI_START_SR_STREAM
The SR engine has reached the start of a new audio stream.
SPEI_SR_AUDIO_LEVEL
The audio input stream object fires this event. wParam is the currentaudio level from zero to 100.
SPEI_SR_RETAINEDAUDIO
Returns the audio that was sent to the recognizer.
SPEI_RECO_OTHER_CONTEXT
A recognition was sent to another context.
SPEI_SR_PRIVATE
Reserved for private/internal use by the SR engine.
SPEI_ACTIVE_CATEGORY_CHANGED
The active category on the speech recognizer has changed. wParam and lParam are null.
SPEI_RESERVED5
Reserved for system use.
--
SPEI_RESERVED6
Reserved for systems use.
--
SPEI_MIN_SR
Minimum event enumeration value for speech recognition events.
SPEI_MAX_SR
Maximum event enumeration value for speech recognition events.
SPEI_RESERVED1
Reserved for SAPI internal use. See SPFEI Remarks section.
SPEI_RESERVED2
Reserved for SAPI internal use. See SPFEI Remarks section.
SPEI_RESERVED3
Reserved for future use, do not use.


SPEVENTLPARAMTYPE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPEVENTLPARAMTYPE

SPEVENTLPARAMTYPE lists objects and data pointers attached to events. SPEVENTLPARAMTYPE specifies the type of the attached data, enabling the user to determine how to access the data, and how to release the data when finished with the event.
See the helper CSpEvent for more information about C++ class that has properties for accessing event-specific data, and a destructor to automatically cleanup attached data.

See the helper SpClearEvent for more information about releasing objects or memory attached to an event.

typedef enum SPEVENTLPARAMTYPE
{
    SPET_LPARAM_IS_UNDEFINED,
    SPET_LPARAM_IS_TOKEN,
    SPET_LPARAM_IS_OBJECT,
    SPET_LPARAM_IS_POINTER,
    SPET_LPARAM_IS_STRING
} SPEVENTLPARAMTYPE;

Elements

SPET_LPARAM_IS_UNDEFINED
The SPEVENT.lParam value represents an undefined value.
For example, all TTS events, except SPEI_VOICE_CHANGE and SPEI_TTS_BOOKMARK, do not have attached data, so the event type is SPET_LPARAM_IS_UNDEFINED.
The user does not need to release associated data, since there is no associated data.
SPET_LPARAM_IS_TOKEN
The SPEVENT.lParam value represents a pointer to an ISpObjectToken object.
For example, the TTS voice change event (i.e., SPEI_VOICE_CHANGE) includes a pointer to the new voice's object token, so the lParam type is SPET_LPARAM_IS_TOKEN.
The user must call IUnknown::Release on the lParam member (as pointer) to release the associated object token.
SPET_LPARAM_IS_OBJECT
The SPEVENT.lParam value represents a pointer to an object.
For example, the speech recognition event (i.e., SPEI_RECOGNITION) includes a pointer to the recognition result (e.g. ISpRecoResult), so the lParam type is SPET_LPARAM_IS_OBJECT.
The user must call IUnknown::Release on the lParam member (as pointer) to release the associated object token.
SPET_LPARAM_IS_POINTER
The SPEVENT.lParam value represents a memory pointer.
For example, the property string change event (i.e., SPEI_PROPERTY_STRING_CHANGE) includes a pointer to a block of memory that contains a string (e.g. WCHAR*), so the lParam type is SPET_LPARAM_IS_POINTER.
The user must call CoTaskMemFree on the lParam member (as pointer) to release the associated memory.
SPET_LPARAM_IS_STRING
The SPEVENT.lParam value represents a pointer to a string.
For example, the TTS bookmark event (i.e., SPEI_TTS_BOOKMARK) includes a pointer the bookmark name, so the lParam type is SPET_LPARAM_IS_STRING.
The user must call CoTaskMemFree on the lParam member (as pointer) to release the associated memory.


SPFILEMODE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPFILEMODE

SPFILEMODE lists the file opening state used by ISpStream::BindToFile and the helper function SPBindToFile.

typedef enum SPFILEMODE
{
    SPFM_OPEN_READONLY,
    SPFM_OPEN_READWRITE,
    SPFM_CREATE,
    SPFM_CREATE_ALWAYS,
    SPFM_NUM_MODES
} SPFILEMODE;

Elements

SPFM_OPEN_READONLY
Opens the existing file in read-only mode. This will fail if the file does not exist.
SPFM_OPEN_READWRITE
Opens the existing file in read-write mode. This will fail if the file does not exist.
SPFM_CREATE
Opens the file if one exists, or creates the file if one does not exist. This flag indicates that the file will be opened in read-write mode.
SPFM_CREATE_ALWAYS
Creates the file, even if the file already exists and deletes the previous file. This flag indicates that the file will be opened in read-write mode.
SPFM_NUM_MODES
This flag is used for limit checking.


SPGRAMBUILDCOMMITFLAGS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPGRAMBUILDCOMMITFLAGS

SPGRAMBUILDCOMMITFLAGS is a bitwise flag used with the ISpGrammarBuilder::Commit function.

typedef enum SPGRAMBUILDCOMMITFLAGS
{
   SPGBCF_NONE         = 0,
   SPGBCF_OPTIMIZE     = (1L << 0),
   SPGBCF_RESERVED1    = (1L << 1),
   SPGBCF_RESERVED2    = (1L << 2),
   SPGBCF_RESERVED3    = (1L << 3),
   SPGBCF_RESERVED4    = (1L << 4),
   SPGBCF_RESERVED5    = (1L << 5),
   SPGBCF_RESERVED6    = (1L << 6),
   SPGBCF_RESERVED7    = (1L << 7),
   SPGBCF_RESERVED8    = (1L << 8),
   SPGBCF_RESERVED9    = (1L << 9),
   SPGBCF_RESERVED10   = (1L << 10),
   SPGBCF_RESERVED11   = (1L << 11),
   SPGBCF_RESERVED12   = (1L << 12),
   SPGBCF_RESERVED13   = (1L << 13),
   SPGBCF_RESERVED14   = (1L << 14),
   SPGBCF_RESERVED15   = (1L << 15),
   SPGBCF_PRIVATE1     = (1L << 16),
   SPGBCF_PRIVATE2     = (1L << 17),
   SPGBCF_PRIVATE3     = (1L << 18),
   SPGBCF_PRIVATE4     = (1L << 19),
   SPGBCF_PRIVATE5     = (1L << 20),
   SPGBCF_PRIVATE6     = (1L << 21),
   SPGBCF_PRIVATE7     = (1L << 22),
   SPGBCF_PRIVATE8     = (1L << 23),
   SPGBCF_PRIVATE9     = (1L << 24),
   SPGBCF_PRIVATE10    = (1L << 25),
   SPGBCF_PRIVATE11    = (1L << 26),
   SPGBCF_PRIVATE12    = (1L << 27),
   SPGBCF_PRIVATE13    = (1L << 28),
   SPGBCF_PRIVATE14    = (1L << 29),
   SPGBCF_PRIVATE15    = (1L << 30),
   SPGBCF_PRIVATE16    = (1L << 31)
} SPGRAMBUILDCOMMITFLAGS;

Elements

SPGBCF_NONE
Indicates that no flag is set.
SPGBCF_OPTIMIZE
The grammar structure is optimized.
SPGBCF_RESERVED1 through SPGBCF_RESERVED15
Reserved for future use.
SPGBCF_PRIVATE1 through SPGBCF_PRIVATE16
Reserved for private use by SAPI.


SPGRAMMAROPTIONS (Microsoft Speech Platform)

Microsoft Speech Platform

SPGRAMMAROPTIONS

New in SAPI 5.3

Specifies the types of grammar options in a recognition context.

SPGRAMMAROPTIONS is a bit-field and hence can be combined into a DWORD using a bit-wise OR.

typedef enum SPGRAMMAROPTIONS
{
    SPGO_SAPI,
    SPGO_SRGS,
    SPGO_SRGS_SCRIPT,
    SPGO_FILE,
    SPGO_HTTP,
    SPGO_RES,
    SPGO_OBJECT,
    SPGO_DEFAULT,
    SPGO_ALL
} SPGRAMMAROPTIONS;

Elements

SPGO_SAPI
Enables support for the SAPI 5.1 grammar XML format.
SPGO_SRGS
Enables support for the W3C SRGS grammar XML format.
SPGO_SRGS_SCRIPT
Enables support for SRGS grammars to contain Jscript for semantic interpretation.
SPGO_FILE
Grammars can be loaded from local and UNC file paths.
SPGO_HTTP
Grammars can be loaded from HTTP and HTTPS URLs.
SPGO_RES
Referenced grammars can be imported from a resource. This ONLY applies to referenced grammars (for example, those loaded by the ruleref tag). This flag has absolutely no effect on the LoadCmdFromResource function.
SPGO_OBJECT
Referenced grammars can be imported from a COM object. This ONLY applies to referenced grammars. This flag has absolutely no effect on the LoadCmdFromObject function. NOTE: Our SRGS implementation has no means of referencing grammars in COM objects. This feature is only used with the Microsoft Speech Platform Grammar XML format or with grammars that are built at runtime by calling SAPI functions.
SPGO_DEFAULT
By default, all options are enabled except scripting in SRGS.
SPGO_ALL
All options are enabled.


SPGRAMMARSTATE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPGRAMMARSTATE

SPGRAMMARSTATE lists controls for setting and restoring grammar states.

typedef enum SPGRAMMARSTATE
{
    SPGS_ENABLED = 0,
    SPGS_DISABLED = 1,
    SPGS_EXCLUSIVE = 3,
} SPGRAMMARSTATE;

Elements

SPGS_ENABLED
Activates all the top-level rules in the grammar for the SR engine.

Note that a rule must have an active recognition context, active grammar, and active top-level rule in order to be recognized.

SPGS_DISABLED
Deactivates all the top-level rules in the grammar for the SR engine.
SPGS_EXCLUSIVE
Turns off all top-level rules that are not part of this grammar.

For example, an application that needs modal-like input exclusivity can change the grammar to exclusive, which disables all other non-exclusive grammars.


SPGRAMMARWORDTYPE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPGRAMMARWORDTYPE

SPGRAMMARWORDTYPE is used during grammar building, when adding a word transition to a grammar. It indicates the type of the word being added to the grammar (for example, is it in display form and will need conversion to lexical form; is it in the same form as it exists in the lexicon; is it in pronunciation form?).

typedef enum SPGRAMMARWORDTYPE
{
    SPWT_DISPLAY,
    SPWT_LEXICAL,
    SPWT_PRONUNCIATION,
    SPWT_LEXICAL_NO_SPECIAL_CHARS
} SPGRAMMARWORDTYPE;

Elements

SPWT_DISPLAY
Each word to be added is in display form. That is, it possibly will have to be converted into lexical form(s). For example, the word "23" (display form) would have to converted into "twenty three" (lexical form). This is currently not implemented in SAPI.
SPWT_LEXICAL
Each word to be added is in lexical form and can be used to access the lexicon.
SPWT_PRONUNCIATION
Each word is specified solely by its pronunciation. This is currently not implemented.
SPWT_LEXICAL_NO_SPECIAL_CHARS
Switches off the handling of special characters in the grammar. For example "*" normally means dictation and "?" means wildcard, but this flag means that "*" means asterisk, and "?" means ellipsis.


SPINTERFERENCE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPINTERFERENCE

SPINTERFERENCE lists possible causes of interference or poor recognition with the input stream.

typedef enum SPINTERFERENCE
{
    SPINTERFERENCE_NONE,
    SPINTERFERENCE_NOISE,
    SPINTERFERENCE_NOSIGNAL,
    SPINTERFERENCE_TOOLOUD,
    SPINTERFERENCE_TOOQUIET,
    SPINTERFERENCE_TOOFAST,
    SPINTERFERENCE_TOOSLOW
} SPINTERFERENCE;

Elements

SPINTERFERENCE_NONE
Private event. Do not use.
SPINTERFERENCE_NOISE
The sound received is interpreted by the speech recognition engine as noise. This event is generated when there is a SOUND_START followed by a SOUND_END without an intervening PHRASE_START. The event will be also generated during dictation if, after a series of hypotheses, it is determined that the signal is noise.
SPINTERFERENCE_NOSIGNAL
A sound is received but it is of a constant intensity. This also includes the microphone being unplugged or muted.
SPINTERFERENCE_TOOLOUD
A sound is received but the stream intensity is too high for discrete recognition.
SPINTERFERENCE_TOOQUIET
A sound is received but the stream intensity is too low for discrete recognition.
SPINTERFERENCE_TOOFAST
The words are spoken too quickly for discrete recognition.
SPINTERFERENCE_TOOSLOW
The words are spoken too slowly and indicates excessive time between words.


SPLEXICONTYPE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPLEXICONTYPE

SPLEXICONTYPE lists the allowed lexicon types. Currently there are only two types in use--user and application lexicons. There are ample reserved types for future expansion and ample private types for potential private use by applications and engines.

typedef enum SPLEXICONTYPE
{
   eLEXTYPE_USER,
   eLEXTYPE_APP,
   eLEXTYPE_VENDORLEXICON1,
   eLEXTYPE_LETTERTOSOUND,
   eLEXTYPE_MORPHOLOGY,
   eLEXTYPE_RESERVED4,
   eLEXTYPE_USER_SHORTCUT,
   eLEXTYPE_RESERVED6,
   eLEXTYPE_RESERVED7,
   eLEXTYPE_RESERVED8,
   eLEXTYPE_RESERVED9,
   eLEXTYPE_RESERVED10,
   eLEXTYPE_PRIVATE1,
   eLEXTYPE_PRIVATE2,
   eLEXTYPE_PRIVATE3,
   eLEXTYPE_PRIVATE4,
   eLEXTYPE_PRIVATE5,
   eLEXTYPE_PRIVATE6,
   eLEXTYPE_PRIVATE7,
   eLEXTYPE_PRIVATE8,
   eLEXTYPE_PRIVATE9,
   eLEXTYPE_PRIVATE10,
   eLEXTYPE_PRIVATE11,
   eLEXTYPE_PRIVATE12,
   eLEXTYPE_PRIVATE13,
   eLEXTYPE_PRIVATE14,
   eLEXTYPE_PRIVATE15,
   eLEXTYPE_PRIVATE16,
   eLEXTYPE_PRIVATE17,
   eLEXTYPE_PRIVATE18,
   eLEXTYPE_PRIVATE19,
   eLEXTYPE_PRIVATE20
} SPLEXICONTYPE;

Elements

eLEXTYPE_USER
Indicates the user lexicon. Each Windows user has a unique user lexicon.
eLEXTYPE_APP
Indicates the application lexicons. Application lexicon is shared by all users.
eLEXTYPE_VENDORLEXICON
Indicates that the pronunciation comes directly from the engine's built-in lexicon.
eLEXTYPE_LETTERTOSOUND
Indicates that the pronunciation was synthesized by an algorithm that deduces pronunciation based on spelling.
eLEXTYPE_MORPHOLOGY
Indicates that the pronunciation was synthesized based on the assumption that the word is a morphed form of another word that already exists in the engine's lexicon.
eLEXTYPE_RESERVED4
Reserved for future use.
eLEXTYPE_USER_SHORTCUT
Indicates that the word is from the user shortcut lexicon. This is a lexicon that maps a spoken term to an expanded printed term. For example, a user may define "my home address" as "12345 NE 678 Av NE Someplace WA 98888" to save them having to dictate and correct the full address.
eLEXTYPE_RESERVED6 through eLEXTYPE_RESERVED10
Reserved for future use.
eLEXTYPE_PRIVATE1 through eLEXTYPE_PRIVATE20
Indicates the private lexicons. Engines can call ISpContainerLexicon::AddLexicon with one of these flags to add its private lexicons to the container lexicon for consistent access. If these lexicon types are used the lexicons must fully comply with the ISpLexicon interface.


SPLOADOPTIONS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPLOADOPTIONS

SPLOADOPTIONS indicates how a grammar is loaded. This is used by the ISpRecoGrammar interface.

typedef enum SPLOADOPTIONS
{
    SPLO_STATIC,
    SPLO_DYNAMIC
} SPLOADOPTIONS;

Elements

SPLO_STATIC
Flag specifying that the grammar is loaded statically.
SPLO_DYNAMIC
Flag specifying that the grammar is loaded dynamically, meaning that rules can be modified and committed at run-time.


SPMATCHINGMODE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPMATCHINGMODE

New in SAPI 5.3

Enumerates the modes of subset matching.

typedef enum SPMATCHINGMODE
{
    AllWords,
    Subsequence,
    OrderedSubset,
    SubsequenceContentRequired,
    OrderedSubsetContentRequired
} SPMATCHINGMODE;

Elements

AllWords
Indicates that recognition of a subset string should take place if all words in the match string are recognized as a sequence in the audio input.
Subsequence
Indicates that recognition of a subset string should take place if one or more words in the match string are recognized as a sequence in the audio input, and the relative order of those recognized words is the same as in the subset phrase. A matched word may be a preposition or article.
OrderedSubset
Indicates that recognition of a subset string should take place if one or more words in the match string are recognized in the audio input, and the relative order of those recognized words is the same as in the subset phrase. A matched word may be a preposition or article.
SubsequenceContentRequired
Indicates that recognition of a subset string should take place if one or more words in the match string are recognized as a sequence in the audio input. A matched word may not be a preposition or article.
OrderedSubsetContentRequired
Indicates that recognition of a subset string should take place if one or more words in the match string are recognized as a sequence in the audio input. A matched word may not be a preposition or article.

Remarks

SPMATCHINGMODE is used by ISpGrammarBuilder2::AddTextSubset.


SPPARTOFSPEECH (Microsoft Speech Platform)

 Microsoft Speech Platform

SPPARTOFSPEECH

SPPARTOFSPEECH is used to indicate the part of speech (noun, verb, etc.) when adding a word to or removing a word from a lexicon. The enumeration lists the parts-of-speech categories used in SAPI 5. This list of known parts-of-speech types is intentionally small and broad and will be expanded and refined in future releases. SPPARTOFSPEECH in its minimal form is required to support look ups from the standard SAPI lexicon. This information is useful to TTS engines to determine the correct pronunciation for ambiguous words based on their context.

typedef enum SPPARTOFSPEECH
{
    SPPS_NotOverriden,
    SPPS_Unknown,
    SPPS_Noun,
    SPPS_Verb,
    SPPS_Modifier,
    SPPS_Function,
    SPPS_Noncontent,
    SPPS_SuppressWord
} SPPARTOFSPEECH;

Elements

SPPS_NotOverriden
Flag indicating that the part of speech already present in the lexicon should not be overridden.
SPPS_Unknown
Flag indicating that the part of speech is unknown and is probably from the user lexicon.
SPPS_Noun
Flag indicating that the part of speech is a noun.
SPPS_Verb
Flag indicating that the part of speech is a verb.
SPPS_Modifier
Flag indicating that the part of speech is a modifier.
SPPS_Function
Flag indicating that the part of speech is a function.
SPPS_Noncontent
Flag indicating that the word generally has no semantic value, and its absence from an utterance in a command-and-control grammar may not matter. This is used with the <SUBSET> tag in C&C grammars. For example, if the word "the" was non-content, then a grammar that is insensitive to non-content words would treat the utterances "play the Beatles" and "play Beatles" identically.
SPPS_SuppressWord
Flag indicating that the word should not be recognized.


SPPHRASERNG (Microsoft Speech Platform)

 Microsoft Speech Platform

SPPHRASERNG

typedef enum SPPHRASERNG
{
   SPPR_ALL_ELEMENTS
} SPPHRASERNG;

Elements

SPPR_ALL_ELEMENTS
Indicates all elements of an alternate phrase may be used.


SPPRONUNCIATIONFLAGS (Microsoft Speech Platform)

Microsoft Speech Platform

SPPRONUNCIATIONFLAGS

New in SAPI 5.3

SPPRONUNCIATIONFLAGS is used with the ISpEnginePronunciation::GetPronounciations function.

typedef enum SPPRONUNCIATIONFLAGS
{
    ePRONFLAG_USED
} SPPRONUNCIATIONFLAGS;

Elements

ePRONFLAG_USED
Set if the engine will use this pronunciation; otherwise, clear. For example, a speech recognition engine would listen for all pronunciations, and hence would always set this bit. However, a synthesis engine will only synthesize one of the pronunciations, and will only set this bit in this case.


SPRECOEVENTFLAGS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPRECOEVENTFLAGS

SPRECOEVENTFLAGS lists the states of the SR engine. When a recognition event is raised, the wParam of SPEVENT or SPEVENTEX will contain a value from SPRECOEVENTFLAGS indicating the state of the SR engine.

typedef enum SPRECOEVENTFLAGS
{
    SPREF_AutoPause,
    SPREF_Emulated,
    SPREF_SMLTimeout,
    SPREF_ExtendableParse,

    SPREF_Hypothesis,
    SPREF_FalseRecognition
} SPRECOECOEVENTFLAGS;

Elements

SPREF_AutoPause
Indicates that the engine is in the auto-paused state.
SPREF_Emulated
Indicates that the engine is in emulation.
SPREF_SMLTimeout
Indicates there was a timeout generating the SML and hence no SML will be returned.
SPREF_ExtendableParse
The user said something that was a valid path through the grammar, but it is possible they could be about to say something else. For example, if the grammar contains "play the ace" and "play the ace of spades" and the user says "play the ace", this flag is set.
SPREF_Hypothesis
Indicates the result is a partial recognition. For example, if the grammar contains "play the ace of spades" and the user says "play the ace", then it is a hypothesis.
SPREF_FalseRecognition
Indicates the recognizer rejected the recognition because of low confidence score.


SPRECOSTATE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPRECOSTATE

SPRECOSTATE lists the various states of the recognition engine.

typedef enum SPRECOSTATE
{
    SPRST_INACTIVE,
    SPRST_ACTIVE,
    SPRST_ACTIVE_ALWAYS,
    SPRST_INACTIVE_WITH_PURGE,
    SPRST_NUM_STATES
} SPRECOSTATE;

Elements

SPRST_INACTIVE
The engine and audio input are inactive and no audio is being read, even if there rules active. The audio device will be closed in this state. Normally an application should not set the state to SPRST_INACTIVE because when using the shared engine, recognition will be stopped for all applications, not just this one. An application can easily disable recognition on its contexts by calling ISpRecoContext::SetContextState.
SPRST_ACTIVE
This state is the default and indicates that recognition will take place if there are any active rules. If a rule is active, audio will be read and passed to the SR engine and recognition will happen.
SPRST_ACTIVE_ALWAYS
Indicates the audio is running regardless of the rule state. Even if there are no active rules, audio will still be read and passed to the engine. This state can be useful for applications if they want to receive volume level events (SPEI_SR_AUDIO_LEVEL), in order to display a VU-meter or similar.
SPRST_INACTIVE_WITH_PURGE
Indicates the engine state will be set to inactive, but all active audio data is purged. This state is used when an application wishes to shut an engine down as quickly as possible, without waiting for it to finish processing any audio data that is currently buffered. This state should be used with care because it will affect all applications in the shared case.
SPRST_NUM_STATES
To be provided in a future release.


SPRULESTATE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPRULESTATE

SPRULESTATE is used when setting the state of a grammar rule or setting the state of dictation (for example, active/inactive, etc).

typedef enum SPRULESTATE
{
    SPRS_INACTIVE,
    SPRS_ACTIVE,
    SPRS_ACTIVE_WITH_AUTO_PAUSE,
    SPRS_ACTIVE_USER_DELIMITED
} SPRULESTATE;

Elements

SPRS_INACTIVE
Grammar rule is inactive.
SPRS_ACTIVE
Grammar rule is active.
SPRS_ACTIVE_WITH_AUTO_PAUSE
SR engine will be placed in a paused state when the grammar rule is recognized. Also known as an "auto-pause" rule.
SPRS_ACTIVE_USER_DELIMITED
Indicates that the audio will start when the user starts speaking and will end when the user stops speaking.


SPRUNSTATE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPRUNSTATE

SPRUNSTATE lists the voice running states.

typedef enum SPRUNSTATE
{
    SPRS_DONE,
    SPRS_IS_SPEAKING
} SPRUNSTATE;

Elements

SPRS_DONE
The voice has completed processing all queued streams.
SPRS_IS_SPEAKING
The voice instance currently has the audio claimed.


SPSEMANTICFORMAT (Microsoft Speech Platform)

 Microsoft Speech Platform

SPSEMANTICFORMAT

New in Microsoft Speech Platform

SPSEMANTICFORMAT lists the various values of a grammar's tag-format attribute.

typedef enum SPSEMANTICFORMAT
{
    SPSMF_SAPI_PROPERTIES,
    SPSMF_SRGS_SEMANTICINTERPRETATION_MS,
    SPSMF_SRGS_SAPIPROPERTIES,
    SPSMF_UPS,
    SPSMF_SRGS_SEMANTICINTERPRETATION_W3C
} SPSEMANTICFORMAT;

Elements

SPSMF_SAPI_PROPERTIES
Indicates that the semantic properties are derived from the property name/value associations declared inside a SAPI text grammar.
SPSMF_SRGS_SEMANTICINTERPRETATION_MS
Indicates that the value of the tag-format attribute is "semantics-ms/1.0".
SPSMF_SRGS_SAPIPROPERTIES
Indicates that the value of the tag-format attribute is "properties-ms/1.0".
SPSMF_UPS
Reserved for system use.
SPSMF_SRGS_SEMANTICINTERPRETATION_W3C
Indicates that the value of the tag-format attribute is either "semantics/1.0" or "semantics/1.0-literals".


SPSHORTCUTTYPE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPSHORTCUTTYPE

New in SAPI 5.3

Enumerates the types of shortcut pair.

typedef enum SPSHORTCUTTYPE
{
    SPSHT_NotOverriden,
    SPSHT_Unknown,
    SPSHT_EMAIL,
    SPSHT_OTHER,
    SPPS_RESERVED1,
    SPPS_RESERVED2,
    SPPS_RESERVED3,
    SPPS_RESERVED4
} SPSHORTCUTTYPE;

Elements

SPSHT_NotOverriden
If the shortcut pair is already present in the store, it should not be overridden.
SPSHT_Unknown
The type of shortcut pair is unknown.
SPSHT_EMAIL
This shortcut pair is for an email address.
SPSHT_OTHER
This shortcut pair is for general input.
SPPS_RESERVED1 through SPPS_RESERVED4
Reserved for future use.


SPSTREAMFORMAT (Microsoft Speech Platform)

 Microsoft Speech Platform

SPSTREAMFORMAT

SPSTREAMFORMAT lists the supported stream formats.

These enumeration elements are all common audio formats ranging from the uncompressed PCM formats to highly compressed formats. They are available as standard formats on the Windows operating systems and are supported by SAPI 5.

typedef enum SPSTREAMFORMAT
{
    SPSF_Default,
    SPSF_NoAssignedFormat,
    SPSF_Text,
    SPSF_NonStandardFormat,
    SPSF_ExtendedAudioFormat,
    // Standard PCM wave formats
    SPSF_8kHz8BitMono,
    SPSF_8kHz8BitStereo,
    SPSF_8kHz16BitMono,
    SPSF_8kHz16BitStereo,
    SPSF_11kHz8BitMono,
    SPSF_11kHz8BitStereo,
    SPSF_11kHz16BitMono,
    SPSF_11kHz16BitStereo,
    SPSF_12kHz8BitMono,
    SPSF_12kHz8BitStereo,
    SPSF_12kHz16BitMono,
    SPSF_12kHz16BitStereo,
    SPSF_16kHz8BitMono,
    SPSF_16kHz8BitStereo,
    SPSF_16kHz16BitMono,
    SPSF_16kHz16BitStereo,
    SPSF_22kHz8BitMono,
    SPSF_22kHz8BitStereo,
    SPSF_22kHz16BitMono,
    SPSF_22kHz16BitStereo,
    SPSF_24kHz8BitMono,
    SPSF_24kHz8BitStereo,
    SPSF_24kHz16BitMono,
    SPSF_24kHz16BitStereo,
    SPSF_32kHz8BitMono,
    SPSF_32kHz8BitStereo,
    SPSF_32kHz16BitMono,
    SPSF_32kHz16BitStereo,
    SPSF_44kHz8BitMono,
    SPSF_44kHz8BitStereo,
    SPSF_44kHz16BitMono,
    SPSF_44kHz16BitStereo,
    SPSF_48kHz8BitMono,
    SPSF_48kHz8BitStereo,
    SPSF_48kHz16BitMono,
    SPSF_48kHz16BitStereo,
    // TrueSpeech format
    SPSF_TrueSpeech_8kHz1BitMono,
    // A-Law formats
    SPSF_CCITT_ALaw_8kHzMono,
    SPSF_CCITT_ALaw_8kHzStereo,
    SPSF_CCITT_ALaw_11kHzMono,
    SPSF_CCITT_ALaw_11kHzStereo,
    SPSF_CCITT_ALaw_22kHzMono,
    SPSF_CCITT_ALaw_22kHzStereo,
    SPSF_CCITT_ALaw_44kHzMono,
    SPSF_CCITT_ALaw_44kHzStereo,
    // u-Law formats
    SPSF_CCITT_uLaw_8kHzMono,
    SPSF_CCITT_uLaw_8kHzStereo,
    SPSF_CCITT_uLaw_11kHzMono,
    SPSF_CCITT_uLaw_11kHzStereo,
    SPSF_CCITT_uLaw_22kHzMono,
    SPSF_CCITT_uLaw_22kHzStereo,
    SPSF_CCITT_uLaw_44kHzMono,
    SPSF_CCITT_uLaw_44kHzStereo,
    // ADPCM formats
    SPSF_ADPCM_8kHzMono,
    SPSF_ADPCM_8kHzStereo,
    SPSF_ADPCM_11kHzMono,
    SPSF_ADPCM_11kHzStereo,
    SPSF_ADPCM_22kHzMono,
    SPSF_ADPCM_22kHzStereo,
    SPSF_ADPCM_44kHzMono,
    SPSF_ADPCM_44kHzStereo,
    // GSM 6.10 formats
    SPSF_GSM610_8kHzMono,
    SPSF_GSM610_11kHzMono,
    SPSF_GSM610_22kHzMono,
    SPSF_GSM610_44kHzMono,
    SPSF_NUM_FORMATS
} SPSTREAMFORMAT;


SPVACTIONS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPVACTIONS

SPVACTIONS is a member of SPVSTATE. This enumeration specifies the action that should be taken for the text fragment with which it is associated.

typedef enum SPVACTIONS
{
    SPVA_Speak,
    SPVA_Silence,
    SPVA_Pronounce,
    SPVA_Bookmark,
    SPVA_SpellOut,
    SPVA_Section,
    SPVA_ParseUnknownTag
} SPVACTIONS;

Elements

SPVA_Speak
The default value - the associated text fragment should be processed and spoken.
SPVA_Silence
There is no associated text string - the associated fragment was the result of a <Silence> XML tag, and a silence (of length specified in the associated SPVSTATE) should be inserted into the output stream.
SPVA_Pronounce
The associated text (possibly empty) is associated with a <Pron> XML tag, and should be pronounced as specified in the associated SPVSTATE.
SPVA_Bookmark
The associated text fragment is the contents of a bookmark.
SPVA_SpellOut
Each character, other than white space, of the associated text fragment should be expanded as a word (e.g., "word!" would become "w o r d exclamation point").
SPVA_Section
Reserved for future use.
SPVA_ParseUnknownTag
The associated text fragment is an unknown XML tag that may be interpreted (or ignored) by the engine.


SPVALUETYPE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPVALUETYPE

SPVALUETYPE lists flags indicating portions of a recognition result to be removed or eliminated once they are no longer needed.

typedef enum tagSPDISCARDTYPES
{
    SPDF_PROPERTY,
    SPDF_REPLACEMENT,
    SPDF_RULE,
    SPDF_DISPLAYTEXT,
    SPDF_LEXICALFORM,
    SPDF_PRONUNCIATION,
    SPDF_AUDIO,
    SPDF_ALTERNATES,
    SPDF_ALL
} SPVALUETYPE;

Elements

SPDF_PROPERTY
Removes the property tree.
SPDF_REPLACEMENT
Removes the phrase replacement text for inverse text normalization.
SPDF_RULE
Removes the non-top level rule tree information for a phrase.
SPDF_DISPLAYTEXT
Removes the display text.
SPDF_LEXICALFORM
Removes the lexicon from text.
SPDF_PRONUNCIATION
Removes the pronunciation text.
SPDF_AUDIO
Removes the audio data that is attached to a phrase. However, the audio had to be both set and retained.
SPDF_ALTERNATES
Removes the alternate data that is attached to a phrase. Discarding alternates loses the words permanently and may not be retrieved, even with ISpRecoResult::GetAlternates.
SPDF_ALL
Removes all the elements above.


SPVFEATURE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPVFEATURE

SPVFEATURE lists information about the features of the phonemes and visemes.

typedef enum SPVFEATURE
{
    SPVFEATURE_STRESSED,
    SPVFEATURE_EMPHASIS
} SPVFEATURE;

Elements

SPVFEATURE_STRESSED
This flag indicates that the phoneme is stressed relative to the other phonemes within a word.
SPVFEATURE_EMPHASIS
This flag indicates that the word (of which the phoneme is a part) is emphasized relative to the other words within a sentence.


SPVISEMES (Microsoft Speech Platform)

 Microsoft Speech Platform

SPVISEMES

SPVISEMES lists the SAPI 5 Viseme set. This set is based on the Disney 13 Visemes. Examples given are for the SAPI 5 English Phoneme set.

typedef enum SPVISEMES
{
                        // English examples
                        //------------------
    SP_VISEME_0,         // silence
    SP_VISEME_1,        // ae, ax, ah
    SP_VISEME_2,        // aa
    SP_VISEME_3,        // ao
    SP_VISEME_4,        // ey, eh, uh
    SP_VISEME_5,        // er
    SP_VISEME_6,        // y, iy, ih, ix
    SP_VISEME_7,        // w, uw
    SP_VISEME_8,        // ow
    SP_VISEME_9,        // aw
    SP_VISEME_10,       // oy
    SP_VISEME_11,       // ay
    SP_VISEME_12,       // h
    SP_VISEME_13,       // r
    SP_VISEME_14,       // l
    SP_VISEME_15,       // s, z
    SP_VISEME_16,       // sh, ch, jh, zh
    SP_VISEME_17,       // th, dh
    SP_VISEME_18,       // f, v
    SP_VISEME_19,       // d, t, n
    SP_VISEME_20,       // k, g, ng
    SP_VISEME_21       // p, b, m
} SPVISEMES;

Elements

SP_VISEME_0
Silence
SP_VISEME_1
ae, ax, ah
SP_VISEME_2
aa
SP_VISEME_3
ao
SP_VISEME_4
ey, eh, uh
SP_VISEME_5
er
SP_VISEME_6
y, iy, ih, ix
SP_VISEME_7
w, uw
SP_VISEME_8
ow
SP_VISEME_9
aw
SP_VISEME_10
oy
SP_VISEME_11
ay
SP_VISEME_12
h
SP_VISEME_13
r
SP_VISEME_14
l
SP_VISEME_15
s, z
SP_VISEME_16
sh, ch, jh, zh
SP_VISEME_17
th, dh
SP_VISEME_18
f, v
SP_VISEME_19
d, t, n
SP_VISEME_20
k, g, ng
SP_VISEME_21
p, b, m


SPVLIMITS (Microsoft Speech Platform)

 Microsoft Speech Platform

SPVLIMITS

SPVLIMITS lists the minimum and maximum values that SAPI 5 TTS engines are required to support for rate and volume adjustments.

typedef enum SPVLIMITS
{
    SPMIN_VOLUME,
    SPMAX_VOLUME,
    SPMIN_RATE,
    SPMAX_RATE
} SPVLIMITS;

Elements

SPMIN_VOLUME
Value specifying the minimum volume level.
SPMAX_VOLUME
Value specifying the maximum volume level.
SPMIN_RATE
Value specifying the minimum rate level.
SPMAX_RATE
Value specifying the maximum rate level.


SPVPRIORITY (Microsoft Speech Platform)

 Microsoft Speech Platform

SPVPRIORITY

SPVPRIORITY lists the priorities that voices can have. See ISpVoice::SetPriority and ISpVoice::GetPriority for more information.

typedef enum SPVPRIORITY
{
    SPVPRI_NORMAL,
    SPVPRI_ALERT,
    SPVPRI_OVER
} SPVPRIORITY;

Elements

SPVPRI_NORMAL
Normal priority.
SPVPRI_ALERT
Alert priority.
SPVPRI_OVER
Over priority - the voice should mix its audio with all other audio on the system with no synchronization. SPVPRI_OVER voices only mix their audio on Windows 2000.


SPWAVEFORMATTYPE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPWAVEFORMATTYPE

SPWAVEFORMATTYPE is used in the ISpRecognizer::GetFormat method (as SPSTREAMFORMATTYPE) to request either the input format for the original audio source or, the format actually arriving at the speech engine. SAPI may be performing on the fly conversion using an SpStreamFormatConverter in-between which will cause the two formats to differ.

typedef enum SPWAVEFORMATTYPE
{
    SPWF_INPUT,
    SPWF_SRENGINE
} SPSTREAMFORMATTYPE;

Elements

SPWF_INPUT
Request for the original audio input source information.
SPWF_SRENGINE
Request for the SR engine input source information.


SPWORDPRONOUNCEABLE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPWORDPRONOUNCEABLE

See also ISpRecoGrammar::IsPronounceable.

typedef enum SPWORDPRONOUNCEABLE
{
    SPWP_UNKNOWN_WORD_UNPRONOUNCEABLE,
    SPWP_UNKNOWN_WORD_PRONOUNCEABLE,
    SPWP_KNOWN_WORD_PRONOUNCEABLE
} SPWORDPRONOUNCEABLE;

Elements

SPWP_UNKNOWN_WORD_UNPRONOUNCEABLE
Specifies an unrecognized word that does not have an available pronunciation.
SPWP_UNKNOWN_WORD_PRONOUNCEABLE
Specifies an unrecognized word that has an available pronunciation.
SPWP_KNOWN_WORD_PRONOUNCEABLE
Specifies a recognized word that has an available pronunciation.


SPWORDTYPE (Microsoft Speech Platform)

 Microsoft Speech Platform

SPWORDTYPE

SPWORDTYPE lists the change state of a word/pronunciation combination in a lexicon. Using this enumeration, an engine can determine what word pronunciation changes have occurred since it last checked using the ISpLexicon::GetGenerationChange method.

typedef enum SPWORDTYPE
{
   eWORDTYPE_ADDED,
   eWORDTYPE_DELETED
} SPWORDTYPE;

Elements

eWORDTYPE_ADDED
The word has been added to the lexicon.
eWORDTYPE_DELETED
The word has been deleted from the lexicon.


SPXMLRESULTOPTIONS (Microsoft Speech Platform)

Microsoft Speech Platform

SPXMLRESULTOPTIONS

New in SAPI 5.3

SPXMLRESULTOPTIONS is used to designate whether the main result or the alternates are desired when calling the ISpPhrase2::GetXMLResult or ISpXMLRecoResult::GetXMLResult function.

typedef enum SPXMLRESULTOPTIONS
{
    SPXRO_SML,
    SPXRO_Alternates_SML
} SPXMLRESULTOPTIONS;

Elements

SPXRO_SML
Indicates the main result is desired (the default setting).
SPXRO_Alternates_SML
Indicates the alternate results are desired.


Helper Functions (Microsoft Speech Platform)

 Microsoft Speech Platform

Helper Functions

Helper functions are available as a convenience to programming. Since many of the procedures use the same few methods or calls in the same sequence each time, these functions are available to consolidate those standard sequences. In all cases, the functions represent nothing more than the individual steps combined into one call; no additional features have been added or removed. Programmers are free to either use these functions or include the original lines of code. The function name attempts to clearly identify the purpose of the function itself.

The following helper functions are used with the Microsoft Speech Platform.

Token Helpers

  • SpCreateBestObject
  • SpCreateDefaultObjectFromCategoryId
  • SpCreateNewToken (by category ID)
  • SpCreateNewToken (by token ID)
  • SpCreateNewTokenEx (by category ID)
  • SpCreateNewTokenEx (by token ID)
  • SpCreateObjectFromSubToken
  • SpCreateObjectFromToken
  • SpCreateObjectFromTokenId
  • SpCreatePhoneConverter
  • SpEnumTokens
  • SpFindBestToken
  • SpGetCategoryFromId
  • SpGetDefaultTokenFromCategoryId
  • SpGetDefaultTokenIdFromCategoryId
  • SpGetDescription
  • SpGetSubTokenFromToken
  • SpGetTokenFromId
  • SpGetUserDefaultUILanguage
  • SpSetCommonTokenData
  • SpSetDefaultTokenForCategoryId
  • SpSetDefaultTokenIdForCategoryId
  • SpSetDescription

Other Helpers

  • SPFEI
  • SPBindToFile
  • SpClearEvent
  • SpConvertStreamFormatEnum
  • SpEventSerializeSize
  • SpInitEvent

Helper Classes

  • CSpDynamicString
  • CSpStreamFormat
  • CSpEvent


CSpStreamFormat (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat

CSpStreamFormat Methods | Description
CSpStreamFormat | The class constructors.
~CSpStreamFormat | The class destructor.
AssignFormat | Assigns (or copies) the instance's current format to a new format (or a new stream).
Clear | Clears values from an instance.
CopyTo | Copies the instance's wave format to a new stream.
Deserialize | Deserializes a stream and passes back a new stream.
DetachTo | Makes a copy of the instance's stream and frees (or detaches) the instance's stream.
FormatId | Returns the instance's format ID.
IsEqual | Compares a specified stream format and format ID to the instance's format and format ID.
ParamValidateAssignFormat | Validates the format ID and wave format and creates the stream.
ParamValidateCopyTo | Validates the pointers for the format ID and wave format parameters.
Serialize | Serializes the stream.
SerializeSize | Determines the serialized size of the instance's stream.
WaveFormatExPtr | Returns the instance's wave format.


CSpStreamFormat Constructor Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::Constructor

The following methods may be used to construct the instance.

Initializes the class members to null values

CSpStreamFormat( void );

Parameters

None.

Formats the instance into a wave format structure. The new format and format ID are passed back from the class' public members, m_pCoMemWaveFormatEx and m_guidFormatId respectively.

CSpStreamFormat(
   SPSTREAMFORMAT   eFormat,
   HRESULT         *phr
);

Parameters

eFormat
[in] The requested stream format. Must be a valid SPSTREAMFORMAT value of SPSF_8kHz8BitMono or greater.
phr
The return value for the method.

Return values

Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Exceeded available memory.
E_INVALIDARG | Either class member m_guidFormatId or m_pCoMemWaveFormatEx is invalid or bad. Alternatively, the current format is not recognized.
FAILED(hr) | Appropriate error message.

Formats the instance according to the format structure specified.

CSpStreamFormat(
   const WAVEFORMATEX *pWaveFormatEx,
   HRESULT            *phr
);

Parameters

pWaveFormatEx
[in] Address of the WAVEFORMATEX structure containing the wave file format information.
phr
The return value for the method.

Return values

Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Exceeded available memory.


CSpStreamFormat Destructor Method (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::Destructor

CSpStreamFormat::Destructor is the class destructor. CoTaskMemFree() is used to deallocate the instance.

~CSpStreamFormat( void );

Parameters

None.

Return values

No value is returned.


AssignFormat (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::AssignFormat

CSpStreamFormat::AssignFormat assigns (or copies) the instance's current format to a new format (or a new stream).

Converts the instance's stream format into a wave format structure.

HRESULT AssignFormat(
   SPSTREAMFORMAT   eFormat
);

Parameters

eFormat
[in] The requested stream format. Must be a valid SPSTREAMFORMAT value of SPSF_8kHz8BitMono or greater.

Return values

Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Exceeded available memory.
E_INVALIDARG | Either class member m_guidFormatId or m_pCoMemWaveFormatEx is invalid or bad. Alternatively, the current format is not recognized.
FAILED(hr) | Appropriate error message.

Converts instance's stream format into a cached format. Class member m_pCoMemWaveFormatEx will be NULL if an error occurred.

HRESULT AssignFormat(
   ISpStreamFormat  *pStream
);

Parameters

pStream
[in] An ISpStreamFormat object.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | Either class member m_guidFormatId or m_pCoMemWaveFormatEx is invalid or bad.

Converts instance's stream format into the specified wave format. Class member m_guidFormatId will be GUID_NULL if an error occurred.

HRESULT AssignFormat(
   const   WAVEFORMATEX   *pWaveFormatEx
);

Parameters

pWaveFormatEx
[in] Address of the WAVEFORMATEX structure containing the wave file format information.

Return values

Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Exceeded available memory.

Assigns the instance's format according to a reference GUID and a wave format.
HRESULT AssignFormat(
   REFGUID                 rguidFormatId,
   const   WAVEFORMATEX   *pWaveFormatEx
);

Parameters

rguidFormatId
[in] The reference ID. If specified as SPDFID_WaveFormatEx, pWaveFormatEx is a WAVEFORMATEX data structure. Otherwise this is set to GUID_NULL.
pWaveFormatEx
[in] If rguidFormatId is not set to SPDFID_WaveFormatEx, this is passed back as NULL.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | pWaveFormatEx is invalid or bad.
E_OUTOFMEMORY | Exceeded available memory.

Assigns (or copies) the instance's stream to a specific stream.
HRESULT AssignFormat(
   const   CSpStreamFormat & Src
);

Parameters

Src
[out] The stream to copy to.

Return values

Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Exceeded available memory.


Clear (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::Clear

CSpStreamFormat::Clear clears values from an instance.

void Clear( void );

Parameters

None.

Return values

No value is returned.


CopyTo (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::CopyTo

CSpStreamFormat::CopyTo copies the instance's wave format to a new stream.

HRESULT CopyTo(
   GUID            *pFormatId,
   WAVEFORMATEX   **ppCoMemWFEX
   );

Parameters

pFormatId
The new format ID based on the class member m_guidFormatId's ID. If class member m_pCoMemWaveFormatEx is invalid, pFormatId is set to NULL.
ppCoMemWFEX
The new wave format. If ppCoMemWFEX could not be successfully created, pFormatId is set to zero.

This method copies the instance's stream to an existing stream.
HRESULT CopyTo(
   wCSpStreamFormat &Other
);

Parameters

Other
The existing stream to copy to. The stream is freed using CoTaskMemFree() first and the instance is then copied to it.

Return values

The return values are the same for both methods.
Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Exceeded available memory.


Deserialize (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::Deserialize

CSpStreamFormat::Deserialize deserializes a stream and passes back a new stream.

HRESULT Deserialize(
   const   BYTE   *pBuffer,
   ULONG          *pcbUsed
);

Parameters

pBuffer
[in out] Buffer containing the serialized stream. After successfully completing the methods, pBuffer will also be set to class member m_pCoMemWaveFormatEx. If unsuccessful, class member m_guidFormatId is set to GUID_NULL.
pcbUsed
The number of bytes used for the stream.

Return values

Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Exceeded available memory.


DetachTo (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::DetachTo

CSpStreamFormat::DetachTo copies the instance's stream and frees (or detaches) the instance's stream. The instance's stream is set to NULL and the format ID is set to zero.

Copies the instance's stream to another existing stream.

void DetachTo(
   CSpStreamFormat   &Other
);

Parameters

Other
The existing stream to copy to. The stream is freed using CoTaskMemFree() first and the instance is then copied to it.

Makes a copy of the instance's stream with the specified format ID and wave format.

void DetachTo(
   GUID            *pFormatId,
   WAVEFORMATEX   **ppCoMemWaveFormatEx
   )

Parameters

pFormatId
The new format ID based on the class member m_guidFormatId.
ppCoMemWaveFormatEx
The new wave format based on the class member m_pCoMemWaveFormatEx.

Return values

Neither method returns a value.


FormatId (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::FormatId

CSpStreamFormat::FormatId returns the instance's format ID.

const GUID& FormatId( void );

Parameters

None.

Return values

The format ID of the current instance is returned by the class member m_guidFormatId.


IsEqual (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::IsEqual

CSpStreamFormat::IsEqual compares a specified stream format and format ID to the instance's format and format ID.

BOOL IsEqual(
   REFGUID                 rguidFormatId,
   const   WAVEFORMATEX   *pwfex
)

Parameters

rguidFormatId
The format ID of the stream to compare with.
pwfex
The wave format of the stream to compare with.

Return values

Value | Description
TRUE | The two streams are identical.
FALSE | The reference IDs of the streams are not the same, or the streams have different contents.


ParamValidateAssignFormat (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::ParamValidateAssignFormat

CSpStreamFormat::ParamValidateAssignFormat validates the format ID and wave format. If successful, creates the stream using AssignFormat.

HRESULT ParamValidateAssignFormat(
   REFGUID               rguidFormatId,
   const WAVEFORMATEX   *pWaveFormatEx,
   BOOL                  fRequireWaveFormat = FALSE
)

Parameters

rguidFormatId
The reference format ID of the requesting stream.
pWaveFormatEx
The wave format of the requesting stream.
fRequireWaveFormat
Optional Boolean indicating to create the stream only if the wave format is of a standard type. It is FALSE by default and may be omitted. TRUE, allows the creation of custom formats.

Return values

Value | Description
E_INVALIDARG | At least one of pWaveFormatEx is NULL, pWaveFormatEx is bad or invalid, rguidFormatId is not SPDFID_WaveFormatEx, or pWaveFormatEx is a non-standard format and is disallowed by fRequireWaveFormat.


ParamValidateCopyTo (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::ParamValidateCopyTo

CSpStreamFormat::ParamValidateCopyTo validates the pointers for the format ID and wave format parameters. If successful, copies the stream using CopyTo.

HRESULT ParamValidateCopyTo(
   GUID            *pFormatId,
   WAVEFORMATEX   **ppCoMemWFEX
   );

Parameters

pFormatId
The proposed pointer for the format ID.
ppCoMemWFEX
The proposed pointer for the stream.

Return values

Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Exceeded available memory.
E_POINTER | Either pFormatId or ppCoMemWFEX is invalid or bad.


Serialize (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::Serialize

CSpStreamFormat::Serialize serializes the stream.

ULONG Serialize(
   BYTE   *pBuffer
   );

Parameters

pBuffer
The buffer accepting the serialized results.

Return values

The length, in bytes, of the serialized stream and stream contents. Class member m_pCoMemWaveFormatEx may be NULL and therefore contributes zero bytes to the total length.


SerializeSize (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::SerializeSize

CSpStreamFormat::SerializeSize determines the serialized size of the instance's stream.

ULONG SerializeSize( void );

Parameters

None.

Return values

Returns the serialized size of the stream, in bytes.


WaveFormatExPtr (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpStreamFormat::WaveFormatExPtr

CSpStreamFormat::WaveFormatExPtr returns the instance's wave format.

const WAVEFORMATEX* WaveFormatExPtr( void );

Parameters

None.

Return values

The wave format of instance is returned by the class member m_pCoMemWaveFormatEx.


CSpDynamicString (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString

The following methods are available.

ISpDataKey Methods | Description
CSpDynamicString | The class constructors.
~CSpDynamicString | The class destructor.
Append | Appends a string or strings to the current instance.
Attach | Attaches or assigns a string to the instance.
Clear | Clears the text from an instance.
ClearAndGrowTo | Clears the instance and reallocates it.
Compact | Compacts the instance by reallocating it.
Copy | Makes a copy of the instance.
CopyToBSTR | Allocates a system BSTR.
Detach | Detaches a string from the instance.
Length | Returns the length of the instance.
LTrim | Trims the white space starting from the left.
RTrim | Trims the white space starting from the right.
TrimBoth | Trims the white space starting from both the right and left sides.
TrimToSize | Truncates the instance to a specific size.


CSpDynamicString Constructor Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::Constructor

The following methods may be used to construct the instance.

Creates and sets the instance to NULL.
void CSpDynamicString( void )

Parameters

None. Initializes string to NULL.

Creates and allocates an instance of the specified number of WCHARs.
void CSpDynamicString(
   ULONG   cchReserve
);

Parameters

cchReserve
[in] The length of the string to allocate.

Creates and initializes and copies the source string into it.
void CSpDynamicString(
   const WCHAR  *pSrc
)

Parameters

cchReserve
[in] Initializes the string to pSrc.

Creates and initializes and copies the source string into it.
void CSpDynamicString(
   const char  *pSrc
)

Parameters

pSrc
[in] Initializes the string to pSrc.

Makes a copy of the CSpDynamicString class string. The current instance is CoTaskMemFree() first, if needed.
void CSpDynamicString(
   const CSpDynamicString  &src
)

Parameters

src
[in] Initializes the string by copying the string of src.

Allocates an instance and copies the reference GUID into it.
void CSpDynamicString(
   REFGUID   rguid
)
Parameters
rguid
[in] Initializes the string from the CLSID of rguid.


CSpDynamicString Destructor Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::Destructor

CSpDynamicString::Destructor is the class destructor. CoTaskMemFree() is used to deallocate the instance.

~CSpDynamicString( void )

Parameters

None


CSpDynamicString Append Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::Append

The following methods append null-terminated strings together.

Appends the null-terminated source string to the end of the instance and returns the resulting string.
WCHAR* Append(
   const WCHAR  *pszSrc
)

Parameters

pszSrc
[in] The null-terminated source string to append.

Appends the null-terminated source string to the end of the instance and returns the resulting string. The size to append is specified.
WCHAR* Append(
   const WCHAR  *pszSrc,
   const ULONG   lenSrc
)

Parameters

pszSrc
[in] The null-terminated source string to append.
lenSrc
[in] Size, in WCHARs, to append.

Appends up to two null-terminated source strings to the end of the instance and returns the resulting string. At least one of the to strings must be non-NULL.
WCHAR* Append2(
   const WCHAR  *pszSrc1,
   const WCHAR  *pszSrc2
)

Parameters

pszSrc1
[in] The first source string to append.
pszSrc2
[in] The second source string to append.


CSpDynamicString Attach Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::Attach

CSpDynamicString::Attach attaches or assigns a string to the instance.

void Attach
   WCHAR  *pszSrc
)

Parameters

pszSrc
[in] The source string to attach or assign.


CSpDynamicString Clear Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::Clear

CSpDynamicString::Clear clears the text from an instance. The instance is set to NULL.

void Clear( void );

Parameters

None


CSpDynamicString ClearAndGrowTo Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::ClearAndGrowTo

CSpDynamicString::ClearAndGrowTo clears the existing instance and reallocates it to the specified size. The subsequent instance is returned.

WCHAR* ClearAndGrowTo(
   ULONG   cch
)

Parameters

cch
[in] The new size of the instance.


CSpDynamicString Compact Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::Compact

CSpDynamicString::Compact compacts the instance by reallocating it to the actual number of characters it currently contains. The subsequent instance is returned.

WCHAR* Compact( void )

Parameters

None


CSpDynamicString Copy Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::Copy

CSpDynamicString::Copy copies the instance.

WCHAR* Copy( void );

Parameters

None


CSpDynamicString CopyToBSTR Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::CopyToBSTR

CSpDynamicString::CopyToBSTR allocates a system BSTR.

HRESULT CopyToBSTR(
   BSTR  *pbstr
)

Parameters

pbstr
[in] The source string to allocate.


CSpDynamicString Detach Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::Detach

CSpDynamicString::Detach detaches and returns a string from the instance. The instance is set to NULL.

WCHAR* Detach( void );

Parameters

None


CSpDynamicString Length Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::Length

CSpDynamicString::Length returns the length of the string instance. If the instance is NULL, zero is returned.

Length( void )

Parameters

None


CSpDynamicString LTrim Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::LTrim

CSpDynamicString::LTrim trims the white space starting from the left. The subsequent instance is returned.

WCHAR* LTrim( void );

Parameters

None


CSpDynamicString RTrim Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::RTrim

CSpDynamicString::RTrim trims the white space starting from the right. The subsequent instance is returned.

WCHAR* RTrim( void );

Parameters

None


CSpDynamicString TrimBoth Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::TrimBoth

CSpDynamicString::TrimBoth trims the white space starting from both the right and left sides. The subsequent instance is returned.

WCHAR* TrimBoth( void );

Parameters

None


CSpDynamicString TrimToSize Methods (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpDynamicString::TrimToSize

CSpDynamicString::TrimToSize truncates the instance to a specific size.

void TrimToSize(
   ULONG  *ulNumChars
)

Parameters

ulNumChars
[in] The new size of the instance. The value must be less than less than or equal to the current size.


CSpEvent (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent

CSpEvent Methods | Description
CSpEvent | The class constructor.
~CSpEvent | The class destructor.
Clear | Clears an event instance.
AddrOf | Returns the address of the event instance.
CopyTo | Copies the event instance and sets the lparam accordingly.
GetFrom | Clears the current instance and retrieves the next event from the event queue.
CopyFrom | Clears the current instance and copies the next event in the event queue to this instance.
Detach | Clears the current instance and optionally makes a copy.
SerializeSize | Calculates the required size of a buffer to serialize an event.
Serialize | Copies event instance and then serializes the new instance.
Deserialize | Sets the current instance to the deserialized version of the specified event.
Phoneme | Returns the event as a cast type of SPPHONEID.
Viseme | Returns the event as a cast type of SPEI_VISEME.
InputWordPos | Returns the event as a cast type of ULONG.
InputWordLen | Returns the event as a cast type of ULONG.
InputSentPos | Returns the event as a cast type of ULONG.
InputSentLen | Returns the event as a cast type of ULONG.
ObjectToken | Returns the event as a cast type of ISpObjectToken pointer.
VoiceToken | Returns the event as a cast type of SpObjectToken pointer.
PersistVoiceChange | Returns the state of the voice change.
Object | Returns the event as a cast type of an IUnknown pointer.
RecoResult | Returns the event as a cast type of an ISpRecoResult pointer.
IsPaused | Returns the pause state.
IsEmulated | Returns the emulation state.
String | Returns the string from the event's lParam.
BookmarkName | Returns the bookmark string from the event's lParam.
RequestTypeOfUI | Returns the IU type string from the event's lParam.
RecoState | Returns the event's recognition state as a cast type of SPRECOSTATE.
PropertyName | Returns the property name string from the event's lParam.
PropertyNumValue | Returns the property number value as cast to LONG.
PropertyStringValue | Returns the property string value from the event's lParam.
Interference | Returns the event's interference value from lParam and cast SPINTERFERENCE.
EndStreamResult | Returns the event's end stream result from the event's lParam.
InputStreamReleased | Returns the state from releasing the stream.


CSpEvent (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::Constructor

CSpEvent::Constructor is used to construct the instance. The SPEVENT instance is cleared to zero.

CSpEvent( void );

Parameters

None.

Return values

None.


~CSpEvent (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::Destructor

CSpEvent::Destructor is the class destructor and is used to clear an event instance. This method is identical to CSpEvent Clear.

~CSpEvent( void );

Parameters

None.

Return values

None.

See Also

SpClearEvent


AddOf (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::AddrOf

CSpEvent::AddrOf returns the address of the event instance. No ASSERT is made in the case of an error. For additional validation, call GetFrom.

CSpEvent*   AddrOf (void)

Parameters

None.

Return values

Returns the address of the event instance.


BookmarkName (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::BookmarkName

CSpEvent::BookmarkName returns the bookmark string from the event's lParam. The caller must make sure the event ID is SPEI_TTS_BOOKMARK.

const WCHAR* BookmarkName( void ) const;

Parameters

None.

Return values

Returns the bookmark string from the event's lParam.


Clear (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::Clear

CSpEvent::Clear clears an event instance. This method is identical to CSpEvent ~CSpEvent.

void Clear( void );

Parameters

None.

Return values

None.

See Also

SpClearEvent


CopyFrom (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::CopyFrom

CSpEvent::CopyFrom clears the current instance and copies the next event in the event queue to this instance.

HRESULT CopyFrom(
   const SPEVENT   *pSrcEvent
)

Parameters

pSrcEvent
[ in ] The event of which to copy from.

Return values

Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Exceeded available memory.


CopyTo (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::CopyTo

CSpEvent::CopyTo copies the event instance and sets the lparam accordingly.

HRESULT CopyTo(
   SPEVENT   *pDestEvent
);

Parameters

pDestEvent
The event to copy to. The member elParamType is copied according to the follow parameter value:
SPET_LPARAM_IS_POINTER copies wparam into lparam if lparam is currently valid. On error, pDestEvent->eEventId is set to SPEI_UNDEFINED.
SPET_LPARAM_IS_STRING copies lparam into lparam if it is currently valid. On error, pDestEvent->eEventId is set to SPEI_UNDEFINED.
SPET_LPARAM_IS_TOKEN or SPET_LPARAM_IS_OBJECT calls AddRef() for lparam.

Return values

Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Exceeded available memory.


Deserialize (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::Deserialize

CSpEvent::Deserialize sets the current instance to the deserialized version of the specified event.

The current instance is cleared first. The original event is not modified.

template <class T>
HRESULT Deserialize(
   const   T   *pSerEvent,
   ULONG       *pcbUsed = NULL
   );

Parameters

pSerEvent
The serialized event.
pcbUsed
Optional parameter passing back the number of bytes of the instance. The default NULL does not pass back any value; TRUE, does.

Return values

Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Exceeded available memory.


Detach (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::Detach

CSpEvent::Detach clears the current instance and optionally makes a copy.

void  Detach(
   SPEVENT   *pDestEvent = NULL
);

Parameters

pDestEvent
The event structure to copy to. If NULL, no copy is made before clearing the instance.

Return values

None.


EndStreamResult (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::EndStreamResult

CSpEvent::EndStreamResult returns the end stream result from the event's lParam. The caller must make sure the event ID is SPEI_END_SR_STREAM.

HRESULT EndStreamResult( void ) const;

Parameters

None.

Return values

Returns the end stream result from the event's lParam.


GetFrom (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::GetFrom

CSpEvent::GetFrom clears the current instance and retrieves the next event from the event queue.

HRESULT GetFrom(
   ISpEventSource   *pEventSrc
)

Parameters

pEventSrc
The event object from which to get the next event.

Return values

Value | Description
S_OK | Function completed successfully and all requested events were returned.
S_FALSE | Success, but less than the requested amount of events were returned.
E_POINTER | pEventArray is invalid.
FAILED(hr) | Appropriate error message.


InputSentLen (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::InputSentLen

CSpEvent::InputSentLen returns the event as a cast type of ULONG. The caller must make sure the event ID is SPEI_SENTENCE_BOUNDARY.

ULONG   InputSentLen( void ) const;

Parameters

None.

Return values

The event cast type of ULONG.


InputSentPos (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::InputSentPos

CSpEvent::InputSentPos returns the event as a cast type of ULONG. The caller must make sure the event ID is SPEI_SENTENCE_BOUNDARY.

ULONG   InputSentPos( void ) const;

Parameters

None.

Return values

The event cast type of ULONG.


InputStreamReleased (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::InputStreamReleased

CSpEvent::InputStreamReleased returns the state from releasing the stream. The caller must make sure the event ID is SPEI_END_SR_STREAM.

See also SPENDSRSTREAMFLAGS for more information.

BOOL InputStreamReleased( void ) const;

Parameters

None.

Return values

Returns the state from releasing the stream. TRUE indicates the stream was successfully released; FALSE otherwise.


InputWordLen (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::InputWordLen

CSpEvent::InputWordLen returns the event as a cast type of ULONG. The caller must make sure the event ID is SPEI_WORD_BOUNDARY.

ULONG InputWordLen( void ) const;

Parameters

None.

Return values

The event cast type of ULONG.


InputWordPos (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::InputWordPos

CSpEvent::InputWordPos returns the event as a cast type of ULONG. The caller must make sure the event ID is SPEI_WORD_BOUNDARY.

ULONG   InputWordPos( void ) const;

Parameters

None.

Return values

The event cast type of ULONG.


Interference (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::Interference

CSpEvent::Interference returns the event's interference value from lParam and cast SPINTERFERENCE. The caller must make sure the event ID is SPEI_INTERFERENCE.

SPINTERFERENCE Interference( void ) const;

Parameters

None.

Return values

Returns the interference value as cast SPINTERFERENCE.


IsEmulated (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::IsEmulated

CSpEvent::IsEmulated returns the emulation state. The caller must make sure the event ID is SPEI_RECOGNITION.

BOOL IsEmulated( void );

Parameters

None.

Return values

The event cast type of SPPHONEID.


IsPaused (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::IsPaused

CSpEvent::IsPaused returns the pause state. The caller must make sure the event ID is either SPEI_RECOGNITION or SPEI_SR_BOOKMARK.

BOOL IsPaused( void )

Parameters

None.

Return values

Returns the pause state.


Object (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::Object

CSpEvent::Object returns the event as a cast type of an IUnknown pointer. The caller must make sure the event ID is SPET_LPARAM_IS_OBJECT.

IUnknown* Object( void ) const;

Parameters

None.

Return values

The event cast type of an IUnknown pointer.


ObjectToken (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::ObjectToken

CSpEvent::ObjectToken returns the event as a cast type of ISpObjectToken pointer. The caller must make sure the event type is SPET_LPARAM_IS_TOKEN.

ISpObjectToken*   ObjectToken( void ) const;

Parameters

None.

Return values

The event cast type of ISpObjectToken pointer.


PersistVoiceChange (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::PersistVoiceChange

CSpEvent::PersistVoiceChange returns the state of the voice change. The caller must make sure the event ID is SPEI_VOICE_CHANGE.

BOOL PersistVoiceChange( void ) const;

Parameters

None.

Return values

The event cast type of BOOL.


Phoneme (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::Phoneme

CSpEvent::Phoneme returns the event as a cast type of SPPHONEID. The caller must make sure the event ID is SPEI_PHONEME.

typedef WCHAR SPPHONEID;

Parameters

None.

Return values

The event cast type of SPPHONEID.


PropertyName (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::PropertyName

CSpEvent::PropertyName returns the property name string from the event's lParam. The caller must make sure the event ID is either SPEI_PROPERTY_NUM_CHANGE and event type is SPET_LPARAM_IS_STRING, or event ID is SPEI_PROPERTY_STRING_CHANGE and event type is SPET_LPARAM_IS_POINTER.

const WCHAR* PropertyName( void ) const;

Parameters

None.

Return values

Returns the property name string from the event's lParam.


PropertyNumValue (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::PropertyNumValue

CSpEvent::PropertyNumValue returns the property number value as cast to LONG. The caller must make sure the event ID is SPEI_PROPERTY_NUM_CHANGE.

const LONG PropertyNumValue( void ) const;

Parameters

None.

Return values

Returns the property number value as cast to LONG.


PropertyStringValue (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::PropertyStringValue

CSpEvent::PropertyStringValue returns the property string value from the event's lParam. The caller must make sure the event ID is SPEI_PROPERTY_STRING_CHANGE.

const WCHAR* PropertyStringValue( void ) const;

Parameters

None.

Return values

Returns the property string value from the event's lParam.


RecoResult (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::RecoResult

CSpEvent::RecoResult returns the event as a cast type of an ISpRecoResult pointer. The caller must make sure the event ID is SPEI_RECOGNITION, SPEI_FALSE_RECOGNITION, or SPEI_HYPOTHESIS.

ISpRecoResult* RecoResult( void ) const;

Parameters

None.

Return values

The event cast type of an ISpRecoResult pointer.


RecoState (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::RecoState

CSpEvent::RecoState returns the event's recognition state as a cast type of SPRECOSTATE. The caller must make sure the event ID is SPEI_RECO_STATE_CHANGE.

SPRECOSTATE RecoState( void ) const;

Parameters

None.

Return values

Returns the event's recognition state as a cast type of SPRECOSTATE.


RequestTypeOfUI (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::RequestTypeOfUI

CSpEvent::RequestTypeOfUI returns the UI type string from the event's lParam. The caller must make sure the event ID is SPEI_REQUEST_UI.

const WCHAR* RequestTypeOfUI( void ) const;

Parameters

None.

Return values

Returns the UI type string from the event's lParam.


Serialize (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::Serialize

CSpEvent::Serialize copies an event instance and then serializes the new instance. The new instance must be based on SPSERIALIZEDEVENT or SPSERIALIZEDEVENT64

void Serialize(
    T    *pSerEvent
);

Parameters

pSerEvent
[ out ] The event for the passed back serialization. Member elParamType must not be SPET_LPARAM_IS_OBJECT.

Return values

None, however member SerializedlParam is set to the size of the serialized structure.

Copies an existing event instance and then serializes the new instance.

HRESULT Serialize(
   T      **ppCoMemSerEvent,
   ULONG   *pcbSerEvent
   );

Parameters

ppCoMemSerEvent
[ out ] The event for the passed back serialization. It is allocated and serialized. When no longer required, it must be manually freed with CoTaskMemFree().
pcbSerEvent
[ out ] The number of bytes allocated for the serialization. On an error, it will be zero.

Return values

Value | Description
S_OK | Serialization completed successfully.
E_OUTOFMEMORY | Exceeded available memory.


SerializeSize (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::SerializeSize

CSpEvent::SerializeSize calculates the required size of a buffer to serialize an event. The instance must be either SPSERIALIZEDEVENT or SPSERIALIZEDEVENT64.

ULONG SerializeSize( void );

Parameters

None.

Return values

Size, in bytes, required to serialize the event.

Remarks

Due to a compiler issue, CSpEvent::SerializeSize may not be used with Visual Studio 6. Use SpEventSerializeSize instead.


String (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::String

CSpEvent::String returns the string from the event's lParam. The caller must make sure the event type is SPET_LPARAM_IS_STRING.

const WCHAR* String( void ) const;

Parameters

None.

Return values

Returns the string from the event's lParam.


Viseme (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::Viseme

CSpEvent::Viseme returns the event as a cast type of SPEI_VISEME. The caller must make sure the event ID is SPEI_VISEME.

SPVISEMES   Viseme( void ) const;

Parameters

None.

Return values

The event cast type of SPVISEMES.


VoiceToken (Microsoft Speech Platform)

 Microsoft Speech Platform

CSpEvent::VoiceToken

CSpEvent::VoiceToken returns the event as a cast type of ISpObjectToken pointer. The caller must make sure the event ID is SPEI_VOICE_CHANGE. This is an additional check for the helper ObjectToken.

ISpObjectToken*   VoiceToken( void ) const;

Parameters

None.

Return values

The event cast type of ISpObjectToken pointer.


Helper SpCreateBestObject (Microsoft Speech Platform)

 Microsoft Speech Platform

SpCreateBestObject

SpCreateBestObject creates an object from tokens that best match a set of criteria from required and optional attributes.

Found in: sphelper.h

SpCreateBestObject(
   const WCHAR   *pszCategoryId,
   const WCHAR   *pszReqAttribs,
   const WCHAR   *pszOptAttribs,
   T            **ppObject,
   IUnknown      *IUnknown = NULL,
   DWORD          dwClsCtxt = CLSCTX_ALL,
);

Parameters

pszCategoryId
[in] The null-terminated string category ID on which to base the new token.
pszReqAttribs
[in] The null-terminated string of required attributes for the token.
pszOptAttribs
[in] The null-terminated string of optional attributes for the token.
ppObject
[out, iid_is(riid)] Address of pointer variable that receives the interface pointer requested in riid. Upon successful return, ppObject contains the requested interface pointer. If the object does not support the interface specified in riid, the implementation must set ppObject to NULL.
IUnknown
[in] Optional parameter used for creating aggregate objects. pUnkOuter is the data for the object. If not specified, the value defaults to NULL.
dwClsCtxt
[in] Context in which the code that manages the newly created object will run. It should be one of the following values. If not specified, the value defaults to CLSCTX_ALL.
  • CLSCTX_INPROC_SERVER
  • CLSCTX_INPROC_HANDLER
  • CLSCTX_LOCAL_SERVER
  • CLSCTX_REMOTE_SERVER

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpCreateDefaultObjectFromCategoryId (Microsoft Speech Platform)

 Microsoft Speech Platform

SpCreateDefaultObjectFromCategoryId

SpCreateDefaultObjectFromCategoryId creates the object instance from the default object token of a specified category.

Found in: sphelper.h

SpCreateDefaultObjectFromCategoryId(
   const WCHAR   *pszCategoryId,
   T             **ppObject,
   IUnknown      *pUnkOuter = NULL,
   DWORD         dwClsCtxt = CLSCTX_ALL
);

Parameters

pszCategoryId
[in] The type of object token to create.
ppObject
[out] The object being created.
pUnkOuter
[in] Optional parameter used for creating aggregate objects. pUnkOuter is the data for the object. If not specified, the value defaults to NULL.
dwClsCtxt
[in] The type of aggregate object being created. If pUnkOuter is not NULL, this must be supplied. If not specified otherwise, the value defaults to all object types.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.

Example

// Declare local identifiers:
HRESULT               hr = S_OK;
CComPtr<ISpAudio>     cpAudio;

hr = SpCreateDefaultObjectFromCategoryId(SPCAT_AUDIOIN, &cpAudio);

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


Helper SpCreateNewToken (Microsoft Speech Platform)

 Microsoft Speech Platform

SpCreateNewToken (by CategoryId)

SpCreateNewToken creates a token coercively. The token is created with the specified name, if provided. Otherwise it will automatically generate both a key name and name.

Found in: sphelper.h

SpCreateNewToken(
   const WCHAR       *pszCategoryId,
   const WCHAR       *pszTokenKeyName,
   ISpObjectToken    **ppToken
);

Parameters

pszCategoryId
[in] The null-terminated string indicating the category ID.
pszTokenKeyName
[in out] The token name being created. If NULL, a unique token key name will be generated. If a name is provided it will append Tokens before it.
ppToken
[out] The newly created token. The token will be created, if one does not currently exist.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.

Example

The following code snippet illustrates the use of the SPCAT_RECOPROFILE category.

// Declare local identifiers:
HRESULT                     hr = S_OK;
CComPtr<ISpObjectToken>     cpObjectToken;

// Create a new recognition profile.
hr = SpCreateNewToken(SPCAT_RECOPROFILES, NULL, &cpObjectToken);

if (SUCCEEDED(hr))
{
   // Do stuff here.
}


Helper SpCreateNewToken (Microsoft Speech Platform)

 Microsoft Speech Platform

SpCreateNewToken (by TokenId)

SpCreateNewToken creates a token forcefully.

Found in: sphelper.h

inline HRESULT SpCreateNewToken(
   const WCHAR       *pszTokenId,
   ISpObjectToken   **ppToken
);

Parameters

pszTokenId
[in] The null-terminated string indicating the token IDw.
ppToken
[out] The token being created. It is created with CoCreateInstance and must be manually freed when no longer required.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpCreateNewTokenEx (Microsoft Speech Platform)

 Microsoft Speech Platform

SpCreateNewTokenEx (by CategoryId)

SpCreateNewTokenEx creates a new token using the category ID and a token name. It subsequently completes the information with the helper function SpSetCommonTokenData.

Found in: sphelper.h

SpCreateNewTokenEx(
   const WCHAR     *pszCategoryId,
   const WCHAR     *pszTokenKeyName,
   const CLSID     *pclsid,
   const WCHAR     *pszLangIndependentName,
   LANGID           langid,
   const WCHAR     *pszLangDependentName,
   ISpObjectToken **ppToken,
   ISpDataKey     **ppDataKeyAttribs
);

Parameters

pszCategoryId
[in] The null-terminated string indicating the category ID.
pszTokenKeyName
[in out] The token name being created. If NULL, a unique token key name will be generated. If a name is provided it will append "Tokens" before it.
pclsid
[in] Sets the token's CLSID, if specified.
pszLangIndependentName
[in] Sets the null-terminated token language dependent name.
langid
[in] The language ID of the word. May be zero to indicate the word can be of any LANGID.
pszLangDependentName
[in] Sets the null-terminated token language dependent name.
ppToken
[out] The newly created token. The token is created if it currently does not exist.
ppDataKeyAttribs
[in] Opens the attributes key. The key is created if it does not currently exist. May be NULL if not needed.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpCreateNewTokenEx (Microsoft Speech Platform)

 Microsoft Speech Platform

SpCreateNewTokenEx (by TokenId)

SpCreateNewTokenEx creates a new token using the category ID and a token name. It subsequently completes the information with the helper function SpSetCommonTokenData.

Found in: sphelper.h

SpCreateNewTokenEx(
   const WCHAR     *pszTokenId,
   const CLSID     *pclsid,
   const WCHAR     *pszLangIndependentName,
   LANGID           langid,
   const WCHAR     *pszLangDependentName,
   ISpObjectToken **ppToken,
   ISpDataKey     **ppDataKeyAttribs
);

Parameters

pszTokenId
[in] The null-terminated string indicating the token ID.
pclsid
[in] Sets the token's CLSID, if specified.
pszLangIndependentName
[in] Sets the null-terminated token language dependent name.
langid
[in] The language ID of the word. May be zero to indicate that the word can be of any LANGID.
pszLangDependentName
[in] Sets the null-terminated token language dependent name.
ppToken
[out] The newly created token. The token is created if it does not currently exist.
ppDataKeyAttribs
[in] Opens the attributes key. The key is created if it does not currently exist. May be NULL if not needed.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpCreateObjectFromSubToken (Microsoft Speech Platform)

 Microsoft Speech Platform

SpCreateObjectFromSubToken

SpCreateObjectFromSubToken creates an object from a specified subtoken.

Found in: spddkhlp.h

SpCreateObjectFromSubToken(
   ISpObjectToken   *pToken,
   const WCHAR      *pszSubKeyName,
   T               **ppObject,
   IUnknown          pUnkOuter = NULL,
   DWORD            *dwClsCtxt = CLSCTX_ALL
);

Parameters

pToken
[in] Address of a pointer to an ISpObjectToken object containing the information associated with the tokens being added.
pszSubKeyName
[in] Address of a null-terminated string specifying the name of the subkey of the pToken's corresponding datakey to open.
ppObject
[out, iid_is(riid)] Address of pointer variable that receives the interface pointer requested in riid. Upon successful return, ppObject contains the requested interface pointer. If the object does not support the interface specified in riid, the implementation must set ppObject to NULL.
IUnknown
[in] Optional parameter used for creating aggregate objects. pUnkOuter is the data for the object. If not specified, the value defaults to NULL.
dwClsCtxt
[in] Context in which the code that manages the newly created object will run. It should be one of the following values. If not specified, the value defaults to CLSCTX_ALL.
  • CLSCTX_INPROC_SERVER
  • CLSCTX_INPROC_HANDLER
  • CLSCTX_LOCAL_SERVER
  • CLSCTX_REMOTE_SERVER

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpCreateObjectFromToken (Microsoft Speech Platform)

 Microsoft Speech Platform

SpCreateObjectFromToken

SpCreateObjectFromToken creates an object instance from a specified object token.

Found in: sphelper.h

SpCreateObjectFromToken(
   ISpObjectToken  *pToken,
   T              **ppObject,
   IUnknown        *pUnkOuter = NULL,
   DWORD            dwClsCtxt = CLSCTX_ALL
);

Parameters

pToken
[in] The type of object token to create.
ppObject
[out] the object instance being created.
pUnkOuter
[in] Optional parameter used for creating aggregate objects. pUnkOuter is the data for the object. If not specified, the value defaults to NULL.
dwClsCtxt
[in] The type of aggregate object being created. If pUnkOuter is not NULL, this must be supplied. If not specified otherwise, the value defaults to all object types.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpCreateObjectFromTokenId (Microsoft Speech Platform)

 Microsoft Speech Platform

SpCreateObjectFromTokenId

SpCreateObjectFromTokenId creates an object instance from a specified object token ID.

Found in: sphelper.h

SpCreateObjectFromTokenId(
   const WCHAR   *pszTokenId,
   T            **ppObject,
   IUnknown      *pUnkOuter = NULL,
   DWORD          dwClsCtxt = CLSCTX_ALL
);

Parameters

pszTokenId
[in] The type of object token to create.
ppObject
[out] The object being created.
pUnkOuter
[in] Optional parameter used for creating aggregate objects. pUnkOuter is the data for the object. If not specified, the value defaults to NULL.
dwClsCtxt
[in] The type of aggregate object being created. If pUnkOuter is not NULL, this must be supplied. If not specified otherwise, the value defaults to all object types.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpCreatePhoneConverter (Microsoft Speech Platform)

 Microsoft Speech Platform

SpCreatePhoneConverter

SpCreatePhoneConverter creates a directly converted phone. Calls the helper function SpCreateBestObject with the category of SPCAT_PHONECONVERTERS.

Found in: sphelper.h

SpCreatePhoneConverter(
   LANGID            *langid,
   const WCHAR       *pszReqAttribs,
   const WCHAR       *pszOptAttribs,
   ISpPhoneConverter  ppPhoneConverter
);

Parameters

langid
[in] The language ID of the word. May not be NULL or zero.
pszReqAttribs
[in] The null-terminated string of required attributes for the token.
pszOptAttribs
[in] The null-terminated string of optional attributes for the token.
ppPhoneConverter
[out] The converted phone interface.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | langid equals zero.
FAILED (hr) | Appropriate error message.


Helper SpEnumTokens (Microsoft Speech Platform)

 Microsoft Speech Platform

SpEnumTokens

SpEnumTokens enumerates the tokens for the specified category.

Found in: sphelper.h

inline HRESULT SpEnumTokens(
   const WCHAR            *pszCategoryId,
   const WCHAR            *pszReqAttribs,
   const WCHAR            *pszOptAttribs,
   IEnumSpObjectTokens   **ppEnum
);

Parameters

pszCategoryId
[in] The null-terminated string category ID on which to base the enumerations.
pszReqAttribs
[in] The null-terminated string of the required attributes for the token.
pszOptAttribs
[in] The null-terminated string of the optional attributes for the token. The order in which the tokens are listed in ppEnum is based on the order that they match pszOptAttribs.
ppEnum
[out] The enumerated list of tokens found.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpFindBestToken (Microsoft Speech Platform)

 Microsoft Speech Platform

SpFindBestToken

SpFindBestToken enumerates the token category and finds the single best match (if any) based on the required and optional attributes.

Found in: sphelper.h

SpFindBestToken(
   const WCHAR       *pszCategoryId,
   const WCHAR       *pszReqAttribs,
   const WCHAR       *pszOptAttribs,
   ISpObjectToken   **ppObjectToken
);

Parameters

pszCategoryId
[in] The null-terminated string category ID on which to base the enumerations.
pszReqAttribs
[in] The null-terminated string of the required attributes for the token.
pszOptAttribs
[in] The null-terminated string of the optional attributes for the token. The order in which the tokens are listed in ppObjectToken is based on the order they match pszOptAttribs.
ppObjectToken
[out] The single best matched token found.

Return values

Value | Description
S_OK | Function completed successfully.
SPERR_NOT_FOUND | No items match the given attributes.
FAILED (hr) | Appropriate error message.


Helper SpGetCategoryFromId (Microsoft Speech Platform)

 Microsoft Speech Platform

SpGetCategoryFromId

SpGetCategoryFromId creates an object of CLSID_SpObjectTokenCategory. This function assists in locating and creating an object token category without having to search or change the registry directly.

Found in: sphelper.h

SpGetCategoryFromId(
   const WCHAR              *pszCategoryId,
   ISpObjectTokenCategory **ppCategory,
   BOOL                     fCreateIfNotExist = FALSE
);

Parameters

pszCategoryId
[in] The string indicating the CategoryId.
ppCategory
[out] The token category of the object being created. It is created with CoCreateInstance and must be manually freed when no longer required.
fCreateIfNotExist
[in] An optional parameter allowing the object to be created if one does not currently exist. The default is FALSE unless otherwise specified.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpGetDefaultTokenFromCategoryId (Microsoft Speech Platform)

 Microsoft Speech Platform

SpGetDefaultTokenFromCategoryId

SpGetDefaultTokenFromCategoryId gets the default token for the specified category ID.

Found in: sphelper.h

inline HRESULT SpGetDefaultTokenFromCategoryId(
   const WCHAR       *pszCategoryId,
   ISpObjectToken   **ppToken,
   BOOL              *fCreateCategoryIfNotExist = TRUE
);

Parameters

pszCategoryId
[in] The null-terminated string for the category ID.
ppToken
[out] The default token for the category ID.
fCreateCategoryIfNotExist
[in] An optional parameter allowing the category to be created if one does not currently exist. By default, the value is TRUE unless otherwise indicated.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpGetDefaultTokenIdFromCategoryId (Microsoft Speech Platform)

 Microsoft Speech Platform

SpGetDefaultTokenIdFromCategoryId

SpGetDefaultTokenIdFromCategoryId gets the default token ID for the specified category.

Found in: sphelper.h

inline HRESULT SpGetDefaultTokenIdFromCategoryId(
   const WCHAR   *pszCategoryId,
   WCHAR        **ppszTokenId
);

Parameters

pszCategoryId
[in] The null-terminated string indicating the category ID.
ppszTokenId
[out] The null-terminated string ID of the owning default token.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpGetDescription (Microsoft Speech Platform)

 Microsoft Speech Platform

SpGetDescription

SpGetDescription passes back the textual description associated with the specified token.

Found in: sphelper.h

SpGetDescription(
   ISpObjectToken   *pObjToken,
   WCHAR           **ppszDescription,
   LANGID           *Language = SpGetUserDefaultUILanguage()
);

Parameters

pObjToken
[in] The object token of the target resource.
ppszDescription
[out] A null-terminated string containing the resource description.
Language
[in] The language ID for the resource. Language is optional and if omitted the default language will be used.

Return values

This helper function calls ISpDataKey::GetStringValue. See those return values.


Helper SpGetSubTokenFromToken (Microsoft Speech Platform)

 Microsoft Speech Platform

SpGetSubTokenFromToken

SpGetSubTokenFromToken creates a subtoken from a token.

Found in: spddkhlp.h

SpGetSubTokenFromToken(
   ISpObjectToken   *pToken,
   const WCHAR      *pszSubKeyName,
   ISpObjectToken  **ppToken,
   BOOL              fCreateIfNotExist = FALSE
);

Parameters

pToken
[in] The object token from which to create the subtoken. If not present, this token will be created if fCreateIfNotExist is TRUE.
pszSubKeyName
[out] The name of the subtoken to use.
ppToken
[in] The newly created subtoken.
fCreateIfNotExist
[in] Optional Boolean indicating that the token is to be created if one does not currently exist. TRUE allows the creation. The default value FALSE does not.

Return values

Value | Description
S_OK | Function completed successfully.
E_POINTER | At least one of the pointers pToken, pszSubKeyName, or ppToken is invalid or bad.
FAILED (hr) | Appropriate error message.


Helper SpGetTokenFromId (Microsoft Speech Platform)

 Microsoft Speech Platform

SpGetTokenFromId

SpGetTokenFromId creates an object token of CLSID_SpObjectToken. This function assists in locating and creating an object token without having to search or change the registry directly.

Found in: sphelper.h

inline HRESULT SpGetTokenFromId(
   const WCHAR       *pszTokenId,
   ISpObjectToken   **ppToken,
   BOOL              *fCreateIfNotExist = FALSE
);

Parameters

pszTokenId
[in] The null-terminated string indicating the token ID.
ppToken
[out] The token being created. It is created with CoCreateInstance and must be manually freed when no longer required.
fCreateIfNotExist
[in] An optional parameter allowing the object to be created if one does not currently exist. The default is FALSE unless otherwise specified.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpGetUserDefaultUILanguage (Microsoft Speech Platform)

 Microsoft Speech Platform

SpGetUserDefaultUILanguage

SpGetUserDefaultUILanguage returns the default user interface language.

Found in: sphelper.h

inline LANGID SpGetUserDefaultUILanguage ( void );

Parameters

None.

Return values

Returns the default language. If the attempt fails to find the default language from the specific operating system, the default language from SAPI is returned instead.


Helper SpSetCommonTokenData (Microsoft Speech Platform)

 Microsoft Speech Platform

SpSetCommonTokenData

SpSetCommonTokenData fills in the token data with the information provided by the parameters. Unused parameters must be NULL.

Found in: sphelper.h

SpSetCommonTokenData(
   ISpObjectToken   *pToken,
   const CLSID      *pclsid,
   const WCHAR      *pszLangIndependentName,
   LANGID            langid,
   const WCHAR      *pszLangDependentName,
   ISpDataKey      **ppDataKeyAttribs
);

Parameters

pToken
[in] Address of a pointer to an ISpObjectToken object containing the information associated with the tokens being added.
pclsid
[in] Sets the token's CLSID, if specified.
pszLangIndependentName
[in] Sets the token's language independent name.
langid
[in] The language ID of the word. May be zero to indicate the word can be of any LANGID.
pszLangDependentName
[in] Sets the token's language dependent name.
ppDataKeyAttribs
[in] Opens the attributes key. The key is created if it does not currently exist. May be NULL if not needed.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpSetDefaultTokenForCategoryId (Microsoft Speech Platform)

 Microsoft Speech Platform

SpSetDefaultTokenForCategoryId

SpSetDefaultTokenForCategoryId sets the default token for the specified category ID.

Found in: sphelper.h

inline HRESULT SpSetDefaultTokenForCategoryId(
   const WCHAR      *pszCategoryId,
   ISpObjectToken   *pToken
);

Parameters

pszCategoryId
[in] The null-terminated string for the category ID.
pToken
[in] The token to be set as the default for the category ID.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SpSetDefaultTokenIdForCategoryId (Microsoft Speech Platform)

 Microsoft Speech Platform

SpSetDefaultTokenIdForCategoryId

SpSetDefaultTokenIdForCategoryId sets a specific token ID as the default for the specified category ID.

Found in: sphelper.h

inline HRESULT SpSetDefaultTokenIdForCategoryId(
   const WCHAR    *pszCategoryId,
   const WCHAR    *pszTokenId
);

Parameters

pszCategoryId
[in] The null-terminated token ID string.
pszTokenId
[in] The null-terminated token ID that will be set as default token ID for this specific category.

Return values

Value | Description
S_OK | Function completed successfully.
FAILED (hr) | Appropriate error message.


Helper SPFEI (Microsoft Speech Platform)

 Microsoft Speech Platform

SPFEI

SPFEI casts a specified value into a 64-bit type.

For a list of the supported SPEI_ord event types, see SPEVENTENUM

Found in: sapi.idl

SPFEI(
   void   *SPEI_ord
);

Parameters

SPEI_ord
[in, out] The value to re-cast. The new value is passed back.

Return values

No error code is returned.

Related Helper Macros

Macro | Description
SPFEI_FLAGCHECK | Retrieves reserved flags for the event interest enum.
SPEI_ALL_EVENTS | Retrieves all possible events flags.
SPFEI_ALL_TTS_EVENTS | Retrieves all possible TTS event flags.
SPFEI_ALL_SR_EVENTS | Retrieves all possible SR event flags.

Remarks

The SPFEI_FLAGCHECK macro retrieves the flags that must always be included in any event interest. SAPI uses the SPFEI_FLAGCHECK macro to help developers avoid mistakes by using event interest related methods (see ISpEventSource::SetInterest and ISpRecoContext::SetVoicePurgeEvent) with the actual enumeration instead of the SPFEI() macro.

Example

Here is an example of the SPFEI macro used to set SR event interest

hr = g_cpRecoCtxt->SetInterest(SPFEI(SPEI_RECOGNITION), SPFEI(SPEI_RECOGNITION));

Here is an example of the SPFEI_ALL_SR_EVENTS macro used to set SR event interest in all events. Note this is an example and not recommended practice.

hr = g_cpRecoCtxt->SetInterest(SPFEI_ALL_SR_EVENTS, SPFEI_ALL_SR_EVENTS);


Helper SPBindToFile (Microsoft Speech Platform)

 Microsoft Speech Platform

SPBindToFile

SPBindToFile binds the audio stream to the specified file.

Found in: sphelper.h

SPBindToFile(
   LPCWSTR               pFileName,
   SPFILEMODE            eMode,
   ISpStream           **ppStream,
   const GUID           *pFormatId = NULL,
   const WAVEFORMATEX   *pWaveFormatEx = NULL,
   ULONGLONG            *ullEventInterest = SPFEI_ALL_EVENTS
);

Parameters

pFileName
[in] Address of a null-terminated string containing the file name of the file to bind the stream to.
eMode
[in] Flag of the type SPFILEMODE to define the file opening mode. When opening an audio wave file, this must be SPFM_OPEN_READONLY or SPFM_CREATE_ALWAYS, otherwise the call will fail.
ppStream
[in, out] The address of an ISpStream pointer. If the function succeeds, this value is filled in with the newly created ISpStream interface.
pFormatId
[in] The data format identifier associated with the stream. This can be NULL (default) and the format will be determined from the supplied wave file, if the file has the '.wav' extension. If it doesn't, the file is assumed to be a text file.
pWaveFormatEx
[in] Address of the WAVEFORMATEX structure that contains the wave file format information. If guidFormatId is SPDFID_WaveFormatEx, this must point to a valid WAVEFORMATEX structure. For other formats, it should be NULL.
ullEventInterest
[in] Flags of type SPEVENTENUM for the events wanted.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | One or more parameters are invalid.
SPERR_ALREADY_INITIALIZED | The object has already been initialized.
SPERR_INVALID_WAV_FILE | The .WAV file is impropertly formatted.


Helper SpClearEvent (Microsoft Speech Platform)

 Microsoft Speech Platform

SpClearEvent

SpClearEvent clears an event structure. May be used by clients not using CSpEvent class.

Found in: sphelper.h

inline void SpClearEvent(
   SPEVENT   *pe
);

Parameters

pe
[in] The event to clear. Events of types SPET_LPARAM_IS_POINTER, SPET_LPARAM_IS_STRING, SPET_LPARAM_IS_TOKEN, or SPET_LPARAM_IS_OBJECT have the associated data in pe->lParam deallocated first.

Return values

No error code is returned.


Helper SpConvertStreamFormatEnum (Microsoft Speech Platform)

 Microsoft Speech Platform

SpConvertStreamFormatEnum

SpConvertStreamFormatEnum converts the specified stream format into a fully populated wave format structure.

Found in: sphelper.h

SpConvertStreamFormatEnum(
   SPSTREAMFORMAT   eFormat,
   GUID            *pFormatId,
   WAVEFORMATEX   **ppCoMemWaveFormatEx
);

Parameters

eFormat
[in] The requested stream format. Must be a valid SPSTREAMFORMAT value of SPSF_8kHz8BitMono or greater.
pFormatId
[in, out] The GUID of the new format. May be GUID_NULL if an error occurred.
ppCoMemWaveFormatEx
[out] The populated WAVEFORMATEX structure specified by the supplied SPSTREAMFORMAT.

Return values

Value | Description
S_OK | Function completed successfully.
E_OUTOFMEMORY | Exceeded available memory.
E_INVALIDARG | Either pFormatId or ppCoMemWaveFormatEx is invalid or bad. Alternatively, the specified format is not recognized.
FAILED(hr) | Appropriate error message.


Helper SpEventSerializeSize (Microsoft Speech Platform)

 Microsoft Speech Platform

SpEventSerializeSize

SpEventSerializeSize calculates the required size of a buffer to serialize an event. The call must specify which type of serialized event.

Found in: sphelper.h

template <class T>
inline ULONG SpEventSerializeSize(
   const SPEVENT   *pEvent
);

Parameters

pEvent
[in] The event structure to calculate the size of. pEvent must be either SPSERIALIZEDEVENT or SPSERIALIZEDEVENT64.

Return values

Size, in bytes, required to serialize the event.


Helper SpInitEvent (Microsoft Speech Platform)

 Microsoft Speech Platform

SpInitEvent

SpInitEvent clears the event structure.

Found in: sphelper.h

inline void SpInitEvent(
   SPEVENT   *pe
);

Parameters

pe
[in] The event to clear.

Return values

No error code is returned.


Helper SpSetDescription (Microsoft Speech Platform)

 Microsoft Speech Platform

SpSetDescription

SpSetDescription sets the string value for the specified token.

Found in: sphelper.h

inline HRESULT SpSetDescription(
   ISpObjectToken  *pObjToken,
   const WCHAR     *pszDescription,
   LANGID           Language = SpGetUserDefaultUILanguage(),
   BOOL             fSetLangIndependentId = TRUE
);

Parameters

pObjToken
[in] The object token of the target resource.
pszDescription
[in] A null-terminated string containing the resource description.
Language
[in] The language ID for the resource. Language is optional and if omitted the default language will be used.
fSetLangIndependentId
[in] Boolean indicating whether the language independent ID is also changed. TRUE, changes it; FALSE does not. If fSetLangIndependentId omitted the default TRUE will be used.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Either pszDescription or the language description is invalid or bad.
FAILED(hr) | Appropriate error message.


SAPI Application Object Classes (Microsoft Speech Platform)

 Microsoft Speech Platform

SAPI Application Object Classes

Object class | Related interfaces
SpNotifyTranslator | ISpNotifySink ISpNotifyTranslator
SpObjectTokenCategory | ISpObjectTokenCategory
SpObjectTokenEnum | IEnumSpObjectTokens
SpObjectToken | ISpObjectToken ISpDataKey
SpDataKey | ISpDataKey
SpResourceManager | IServiceProvider ISpResourceManager
SpStreamFormatConverter | IStream ISpStreamFormat ISpAudio
SpMMAudioEnum | IEnumSpObjectTokens
SpMMAudioIn | ISpAudio IStream ISpStreamFormat ISpEventSource ISpEventSink ISpObjectWithToken ISpMMSysAudio
SpMMAudioOut | ISpAudio IStream ISpStreamFormat ISpEventSource ISpEventSink ISpObjectWithToken ISpMMSysAudio
SpRecPlayAudio | ISpAudio IStream ISpStreamFormat ISpEventSource ISpEventSink ISpObjectWithToken
SpStream | IStream ISpStreamFormat IStream
SpVoice | ISpVoice ISpEventSource ISpNotifySource
SpSharedRecognizer | ISpRecognizer
SpInprocRecognizer | ISpRecognizer
SpRecoContext | ISpRecoContext ISpEventSource ISpNotifySource
SpSharedRecoContext | ISpRecoContext ISpEventSource ISpNotifySource
SpRecoGrammar | ISpRecoGrammar ISpGrammarBuilder
SpRecoResult | ISpRecoResult ISpPhrase
SpPhraseAlt | ISpPhraseAlt ISpPhrase
SpLexicon | ISpLexicon
SpUnCompressedLexicon | ISpLexicon ISpObjectWithToken
SpCompressedLexicon | ISpLexicon ISpObjectWithToken
SpPhoneConverter | ISpPhoneConverter ISpObjectWithToken
SpShortcut | ISpShortcut ISpObjectWithToken


SpNotifyTranslator (Microsoft Speech Platform)

 Microsoft Speech Platform

SpNotifyTranslator

SpNotifyTranslator |
 | ISpNotifySink
 | ISpNotifyTranslator


SpObjectTokenCategory (Microsoft Speech Platform)

 Microsoft Speech Platform

SpObjectTokenCategory

SpObjectTokenCategory |
 | ISpDataKey
 | ISpObjectTokenCategory


SpObjectTokenEnum (Microsoft Speech Platform)

 Microsoft Speech Platform

SpObjectTokenEnum

SpObjectTokenEnum |
 | IEnumSpObjectTokens


SpObjectToken (Microsoft Speech Platform)

 Microsoft Speech Platform

SpObjectToken

SpObjectToken |
 | ISpObjectToken
 | ISpDataKey


SpDataKey (Microsoft Speech Platform)

 Microsoft Speech Platform

SpDataKey

SpDataKey |
 | ISpDataKey


SpResourceManager (Microsoft Speech Platform)

 Microsoft Speech Platform

SpResourceManager

SpResourceManager |
 | IServiceProvider
 | ISpResourceManager
 | ISpTaskManager


SpStreamFormatConverter (Microsoft Speech Platform)

 Microsoft Speech Platform

SpStreamFormatConverter

SpStreamFormatConverter |
 | IStream
 | ISpStreamFormat
 | ISpAudio


SpMMAudioEnum (Microsoft Speech Platform)

 Microsoft Speech Platform

SpMMAudioEnum

SpMMAudioEnum |
 | IEnumSpObjectTokens


SpMMAudioIn (Microsoft Speech Platform)

 Microsoft Speech Platform

SpMMAudioIn

The SAPI implementation of the SpMMAudioIn object supports the following UI if the object has a Windows mixer associated with it:

SpMMAudioIn |
 | IStream
 | ISpStreamFormat
 | ISpEventSource
 | ISpObjectWithToken
 | ISpMMSysAudio


SpMMAudioOut (Microsoft Speech Platform)

 Microsoft Speech Platform

SpMMAudioOut

The SAPI implementation of the SpMMAudioOut object supports the following UI if the object has a Windows mixer associated with it:

SpMMAudioOut |
 | IStream
 | ISpStreamFormat
 | ISpEventSource
 | ISpObjectWithToken
 | ISpMMSysAudio


SpRecPlayAudio (Microsoft Speech Platform)

 Microsoft Speech Platform

SpRecPlayAudio

SpRecPlayAudio |
 | ISpAudio
 | IStream
 | ISpStreamFormat
 | ISpEventSink
 | ISpObjectWithToken


SpShortcut (Microsoft Speech Platform)

 Microsoft Speech Platform

SpShortcut

SpShortcut |
 | ISpShortcut
 | ISpObjectWithToken


SpStream (Microsoft Speech Platform)

 Microsoft Speech Platform

SpStream

SpStream |
 | ISpStream
 | ISpStreamFormat
 | IStream


SpVoice (Microsoft Speech Platform)

 Microsoft Speech Platform

SpVoice

SpVoice |
 | ISpVoice
 | ISpEventSource
 | ISpNotifySource

An application creates the SpVoice object and uses the ISpVoice interface to submit and control speech synthesis. Applications can speak text strings, text files, and audio files. Although this object is named the "SpVoice," it is actually a much higher-level object than a single voice. Conceptually, it is an object which accepts input data streams that are then rendered to the specified output, potentially using multiple speech synthesis voices in the process. Each SpVoice instance contains its own queue of input streams (usually just text) and its own output stream (usually an audio device). When an application calls ISpVoice::Speak, another item is added to the end of the SpVoice queue.

Basic Synthesis

The main speech synthesis method is ISpVoice::Speak. Almost everything having to do with controlling synthesis (for example, rate, pitch, and volume) is performed by this single function. This function can speak plain text, or the application can mark up the text using synthesis markup tags. The speak method enables the application to specify whether the call should be synchronous or asynchronous. If the call is synchronous, the Speak method will not return until all of the text has been rendered. Speak returns immediately for asynchronous Speak calls, and the text is rendered on a background thread.

ISpVoice::SpeakStream is similar to the Speak method, but by using SpeakStream, streams of text or audio data can be added to the rendering queue.

Overriding Defaults

SAPI will automatically use the default voice and default audio output device if the application does not specify otherwise. The output can be controlled by the application through ISpVoice::SetOutput. The default voice can be overridden in one of two ways: The application can call ISpVoice::SetVoice or it could speak a <VOICE> synthesis markup tag.

Audio Device Sharing

When an SpVoice object is rendering to an audio device (as opposed to a stream), it will attempt to cooperate with other SpVoice objects that are sharing the same device based on the priority of the SpVoice. By default, a voice is set to SPVPRI_NORMAL which means that it will wait until other voices in the system have completed before it will begin rendering its input queue. A voice set to SPVPRI_ALERT will interrupt a normal priority voice by stopping the normal voice, rendering its own queue, and then restarting the normal priority voice. An SpVoice with a priority of SPVPRI_OVER will simply render its data immediately even if another voice is currently speaking (they would both speak at the same time).

Applications can control the priority of a voice by calling ISpVoice::SetPriority.

Rendering to Streams

The SpVoice can render data to any object that implements ISpStreamFormat, which is a simple derivative of the COM standard IStream. The SpStream object is provided to allow easy conversion of existing IStreams to support ISpStreamFormat or to read or write wav or other files. Applications can ISpVoice::SetOutput to force the SpVoice to render to a stream. When rendering to a stream, the voice will render the data as quickly as possible.

Synthesis Events

The SpVoice implements the ISpEventSource interface. It forwards events back to the application when the corresponding audio data has been rendered to the output device. Examples of events are reaching a word boundary, speaking a phoneme, reaching a bookmark, etc. Some applications can simply be notified when events occur and then call ISpVoice::GetStatus to determine the current stat of the SpVoice object. More complex applications may need to queue events. See the documentation for ISpEventSource for information on setting interest in events.

How Created

Create the SpVoice object by calling ::CoCreateInstance with CLSID_SpVoice.


SpSharedRecognizer (Microsoft Speech Platform)

 Microsoft Speech Platform

SpSharedRecognizer

SpSharedRecognizer |
 | ISpRecognizer
 | ISpSerializeState


SpInProcRecoContext (Microsoft Speech Platform)

 Microsoft Speech Platform

SpInProcRecoContext

SpInProcRecoContext |
 | ISpRecoContext
 | ISpRecoContext2


SpInprocRecognizer (Microsoft Speech Platform)

 Microsoft Speech Platform

SpInprocRecognizer

SpInprocRecognizer |
 | ISpRecognizer
 | ISpSerializeState


SpRecoContext (Microsoft Speech Platform)

 Microsoft Speech Platform

SpRecoContext

SpRecoContext |
 | ISpRecoContext
 | ISpEventSource
 | ISpNotifySource


SpSharedRecoContext (Microsoft Speech Platform)

 Microsoft Speech Platform

SpSharedRecoContext

SpSharedRecoContext |
 | ISpRecoContext
 | ISpRecoContext2
 | ISpEventSource
 | ISpNotifySource


SpRecoGrammar (Microsoft Speech Platform)

 Microsoft Speech Platform

SpRecoGrammar

SpRecoGrammar |
 | ISpRecoGrammar
 | ISpGrammarBuilder


SpRecoResult (Microsoft Speech Platform)

 Microsoft Speech Platform

SpRecoResult

SpRecoResult |
 | ISpRecoResult
 | ISpPhrase


SpPhraseAlt (Microsoft Speech Platform)

 Microsoft Speech Platform

SpPhraseAlt

SpPhraseAlt |
 | ISpPhraseAlt
 | ISpPhrase


SpLexicon (Microsoft Speech Platform)

 Microsoft Speech Platform

SpLexicon

SpLexicon |
 | ISpLexicon

The Lexicon database is a repository of words and word-related information such as pronunciations and parts of speech. The SAPI lexicon interface provides application, CSR engine, and TTS engine developers a standard method with which to create, access, modify, and synchronize with lexicons.

Types of Lexicons

There are two types of custom lexicons supported by lexicon interface: user and application. The user lexicon stores words specific to a user. It is a read/write lexicon and is shared among all applications. The application lexicon is supplied by the application and stores words specific to the application. The application supplied lexicons are read-only. Application lexicons ensure that the vocabulary used by the application is well represented in the lexicon.

User lexicons override application lexicons and engine private lexicons. You cannot change application lexicons from the SpLexicon object.

Modifying and Viewing the Contents of a Lexicon

An application can modify the user lexicon using the calls ISpLexicon::AddPronunciation and ISpLexicon::RemovePronunciation. The function ISpLexicon::GetWords enables the caller to see what words are in the user or application lexicon. To obtain the pronunciation of a given word, the client would call ISpLexicon::GetPronunciations. There is not a standard method for applications to access the lexicons that are supplied by the engine.

Synchronizing Changes to a Lexicon

The lexicon interface provides methods to synchronize changes in lexicons using a lexicon generation ID, which is a sort of time-stamp on the lexicon. These changes in the lexicon are a result of modifications to user lexicons or for the installation or uninstallation of application lexicons. The client can get the current generation by calling ISpLexicon::GetGeneration and can see the change history since a given generation by calling ISpLexicon::GetGenerationChange. A speech recognition engine might want to use the synchronization to update its private stores with the changes made to the custom lexicons while the client has been offline. For example, SR engines can update their language models with changes made to the custom lexicons while the SR engine had been offline.

How Created

An SpLexicon can be created by calling ::CoCreateInstance with CLSID_SpLexicon.


SpUnCompressedLexicon (Microsoft Speech Platform)

 Microsoft Speech Platform

SpUnCompressedLexicon

SpUnCompressedLexicon |
 | ISpLexicon
 | ISpObjectWithToken


SpCompressedLexicon (Microsoft Speech Platform)

 Microsoft Speech Platform

SpCompressedLexicon

SpCompressedLexicon |
 | ISpLexicon
 | ISpObjectWithToken


SpPhoneConverter (Microsoft Speech Platform)

 Microsoft Speech Platform

SpPhoneConverter

SpPhoneConverter |
 | ISpPhoneConverter
 | ISpObjectWithToken


Error Codes Introduction (Microsoft Speech Platform)

 Microsoft Speech Platform

Error Codes Introduction

The following section includes:

  • Complete List of Error Codes

Error codes listed here include the symbolic error name, and the numeric equivalent displayed as both decimal and hexadecimal. The following list may be searched using Ctrl+F.


SAPI Error Codes (Microsoft Speech Platform)

 Microsoft Speech Platform

Error Codes

The following table lists error codes returned by SAPI.

Error Name Hexadecimal Decimal
Description
SPERR_UNINITIALIZED 0x80045001 -2147201023
The object has not been properly initialized.
SPERR_ALREADY_INITIALIZED 0x80045002 -2147201022
The object has already been initialized.
SPERR_UNSUPPORTED_FORMAT 0x80045003 -2147201021
The caller has specified an unsupported format.
SPERR_INVALID_FLAGS 0x80045004 -2147201020
The caller has specified invalid flags for this operation.
SP_END_OF_STREAM 0x00045005 282629
The operation has reached the end of stream.
SPERR_DEVICE_BUSY 0x80045006 -2147201018
The wave device is busy.
SPERR_DEVICE_NOT_SUPPORTED 0x80045007 -2147201017
The wave device is not supported.
SPERR_DEVICE_NOT_ENABLED 0x80045008 -2147201016
The wave device is not enabled.
SPERR_NO_DRIVER 0x80045009 -2147201015
There is no wave driver installed.
SPERR_FILEMUSTBEUNICODE 0x8004500a -2147201014
The file must be Unicode.
SP_INSUFFICIENTDATA 0x0004500b 282635
SPERR_INVALID_PHRASE_ID 0x8004500c -2147201012
The phrase ID specified does not exist or is out of range.
SPERR_BUFFER_TOO_SMALL 0x8004500d -2147201011
The caller provided a buffer too small to return a result.
SPERR_FORMAT_NOT_SPECIFIED 0x8004500e -2147201010
Caller did not specify a format prior to opening a stream.
SPERR_AUDIO_STOPPED 0x8004500f -2147201009
The stream I/O was stopped by setting the audio object to the stopped state. This will be returned for both read and write streams.
SP_AUDIO_PAUSED 0x00045010 282640
This will be returned only on input (read) streams when the stream is paused. Reads on paused streams will not block, and this return code indicates that all of the data has been removed from the stream.
SPERR_RULE_NOT_FOUND 0x80045011 -2147201007
Invalid rule name passed to ActivateGrammar.
SPERR_TTS_ENGINE_EXCEPTION 0x80045012 -2147201006
An exception was raised during a call to the current TTS driver.
SPERR_TTS_NLP_EXCEPTION 0x80045013 -2147201005
An exception was raised during a call to an application sentence filter.
SPERR_ENGINE_BUSY 0x80045014 -2147201004
In speech recognition, the current method cannot be performed while a grammar rule is active.
SP_AUDIO_CONVERSION_ENABLED 0x00045015 282645
The operation was successful, but only with automatic stream format conversion.
SP_NO_HYPOTHESIS_AVAILABLE 0x00045016 282646
There is currently no hypothesis recognition available.
SPERR_CANT_CREATE 0x80045017 -2147201001
Cannot create a new object instance for the specified object category.
SP_ALREADY_IN_LEX 0x00045018 282648
The word, pronunciation, or POS pair being added is already in lexicon.
SPERR_NOT_IN_LEX 0x80045019 -2147200999
The word does not exist in the lexicon.
SP_LEX_NOTHING_TO_SYNC 0x0004501a 282650
The client is currently synced with the lexicon.
SPERR_LEX_VERY_OUT_OF_SYNC 0x8004501b -2147200997
The client is excessively out of sync with the lexicon. Mismatches may not sync incrementally.
SPERR_UNDEFINED_FORWARD_RULE_REF 0x8004501c -2147200996
A rule reference in a grammar was made to a named rule that was never defined.
SPERR_EMPTY_RULE 0x8004501d -2147200995
A non-dynamic grammar rule that has no body.
SPERR_GRAMMAR_COMPILER_INTERNAL_ERROR 0x8004501e -2147200994
The grammar compiler failed due to an internal state error.
SPERR_RULE_NOT_DYNAMIC 0x8004501f -2147200993
An attempt was made to modify a non-dynamic rule.
SPERR_DUPLICATE_RULE_NAME 0x80045020 -2147200992
A rule name was duplicated.
SPERR_DUPLICATE_RESOURCE_NAME 0x80045021 -2147200991
A resource name was duplicated for a given rule.
SPERR_TOO_MANY_GRAMMARS 0x80045022 -2147200990
Too many grammars have been loaded.
SPERR_CIRCULAR_REFERENCE 0x80045023 -2147200989
Circular reference in import rules of grammars.
SPERR_INVALID_IMPORT 0x80045024 -2147200988
A rule reference to an imported grammar that could not be resolved.
SPERR_INVALID_WAV_FILE 0x80045025 -2147200987
The format of the WAV file is not supported.
SP_REQUEST_PENDING 0x00045026 282662
This success code indicates that an SR method called with the SPRIF_ASYNC flag is being processed. When it has finished processing, an SPFEI_ASYNC_COMPLETED event will be generated.
SPERR_ALL_WORDS_OPTIONAL 0x80045027 -2147200985
A grammar rule was defined with a null path through the rule. That is, it is possible to satisfy the rule conditions with no words.
SPERR_INSTANCE_CHANGE_INVALID 0x80045028 -2147200984
It is not possible to change the current engine or input. This occurs in the following cases: 1) SelectEngine called while a recognition context exists, or 2) SetInput called in the shared instance case.
SPERR_RULE_NAME_ID_CONFLICT 0x80045029 -2147200983
A rule exists with matching IDs (names) but different names (IDs).
SPERR_NO_RULES 0x8004502a -2147200982
A grammar contains no top-level, dynamic, or exported rules. There is no possible way to activate or otherwise use any rule in this grammar.
SPERR_CIRCULAR_RULE_REF 0x8004502b -2147200981
Rule 'A' refers to a second rule 'B' which, in turn, refers to rule 'A'.
SP_NO_PARSE_FOUND 0x0004502c 282668
Parse path cannot be parsed given the currently active rules.
SPERR_NO_PARSE_FOUND 0x8004502d -2147200979
Parse path cannot be parsed given the currently active rules.
SPERR_REMOTE_CALL_TIMED_OUT 0x8004502e -2147200978
A marshaled remote call failed to respond.
SPERR_AUDIO_BUFFER_OVERFLOW 0x8004502f -2147200977
This will only be returned on input (read) streams when the stream is paused because the SR driver has not retrieved data recently.
SPERR_NO_AUDIO_DATA 0x80045030 -2147200976
The result does not contain any audio, nor does the portion of the element chain of the result contain any audio.
SPERR_DEAD_ALTERNATE 0x80045031 -2147200975
This alternate is no longer a valid alternate to the result it was obtained from. Returned from ISpPhraseAlt methods.
SPERR_HIGH_LOW_CONFIDENCE 0x80045032 -2147200974
The result does not contain any audio, nor does the portion of the element chain of the result contain any audio. Returned from ISpResult::GetAudio and ISpResult::SpeakAudio.
SPERR_INVALID_FORMAT_STRING 0x80045033 -2147200973
The XML format string for this RULEREF is invalid, e.g. not a GUID or REFCLSID.
SP_UNSUPPORTED_ON_STREAM_INPUT 0x00045034 282676
The operation is not supported for stream input.
SPERR_APPLEX_READ_ONLY 0x80045035 -2147200971
The operation is invalid for all but newly created application lexicons.
SPERR_NO_TERMINATING_RULE_PATH 0x80045036 -2147200970
SP_WORD_EXISTS_WITHOUT_PRONUNCIATION 0x00045037 282679
The word exists but without pronunciation.
SPERR_STREAM_CLOSED 0x80045038 -2147200968
An operation was attempted on a stream object that has been closed.
SPERR_NO_MORE_ITEMS 0x80045039 -2147200967
When enumerating items, the requested index is greater than the count of items.
SPERR_NOT_FOUND 0x8004503a -2147200966
The requested data item (data key, value, etc.) was not found.
SPERR_INVALID_AUDIO_STATE 0x8004503b -2147200965
Audio state passed to SetState() is invalid.
SPERR_GENERIC_MMSYS_ERROR 0x8004503c -2147200964
A generic MMSYS error not caught by _MMRESULT_TO_HRESULT.
SPERR_MARSHALER_EXCEPTION 0x8004503d -2147200963
An exception was raised during a call to the marshaling code.
SPERR_NOT_DYNAMIC_GRAMMAR 0x8004503e -2147200962
Attempt was made to manipulate a non-dynamic grammar.
SPERR_AMBIGUOUS_PROPERTY 0x8004503f -2147200961
Cannot add ambiguous property.
SPERR_INVALID_REGISTRY_KEY 0x80045040 -2147200960
The key specified is invalid.
SPERR_INVALID_TOKEN_ID 0x80045041 -2147200959
The token specified is invalid.
SPERR_XML_BAD_SYNTAX 0x80045042 -2147200958
The xml parser failed due to bad syntax.
SPERR_XML_RESOURCE_NOT_FOUND 0x80045043 -2147200957
The xml parser failed to load a required resource (e.g., voice, phoneconverter, etc.).
SPERR_TOKEN_IN_USE 0x80045044 -2147200956
Attempted to remove registry data from a token that is already in use elsewhere.
SPERR_TOKEN_DELETED 0x80045045 -2147200955
Attempted to perform an action on an object token that has had associated registry key deleted.
SPERR_MULTI_LINGUAL_NOT_SUPPORTED 0x80045046 -2147200954
The selected voice was registered as multi-lingual. SAPI does not support multi-lingual registration.
SPERR_EXPORT_DYNAMIC_RULE 0x80045047 -2147200953
Exported rules cannot refer directly or indirectly to a dynamic rule.
SPERR_STGF_ERROR 0x80045048 -2147200952
Error parsing the SAPI Text Grammar Format (XML grammar).
SPERR_WORDFORMAT_ERROR 0x80045049 -2147200951
Incorrect word format, probably due to incorrect pronunciation string.
SPERR_STREAM_NOT_ACTIVE 0x8004504a -2147200950
Methods associated with active audio stream cannot be called unless stream is active.
SPERR_ENGINE_RESPONSE_INVALID 0x8004504b -2147200949
Arguments or data supplied by the engine are in an invalid format or are inconsistent.
SPERR_SR_ENGINE_EXCEPTION 0x8004504c -2147200948
An exception was raised during a call to the current SR engine.
SPERR_STREAM_POS_INVALID 0x8004504d -2147200947
Stream position information supplied from engine is inconsistent.
SP_RECOGNIZER_INACTIVE 0x0004504e 282702
Operation could not be completed because the recognizer is inactive. It is inactive either because the recognition state is currently inactive or because no rules are active.
SPERR_REMOTE_CALL_ON_WRONG_THREAD 0x8004504f -2147200945
When making a remote call to the server, the call was made on the wrong thread.
SPERR_REMOTE_PROCESS_TERMINATED 0x80045050 -2147200944
The remote process terminated unexpectedly.
SPERR_REMOTE_PROCESS_ALREADY_RUNNING 0x80045051 -2147200943
The remote process is already running; it cannot be started a second time.
SPERR_LANGID_MISMATCH 0x80045052 -2147200942
An attempt to load a CFG grammar with a LANGID different than other loaded grammars.
SP_PARTIAL_PARSE_FOUND 0x00045053 282707
A grammar-ending parse has been found that does not use all available words.
SPERR_NOT_TOPLEVEL_RULE 0x80045054 -2147200940
An attempt to deactivate or activate a non top-level rule.
SP_NO_RULE_ACTIVE 0x00045055 282709
An attempt to parse when no rule was active.
SPERR_LEX_REQUIRES_COOKIE 0x80045056 -2147200938
An attempt to ask a container lexicon for all words at once.
SP_STREAM_UNINITIALIZED 0x00045057 282711
An attempt to activate a rule/dictation/etc without calling SetInput first in the InProc case.
SPERR_UNSUPPORTED_LANG 0x80045059 -2147200935
The requested language is not supported.
SPERR_VOICE_PAUSED 0x8004505a -2147200934
The operation cannot be performed because the voice is currently paused.
SPERR_AUDIO_BUFFER_UNDERFLOW 0x8004505b -2147200933
This will only be returned on input (read) streams when the real time audio device stops returning data for a long period of time.
SPERR_AUDIO_STOPPED_UNEXPECTEDLY 0x8004505c -2147200932
An audio device stopped returning data from the Read() method even though it was in the run state. This error is only returned in the END_SR_STREAM event.
SPERR_NO_WORD_PRONUNCIATION 0x8004505d -2147200931
The SR engine is unable to add this word to a grammar. The application may need to supply an explicit pronunciation for this word.
SPERR_ALTERNATES_WOULD_BE_INCONSISTENT 0x8004505e -2147200930
An attempt to call ScaleAudio on a recognition result having previously called GetAlternates. Allowing the call to succeed would result in the previously created alternates located in incorrect audio stream positions.
SPERR_NOT_SUPPORTED_FOR_SHARED_RECOGNIZER 0x8004505f -2147200929
The method called is not supported for the shared recognizer. For example, ISpRecognizer::GetInputStream().
SPERR_TIMEOUT 0x80045060 -2147200928
A task could not complete because the SR engine had timed out.
SPERR_REENTER_SYNCHRONIZE 0x80045061 -2147200927
An SR engine called synchronize while inside of a synchronize call.
SPERR_STATE_WITH_NO_ARCS 0x80045062 -2147200926
The grammar contains a node no arcs.
SPERR_NOT_ACTIVE_SESSION 0x80045063 -2147200925
Neither audio output nor input is supported for non-active console sessions.
SPERR_ALREADY_DELETED 0x80045064 -2147200924
The object is a stale reference and is invalid to use. For example, having an ISpeechGrammarRule object reference and then calling ISpeechRecoGrammar::Reset() will cause the rule object to be invalidated. Calling any methods after this will result in this error.
SP_AUDIO_STOPPED 0x00045065 282725
This can be returned from Read or Write calls for audio streams when the stream is stopped.
SPERR_RECOXML_GENERATION_FAIL 0x80045066 -2147200922
The Recognition Parse Tree could not be generated. For example, a rule name begins with a digit but the XML parser does not allow an element name beginning with a digit.
SPERR_SML_GENERATION_FAIL 0x80045067 -2147200921
The SML could not be generated. For example, the transformation xslt template is not well formed.
SPERR_NOT_PROMPT_VOICE 0x80045068 -2147200920
The SML could not be generated. For example, the transformation xslt template is not well formed.
SPERR_ROOTRULE_ALREADY_DEFINED 0x80045069 -2147200919
There is already a root rule for this grammar. Defining another root rule will fail.
SPERR_SCRIPT_DISALLOWED 0x80045070 -2147200912
Support for embedded script not supported because browser security settings have disabled it.
SPERR_REMOTE_CALL_TIMED_OUT_START 0x80045071 -2147200911
A time out occurred starting the sapi server.
SPERR_REMOTE_CALL_TIMED_OUT_CONNECT 0x80045072 -2147200910
A timeout occurred obtaining the lock for starting or connecting to sapi server.
SPERR_SECMGR_CHANGE_NOT_ALLOWED 0x80045073 -2147200909
When there is a cfg grammar loaded, changing the security manager is not permitted.
SP_COMPLETE_BUT_EXTENDABLE 0x00045074 282740
Parse is valid but could be extendable (internal use only).
SPERR_FAILED_TO_DELETE_FILE 0x80045075 -2147200907
Tried and failed to delete an existing file.
SPERR_SHARED_ENGINE_DISABLED 0x80045076 -2147200906
The user has chosen to disable speech from running on the machine, or the system is not set up to run speech (for example, initial setup and tutorial has not been run).
SPERR_RECOGNIZER_NOT_FOUND 0x80045077 -2147200905
No recognizer is installed.
SPERR_AUDIO_NOT_FOUND 0x80045078 -2147200904
No audio device is installed.
SPERR_NO_VOWEL 0x80045079 -2147200903
No vowel in a word.
SPERR_UNSUPPORTED_PHONEME 0x8004507A -2147200902
No vowel in a word.
SP_NO_RULES_TO_ACTIVATE 0x0004507B 282747
The grammar does not have any root or top-level active rules to activate.
SP_NO_WORDENTRY_NOTIFICATION 0x0004507C 282748
The engine does not need SAPI word entry handles for this grammar.
SPERR_WORD_NEEDS_NORMALIZATION 0x8004507D -2147200899
The word passed to the GetPronunciations interface needs normalizing first.
SPERR_CANNOT_NORMALIZE 0x8004507E -2147200898
The word passed to the normalize interface cannot be normalized.
S_NOTSUPPORTED 0x80045080 -2147200896
This combination of function call and input is currently not supported.


Miscellanea (Microsoft Speech Platform)

 Microsoft Speech Platform

Miscellanea

The follow sections cover supporting speech functions:

  • Global Constants
  • COM Class ID List
  • Token Category IDs
  • COM Interface IUnknown
  • American English Phoneme Representation
  • International Phoneme Representation
  • Further Reading


SP_MAX_WORD_LENGTH (Microsoft Speech Platform)

 Microsoft Speech Platform

Constants

The following constants are used in SAPI. They are shown with the C/C++ name and Automation name although each pair uses the same numeric value.

C/C++ Name | Description
Automation Name
Value
SP_MAX_WORD_LENGTH | The maximum length of a word. Functions with input word strings matching or exceeding this limit will return E_INVALIDARG.
Speech_Max_Word_Length
128
SP_MAX_PRON_LENGTH | The maximum length of a phoneme pronunciation. This limit applies to zero-terminated lists of SPPHONEID elements. Functions with SPPHONEID parameters matching or exceeding this limit will return E_INVALIDARG.
Speech_Max_Pron_Length
384
SP_STREAMPOS_ASAP | Indicates the Bookmark event will be fired as soon as possible after the speech recognition (SR) engine reaches a synchronization point. This allows the Bookmark to be sent at the first available opportunity.
Speech_StreamPos_Asap
0
SP_STREAMPOS_REALTIME | Speech_StreamPos_RealTime indicates Bookmark event will occur when the SR engine reaches the current audio device position.
Speech_StreamPos_RealTime
-1


Class IDs (Microsoft Speech Platform)

 Microsoft Speech Platform

COM Class ID List

The following Class IDs are used with the Microsoft Speech Platform.

CLSID | Interface on which CLSID can be co-created
CLSID_SpNotifyTranslator | ISpNotifyTranslator
CLSID_SpObjectTokenCategory | ISpObjectTokenCategory
CLSID_SpObjectToken | ISpObjectTokenInit
CLSID_SpResourceManager | ISpResourceManager
CLSID_SpStreamFormatConverter | ISpStreamFormatConverter
CLSID_SpStreamFormatConverter | ISpEventSource
CLSID_SpStreamFormatConverter | ISpEventSink
CLSID_SpStreamFormatConverter | ISpAudio
CLSID_SpMMAudioEnum | ISpObjectWithToken
CLSID_SpMMAudioEnum | IEnumSpObjectTokens
CLSID_SpMMAudioIn | ISpMMSysAudio
CLSID_SpMMAudioOut | ISpMMSysAudio
CLSID_SpRecPlayAudio | ISpAudio
CLSID_SpRecPlayAudio | ISpObjectWithToken
CLSID_SpStream | ISpStream
CLSID_SpStream | ISpEventSource
CLSID_SpStream | ISpEventSink
CLSID_SpStream | ISpTranscript
CLSID_SpVoice | ISpVoice
CLSID_SpVoice | ISpThreadTask
CLSID_SpSharedRecoContext | ISpRecoContext
CLSID_SpSharedRecoContext | _ISpPrivateEngineCall
CLSID_SpInprocRecognizer | ISpRecognizer
CLSID_SpSharedRecognizer | ISpRecognizer
CLSID_SpLexicon | ISpContainerLexicon
CLSID_SpUnCompressedLexicon | ISpLexicon
CLSID_SpUnCompressedLexicon | ISpObjectWithToken
CLSID_SpCompressedLexicon | ISpLexicon
CLSID_SpCompressedLexicon | ISpObjectWithToken
CLSID_SpPhoneConverter | ISpPhoneConverter
CLSID_SpNullPhoneConverter | ISpPhoneConverter
CLSID_SpResourceManager | ISpTaskManager


Category IDs (Microsoft Speech Platform)

 Microsoft Speech Platform

Token Category IDs

The following token category IDs are used with the Microsoft Speech Platform.

Category ID | Purpose
SPCAT_AUDIOOUT | Available audio output devices.
SPCAT_AUDIOIN | Available audio input devices.
SPCAT_VOICES | Available voices.
SPCAT_RECOGNIZERS | Available recognizers.
SPCAT_APPLEXICONS | Available application lexicons.
SPCAT_PHONECONVERTERS | Available phoneme converters
SPCAT_RECOPROFILES | Available recognition profiles.


IUnknown (Microsoft Speech Platform)

 Microsoft Speech Platform

COM Interface IUnknown

The IUnknown interface is a common interface supported by all COM objects and, therefore, by all speech objects. The IUnknown interface has the following member functions:

  • QueryInterface
  • AddRef
  • Release

An application uses IUnknown to obtain pointers to other interfaces supported by an object and to manage the interface pointers after obtaining them.

QueryInterface

HRESULT QueryInterface(
   REFIID riid,			//Identifier of the requested interface
   LPVOID FAR   *ppvObj		//Address of output variable that receives the
                          //interface pointer requested in iid
);

Retrieves the address of a specified interface on a particular object so that an application can query an object to determine what interfaces it supports.

Returns NOERROR, if successful, or one of these error values:

  • CO_E_OBJNOTCONNECTED
  • E_NOINTERFACE
  • E_OUTOFMEMORY
  • E_INVALIDARG
  • E_UNEXPECTED
  • REGDB_E_IIDNOTREG
Parameter | Description
riid | [in] Interface identifier of the interface to be retrieved.
ppvObj | [out] Address of a variable that receives the address of the specified interface on the object. If the interface specified in riid is not supported by the object, the function returns E_NOINTERFACE. All errors set *ppvObj to NULL.

AddRef

ULONG AddRef(void);
  • Increments a reference count for every new copy of an interface pointer to a specified interface on a particular object.
  • Returns the value of the reference count.

When an interface is fully released, the reference count is zero. This information should be used only for diagnostics and testing.

Release

ULONG Release(void);
  • Decrements the reference count for the specified interface on a particular object.
  • Returns the value of the reference count.

When an interface is fully released, the reference count is zero. This information should be used only for diagnostics and testing.

If the object reference count goes to zero as a result of calling Release, the object is freed from memory.

If the AddRef member function has been called on this object's interface n times and this is the n+1th call to Release, the interface pointer frees itself. An object frees itself if the released pointer is the only pointer and if the object supports multiple interfaces through the QueryInterface member function.


American English Phoneme Representation (Microsoft Speech Platform)

 Microsoft Speech Platform

American English Phoneme Representation

This is a brief introduction to the use and implementation of the SAPI phoneme representations.

Symbolic and Numerical Representation

Application developers can create pronunciations for words that are not currently in the lexicon by using the English phonemes represented in the following table. The phoneme set is composed of a symbolic phonetic representation (SYM).

The application developer will be able to enter the SYM representation to create the pronunciation using the XML PRON tag, or by creating a new lexicon entry. Each phoneme entry should be space delimited.

Tag | Description
PRON SYM | Tag used to insert a pronunciation using symbolic representation.

Example: pronunciation for "hello":

<PRON SYM = "h eh l ow"/>

For improved accuracy, the primary (1), secondary (2) stress markers, and the syllabic markers (-) can be added to the pronunciation.

Example: pronunciation for "hello" using the primary stress (1) and syllabic (-) markers:

<PRON SYM = "h eh - l ow 1"/>

American English Phoneme Table

SYM | Example | PhoneID
- | syllable boundary (hyphen) | 1
! | Sentence terminator (exclamation mark) | 2
& | word boundary | 3
, | Sentence terminator (comma) | 4
. | Sentence terminator (period) | 5
? | Sentence terminator (question mark) | 6
_ | Silence (underscore) | 7
1 | Primary stress | 8
2 | Secondary stress | 9
aa | father | 10
ae | cat | 11
ah | cut | 12
ao | dog | 13
aw | foul | 14
ax | ago | 15
ay | bite | 16
b | big | 17
ch | chin | 18
d | dig | 19
dh | then | 20
eh | pet | 21
er | fur | 22
ey | ate | 23
f | fork | 24
g | gut | 25
h | help | 26
ih | fill | 27
iy | feel | 28
jh | joy | 29
k | cut | 30
l | lid | 31
m | mat | 32
n | no | 33
ng | sing | 34
ow | go | 35
oy | toy | 36
p | put | 37
r | red | 38
s | sit | 39
sh | she | 40
t | talk | 41
th | thin | 42
uh | book | 43
uw | too | 44
v | vat | 45
w | with | 46
y | yard | 47
z | zap | 48
zh | pleasure | 49

Please see International Phonemes for information on other phoneme sets.


International Phoneme Representation (Microsoft Speech Platform)

 Microsoft Speech Platform

International Phoneme Representation

You can create pronunciations for words that are not currently in the lexicon using the phonemes represented in the attached appendices. The proposed phoneme set is composed of a symbolic phonetic representation (SYM).

You can enter the SYM representation to create the pronunciation by using the XML PRON tag, or by creating a new lexicon entry. Each phoneme should be space delimited.

The engine is passed a USHORT structure called SPPHONEID (a number between 1 and n where n is the total number of phonemes for that language). The conversion from the SYM to SPPHONEID occurs in the SAPI PhoneConverter.

Mark Up Tag | Description
PRON SYM | Tag used to insert a pronunciation using symbolic representation

Example: pronunciation for "hello"

<PRON SYM = "h eh l ow"/>

For improved accuracy, the primary (1), secondary (2) stress markers, and the syllabic markers (-) can be added to the pronunciation.

Example: pronunciation for "hello" using the primary stress (1) and syllabic (-) markers:

<PRON SYM = "h eh - l ow 1"/>

SAPI-compliant engines are required to accept the PHONEID representation, and produce an articulation. The specific allophonic articulation is defined by the engine. There is no provision for support of phonemes outside the SAPI phoneme set.

Main goals for defining the language dependent phoneme set:
  • Provide an engine-independent architecture for application developers to create user and application lexicons.
  • Make the English phonetic table simple enough to be used and understood by non-linguists who use the American English phoneme set.

Note on SAPI German Phone Set

The SAPI German phone set collapses two separate German phonemes into one representation. The final -e and -er sounds of a German word are both represented by the symbol "ax", which indicates a schwa. This conflation of the two phonemes can cause problems with words in which the -e and -er phonemes form a minimal pair, such as "koche" (I cook) and "Kocher" (stove). An imperfect workaround is to represent the -er phone using "ax R".

International phoneme use

Using the international phoneme schema, you can create a phoneme set which can be used for each language independently. Using the numeric representation as opposed to the International Phonetic Alphabet (IPA) code will eliminate some of the problems regarding the possible differences in the IPA values for the same phonemes. Hence, an 'r' in English will correspond to a certain number (38) and an 'r' in French may correspond to a different number. It is up to the individual engine to provide the exact IPA value for the two 'r's.

Each language will be associated with a set of phonemes numbered from 1 to X. You can use either the symbolic representation or the number representation to enter the pronunciation.

Please note that consistent pronunciation is NOT a goal, while predictable pronunciation is. Using the phoneme set, an application developer can guarantee a minimal pronunciation, but not the exact allophonic expression. So, the word "first" will always be pronounced as "first", never as "fist" or "feast", etc, but the accent of the engine may be slightly different due to the fact that the internal allophone values may differ

For more information and definitions for international phoneme sets, please see:

  • Chinese Phonemes
  • Japanese Phonemes


Chinese Phonemes (Microsoft Speech Platform)

 Microsoft Speech Platform

Chinese Phonemes

The following table defines the Chinese language phoneme set.

Symbol | PhoneID | Example
- | 1 | Syllable boundary (hyphen)
! | 2 | Sentence terminator (exclamation mark)
& | 3 | word boundary
, | 4 | Sentence terminator (comma)
. | 5 | Sentence terminator (period)
? | 6 | Sentence terminator (question mark)
_ | 7 | Silence (underscore)
+ | 8 | primary stress
* | 9 | secondary stress
1 | 10 | Tone 1
2 | 11 | Tone 2
3 | 12 | Tone 3
4 | 13 | Tone 4
5 | 14 | Tone 5
a | 15 | a 1 fei 1 (rogue)
ai | 16 | ai 4 ren 2 (lover)
an | 17 | an 1 quan 2 (safe)
ang | 18 | ang 1 zang 1 (dirty)
ao | 19 | jiao 1 ao 4 (proud)
ba | 20 | ba 4 ba 5 (dad)
bai | 21 | bai 2 se 4 (white)
ban | 22 | mu 4 ban 3 (board)
bang | 23 | bang 3 jia 4 (kidnap)
bao | 24 | yong 1 bao 4 (embrace)
bei | 25 | bei 3 fang 1 (north)
ben | 26 | ben 4 dan 4 (fool)
beng | 27 | beng 4 tiao 4 (jump)
bi | 28 | bi 2 zi 5 (nose)
bian | 29 | bian 4 hua 5 (change)
biao | 30 | biao 3 ge 2 (table)
bie | 31 | li 2 bie 2 (part with)
bin | 32 | bin 1 ke 4 (guest)
bing | 33 | shi 4 bing 1 (soldier)
bo | 34 | bo 2 dou 4 (wrestle)
bu | 35 | bu 4 xing 2 (walk)
ca | 36 | ca 1 gan 1 (wipe)
cai | 37 | cai 1 ce 4 (guess)
can | 38 | can 1 jia 1 (join)
cang | 39 | cang 1 ying 5 (fly)
cao | 40 | cao 1 chang 3 (playground)
ce | 41 | ce 4 liang 2 (measure)
cen | 42 | cen 1 ci 1 (uneven)
ceng | 43 | ceng 2 jing 1 (once)
cha | 44 | jian 3 cha 2 (check)
chai | 45 | chai 1 hui 3 (demolish)
chan | 46 | chan 3 ye 4 (industry)
chang | 47 | jing 1 chang 2 (often)
chao | 48 | chao 1 yue 4 (exceed)
che | 49 | qi 4 che 1 (automobile)
chen | 50 | chen 2 jiu 4 (old)
cheng | 51 | cheng 2 che 1 (ride)
chi | 52 | chi 2 dao 4 (late for)
chong | 53 | chong 1 man 3 (full of)
chou | 54 | chou 2 hen 4 (hatred)
chu | 55 | chu 2 fa 3 (division)
chuai | 56 | chuai 3 ce 4 (guess)
chuan | 57 | lun 2 chuan 2 (ship)
chuang | 58 | chuang 4 ye 4 (carve out)
chui | 59 | tie 3 chui 2 (hammer)
chun | 60 | chun 1 tian 1 (spring)
chuo | 61 | wo 4 chuo 4 (dirty)
ci | 62 | ci 2 qi 4 (porcelain)
cong | 63 | cong 2 lin 2 (thicket)
cou | 64 | jin 3 cou 4 (compact)
cu | 65 | cu 4 xiao 1 (sales promotion)
cuan | 66 | tao 2 cuan 4 (run away)
cui | 67 | cui 1 cu 4 (press)
cun | 68 | xiang 1 cun 1 (country)
cuo | 69 | cuo 4 wu 4 (error)
da | 70 | da 4 (big)
dai | 71 | dai 4 biao 3 (delegate)
dan | 72 | dan 4 shi 4 (but)
dang | 73 | dang 1 ran 2 (sure)
dao | 74 | dao 1 (knife)
de | 75 | de 5 (function word)
dei | 76 | dei 3 (must)
den | 77 | den 4 (yank)
deng | 78 | ban 3 deng 4 (wooden stool)
di | 79 | di 2 que 4 (certainly)
dia | 80 | dia 3 (coquetry voice)
dian | 81 | dian 3 (dot)
diao | 82 | diao 4 (hang)
die | 83 | die 1 dao 3 (tumble)
ding | 84 | jue 2 ding 4 (decide)
diu | 85 | diu 1 qi 4 (discard)
dong | 86 | dong 1 fang 1 (east)
dou | 87 | zhan 4 dou 4 (struggle)
du | 88 | du 4 jue 2 (stop)
duan | 89 | duan 3 (short)
dui | 90 | dui 4 (right)
dun | 91 | ting 2 dun 4 (halt)
duo | 92 | duo 1 yu 2 (unnecessary)
e | 93 | e 4 (hungry)
ei | 94 | ei 4 (yes)
en | 95 | en 1 hui 4 (favor)
er | 96 | er 3 (ear)
fa | 97 | fa 1 zhan 3 (development)
fan | 98 | fan 4 (rice)
fang | 99 | fang 2 jian 1 (room)
fei | 100 | fei 1 (fly)
fen | 101 | fen 1 bie 2 (separate)
feng | 102 | feng 1 (wind)
fo | 103 | fo 2 (buddha)
fou | 104 | fou 3 ding 4 (denial)
fu | 105 | fu 4 qin 1 (father)
ga | 106 | gan 1 ga 4 (awkward)
gai | 107 | ying 1 gai 1 (should)
gan | 108 | gan 1 jing 4 (neatness)
gang | 109 | gang 1 cai 2 (just)
gao | 110 | gao 1 (tall)
ge | 111 | pin 3 ge 2 (character)
gei | 112 | gei 3 yu 3 (give)
gen | 113 | gen 1 (root)
geng | 114 | geng 4 jia 1 (much more)
gong | 115 | gong 1 ren 2 (worker)
gou | 116 | zu 2 gou 4 (enough)
gu | 117 | gu 4 xiang 1 (hometown)
gua | 118 | xi 1 gua 1 (watermelon)
guai | 119 | qi 2 guai 4 (oddness)
guan | 120 | guan 1 bi 4 (close)
guang | 121 | guang 1 (light)
gui | 122 | gui 3 (ghost)
gun | 123 | gun 4 (stick)
guo | 124 | guo 4 qu 4 (past)
ha | 125 | ha 1 (sound of laugh)
hai | 126 | hai 2 zi 5 (child)
han | 127 | chu 1 han 4 (sweat)
hang | 128 | hang 2 xing 2 (sail)
hao | 129 | hao 3 (good)
he | 130 | he 2 (river)
hei | 131 | hei 1 (black)
hen | 132 | hen 3 (very)
heng | 133 | heng 2 xiang 4 (landscape orientation)
hong | 134 | hong 2 (red)
hou | 135 | hou 2 zi 5 (monkey)
hu | 136 | hu 2 xu 1 (beard)
hua | 137 | hua 4 (picture)
huai | 138 | huai 4 (bad)
huan | 139 | huan 2 jing 4 (environment)
huang | 140 | huang 2 se 4 (yellow)
hui | 141 | hui 1 huang 2 (refulgence)
hun | 142 | hun 2 zhuo 2 (muddy)
huo | 143 | huo 3 (fire)
ji | 144 | ji 2 shi 2 (in time)
jia | 145 | jia 4 qi 1 (holiday)
jian | 146 | jian 3 dan 1 (simple)
jiang | 147 | jiang 1 (river)
jiao | 148 | jiao 1 tong 1 (traffic)
jie | 149 | jie 2 ri 4 (feast)
jin | 150 | jin 3 zhang 1 (strain)
jing | 151 | gan 1 jing 4 (neatness)
jiong | 152 | jiong 3 po 4 (embarrassed)
jiu | 153 | jiu 3 (nine)
ju | 154 | ju 4 zi 5 (sentence)
juan | 155 | juan 3 qu 1 (curl)
jue | 156 | jue 2 ding 4 (decide)
jun | 157 | jun 1 dui 4 (army)
ka | 158 | ka 3 che 1 (truck)
kai | 159 | kai 3 xuan 2 (triumph)
kan | 160 | kan 4 (see)
kang | 161 | di 3 kang 4 (resist)
kao | 162 | kao 3 shi 4 (test)
ke | 163 | ke 3 (thirsty)
kei | 164 | kei 1 (scold)
ken | 165 | ken 3 ding 4 (affirm)
keng | 166 | keng 1 hai 4 (entrap)
kong | 167 | kong 1 qi 4 (air)
kou | 168 | kou 3 (mouth)
ku | 169 | jian 1 ku 3 (trial)
kua | 170 | kua 1 jiang 3 (praise)
kuai | 171 | kuai 4 (fast)
kuan | 172 | kuan 1 kuo 4 (openness)
kuang | 173 | kong 1 kuang 4 (void)
kui | 174 | kui 1 qian 4 (owe)
kun | 175 | kun 4 nan 2 (hard)
kuo | 176 | kuo 4 da 4 (enlarge)
la | 177 | la 4 jiao 1 (hot pepper)
lai | 178 | lai 2 (come)
lan | 179 | lan 2 se 4 (blue)
lang | 180 | lang 2 (wolf)
lao | 181 | lao 3 (old)
le | 182 | kuai 4 le 4 (happy)
lei | 183 | lei 2 (thunder)
leng | 184 | leng 3 ku 4 (steeliness)
li | 185 | li 2 (pear)
lia | 186 | lia 2 (two)
lian | 187 | lian 3 (face)
liang | 188 | li 4 liang 4 (power)
liao | 189 | zuo 2 liao 4 (seasoning)
lie | 190 | lin 3 lie 4 (severe)
lin | 191 | lin 3 lie 4 (severe)
ling | 192 | ling 2 mu 4 (mausoleum)
liu | 193 | liu 2 dong 4 (flow)
lo | 194 | lo 5 (function word)
long | 195 | long 2 (dragon)
lou | 196 | lou 4 (leak)
lu | 197 | lu 4 di 4 (land)
luan | 198 | hun 4 luan 4 (chaos)
lue | 199 | ce 4 lue 4 (tactic)
lun | 200 | yi 4 lun 4 (discuss)
luo | 201 | xia 4 luo 4 (whereabouts)
lv | 202 | lv 4 se 4 (green)
ma | 203 | ma 3 (horse)
mai | 204 | mai 2 zang 4 (bury)
man | 205 | man 3 zu 2 (satisfy)
mang | 206 | cong 1 mang 2 (hurry)
mao | 207 | mao 1 (cat)
me | 208 | shen 2 me 5 (what)
mei | 209 | mei 2 you 3 (no)
men | 210 | wo 3 men 2 (we)
meng | 211 | meng 4 (dream)
mi | 212 | hun 1 mi 2 (coma)
mian | 213 | mian 4 ji 5 (area)
miao | 214 | miao 4 (temple)
mie | 215 | mie 4 jue 2 (annihilation)
min | 216 | ren 2 min 2 (people)
ming | 217 | ming 2 bai 2 (clearness)
miu | 218 | huang 1 miu 4 (absurd)
mo | 219 | mo 4 shui 3 (ink)
mou | 220 | mou 2 lue 4 (trick)
mu | 221 | mu 4 biao 1 (target)
na | 222 | na 4 li 3 (there)
nai | 223 | nai 3 nai 5 (grandmother)
nan | 224 | nan 2 fang 1 (south)
nang | 225 | nang 2 kuo 4 (include)
nao | 226 | re 4 nao 4 (liveliness)
ne | 227 | mu 4 ne 4 (numb)
nei | 228 | nei 4 bu 4 (inside)
nen | 229 | nen 4 lv 4 (light green)
neng | 230 | neng 2 gou 4 (be capable of)
ni | 231 | ni 3 (you)
nian | 232 | nian 2 (year)
niang | 233 | gu 1 niang 5 (girl)
niao | 234 | niao 3 (bird)
nie | 235 | nie 4 (bite)
nin | 236 | nin 2 (you)
ning | 237 | an 1 ning 2 (peace)
niu | 238 | niu 2 (bull)
nong | 239 | nong 2 min 2 (farmer)
nou | 240 | nou 4 (weeding)
nu | 241 | nu 3 li 4 (try hard)
nuan | 242 | wen 1 nuan 3 (warm)
nue | 243 | nue 4 dai 4 (abuse)
nuo | 244 | nuo 4 yan 2 (promise)
nv | 245 | nv 3 zi 3 (woman)
o | 246 | o 5 (function word)
ou | 247 | ou 1 yang 2 (Chinese first name)
pa | 248 | hai 4 pa 4 (scare)
pai | 249 | pai 4 qian 3 (send)
pan | 250 | pan 4 tu 2 (betrayer)
pang | 251 | pang 2 da 4 (huge)
pao | 252 | pao 3 (run)
pei | 253 | pei 2 ban 4 (accompany)
pen | 254 | pen 2 di 4 (pan)
peng | 255 | peng 2 pai 4 (surge)
pi | 256 | pi 2 fu 1 (skin)
pian | 257 | qi 1 pian 4 (cheat)
piao | 258 | piao 4 liang 4 (pretty)
pie | 259 | pie 1 kai 1 (put aside)
pin | 260 | pin 2 fan 2 (frequency)
ping | 261 | ping 2 zi 5 (bottle)
po | 262 | po 4 huai 4 (damage)
pou | 263 | pou 2 (hold something with cupped hand)
pu | 264 | pu 2 tao 5 (grape)
qi | 265 | qi 3 qiu 2 (beg)
qia | 266 | qia 4 dang 4 (proper)
qian | 267 | qian 1 xu 1 (humility)
qiang | 268 | qiang 2 da 4 (powerful)
qiao | 269 | qiao 3 miao 4 (artifice)
qie | 270 | xiu 1 qie 4 (shyness)
qin | 271 | qin 1 zi 4 (oneself)
qing | 272 | qing 1 song 1 (easy)
qiong | 273 | qiong 2 (poverty)
qiu | 274 | qiu 2 fan 4 (prisoner)
qu | 275 | qu 1 dong 4 (drive)
quan | 276 | quan 2 bu 4 (all)
que | 277 | que 4 ding 4 (ensure)
qun | 278 | qun 2 zhong 4 (crowd)
ran | 279 | ran 2 hou 4 (then)
rang | 280 | tu 3 rang 3 (soil)
rao | 281 | wei 2 rao 4 (surround)
re | 282 | re 4 (hot)
ren | 283 | ren 2 lei 4 (human being)
reng | 284 | reng 2 ran 2 (all the same)
ri | 285 | ri 4 chu 1 (sunrise)
rong | 286 | rong 2 yao 4 (glory)
rou | 287 | niu 2 rou 4 (beef)
ru | 288 | ru 2 guo 3 (if)
ruan | 289 | rou 2 ruan 3 (soft)
rui | 290 | rui 4 zhi 4 (smart)
run | 291 | shi 1 run 4 (wetness)
ruo | 292 | ruo 4 xiao 3 (puniness)
sa | 293 | sa 1 (three)
sai | 294 | bi 3 sai 4 (compete)
san | 295 | fen 1 san 4 (disperse)
sang | 296 | sang 4 (die)
sao | 297 | da 3 sao 3 (sweep)
se | 298 | yan 2 se 4 (color)
sen | 299 | sen 1 lin 2 (forest)
seng | 300 | seng 1 lv 3 (monk)
sha | 301 | sha 1 chang 3 (battlefield)
shai | 302 | ri 4 shai 4 (be exposed to the sun)
shan | 303 | shan 4 liang 2 (goodness)
shang | 304 | shang 4 mian 4 (top)
shao | 305 | shao 4 nian 2 (youth)
she | 306 | she 2 (snake)
shei | 307 | shei 2 (who)
shen | 308 | shen 2 me 5 (what)
sheng | 309 | sheng 1 yin 1 (voice)
shi | 310 | shi 4 fei 1 (dispute)
shou | 311 | shou 3 (hand)
shu | 312 | shu 4 mu 4 (tree)
shua | 313 | shua 1 zi 5 (brush)
shuai | 314 | shuai 1 da 3 (beat)
shuan | 315 | men 2 shuan 1 (latch)
shuang | 316 | shuang 1 (pair)
shui | 317 | shui 3 (water)
shun | 318 | shun 4 li 4 (all right)
shuo | 319 | shuo 1 (say)
si | 320 | si 4 (four)
song | 321 | song 4 bie 2 (send-off)
sou | 322 | sou 1 cha 2 (search)
su | 323 | su 4 du 4 (speed)
suan | 324 | suan 4 fa 3 (arithmetic)
sui | 325 | sui 1 ran 2 (though)
sun | 326 | sun 3 shi 1 (loss)
suo | 327 | suo 3 yi 3 (so)
ta | 328 | ta 1 men 2 (they)
tai | 329 | tai 4 (too)
tan | 330 | tan 2 hua 4 (talk)
tang | 331 | tang 2 (sugar)
tao | 332 | tao 2 pao 3 (flee)
te | 333 | te 4 bie 2 (special)
tei | 334 | tei 1 (very)
teng | 335 | ben 1 teng 2 (riot)
ti | 336 | ti 1 zi 5 (ladder)
tian | 337 | tian 1 (sky)
tiao | 338 | tiao 4 yue 4 (jump)
tie | 339 | tie 3 (iron)
ting | 340 | ting 1 (listen)
tong | 341 | tong 3 yi 1 (unify)
tou | 342 | tou 2 (head)
tu | 343 | tu 3 di 4 (earth)
tuan | 344 | tuan 2 jie 2 (solidify)
tui | 345 | tui 1 dong 4 (push)
tun | 346 | tun 2 ji 1 (store up)
tuo | 347 | tuo 1 yi 1 (undress)
wa | 348 | qing 1 wa 1 (frog)
wai | 349 | wai 4 mian 4 (outside)
wan | 350 | wan 4 (ten thousands)
wang | 351 | si 3 wang 2 (death)
wei | 352 | wei 3 da 4 (great)
wen | 353 | wen 2 hua 4 (culture)
weng | 354 | lao 3 weng 1 (oldman)
wo | 355 | wo 3 (I)
wu | 356 | wu 2 lun 4 (no matter what)
xi | 357 | xi 1 fang 1 (west)
xia | 358 | xia 4 mian 4 (bottom)
xian | 359 | xian 4 zai 4 (now)
xiang | 360 | xiang 4 (like)
xiao | 361 | xiao 3 (small)
xie | 362 | xie 3 (write)
xin | 363 | xin 1 (new)
xing | 364 | xing 2 dong 4 (act)
xiong | 365 | xiong 2 (bear)
xiu | 366 | xiu 1 xi 5 (break)
xu | 367 | xu 1 yao 4 (need)
xuan | 368 | xuan 1 bu 4 (declare)
xue | 369 | xue 3 (snow)
xun | 370 | xun 2 wen 4 (ask for)
ya | 371 | ya 4 zhou 1 (Asia)
yan | 372 | yan 4 zi 5 (swallow)
yang | 373 | tai 4 yang 2 (sun)
yao | 374 | yao 1 qiu 2 (require)
ye | 375 | ye 2 ye 5 (grandfather)
yi | 376 | yi 1 (one)
yin | 377 | yin 1 yue 4 (music)
ying | 378 | ying 1 gai 1 (should)
yo | 379 | yo 5 (function word)
yong | 380 | yong 3 yuan 3 (forever)
you | 381 | you 2 yu 2 (due to)
yu | 382 | yu 2 (fish)
yuan | 383 | yuan 2 lai 2 (formerly)
yue | 384 | yue 4 (month)
yun | 385 | yun 2 (cloud)
za | 386 | za 2 luan 4 (disorder)
zai | 387 | zai 4 jian 4 (farewell)
zan | 388 | zan 2 men 5 (our)
zang | 389 | ang 1 zang 1 (dirty)
zao | 390 | zao 3 chen 2 (morning)
ze | 391 | ze 2 ren 4 (response)
zei | 392 | zei 2 (thief)
zen | 393 | zan 4 yang 2 (praise)
zeng | 394 | zeng 1 jia 1 (add)
zha | 395 | zha 4 dan 4 (bomb)
zhai | 396 | qian 4 zhai 4 (owe)
zhan | 397 | zhan 4 li 4 (stand)
zhang | 398 | zhang 1 kai 1 (open)
zhao | 399 | zhao 1 huan 4 (summon)
zhe | 400 | zhe 4 li 3 (here)
zhei | 401 | zhei 5 (this)
zhen | 402 | zhen 1 zheng 4 (real)
zheng | 403 | zheng 4 yi 4 (justice)
zhi | 404 | yi 4 zhi 4 (restrain)
zhong | 405 | zhong 1 guo 2 (China)
zhou | 406 | si 4 zhou 1 (around)
zhu | 407 | zhu 1 (pig)
zhua | 408 | zhua 1 (grab)
zhuai | 409 | zhuai 4 (pull)
zhuan | 410 | zhuan 1 (brick)
zhuang | 411 | zhuang 1 (pretend)
zhui | 412 | zhui 1 (chase)
zhun | 413 | zhun 3 (precise)
zhuo | 414 | zhuo 1 (table)
zi | 415 | zi 4 (character)
zong | 416 | zong 3 (total)
zou | 417 | zou 3 (walk)
zu | 418 | zu 1 (rent)
zuan | 419 | zuan 4 (diamond)
zui | 420 | zui 4 (most)
zun | 421 | zun 1 (respect)
zuo | 422 | zuo 4 (sit)


Japanese Phonemes (Microsoft Speech Platform)

 Microsoft Speech Platform

Japanese Phonemes

SAPI Supported Japanese Phonemes (Katakana)

Symbol | Phonetic | Unicode Value | Remarks
' |  | 0027 | Accent position
+ |  | 002B | Accent boundary
| |  | 007C | Phrase boundary
. |  | 002E | Sentence end (standard)
? |  | 003F | Sentence end (interrogative)
! |  | 0021 | Sentence end (exclamation)
_ |  | 005F | One mora pause
 |  | 309C | Semi-voiced sound
 | a | 30A1 | Modifier
 | a | 30A2 |
 | i | 30A3 | Modifier
 | i | 30A4 |
 | u | 30A5 |
 | u | 30A6 |
 | e | 30A7 | Modifier
 | e | 30A8 |
 | o | 30A9 | Modifier
 | o | 30AA |
 | ka | 30AB |
 | ga | 30AC |
 | ki | 30AD |
 | gi | 30AE |
 | ku | 30AF |
 | gu | 30B0 |
 | ke | 30B1 |
 | ge | 30B2 |
 | ko | 30B3 |
 | go | 30B4 |
 | sa | 30B5 |
 | za | 30B6 |
 | shi | 30B7 |
 | ji | 30B8 |
 | su | 30B9 |
 | zu | 30BA |
 | se | 30BB |
 | ze | 30BC |
 | so | 30BD |
 | zo | 30BE |
 | ta | 30BF |
 | da | 30C0 |
 | chi | 30C1 |
 | di | 30C2 | Deprecated - use 30B8
 | q | 30C3 |
 | tsu | 30C4 |
 | du | 30C5 | Deprecated - use 30BA
 | te | 30C6 |
 | de | 30C7 |
 | to | 30C8 |
 | do | 30C9 |
 | na | 30CA |
 | ni | 30CB |
 | nu | 30CC |
 | ne | 30CD |
 | no | 30CE |
 | ha | 30CF |
 | ba | 30D0 |
 | pa | 30D1 |
 | hi | 30D2 |
 | bi | 30D3 |
 | pi | 30D4 |
 | hu | 30D5 |
 | bu | 30D6 |
 | pu | 30D7 |
 | he | 30D8 |
 | be | 30D9 |
 | pe | 30DA |
 | ho | 30DB |
 | bo | 30DC |
 | po | 30DD |
 | ma | 30DE |
 | mi | 30DF |
 | mu | 30E0 |
 | me | 30E1 |
 | mo | 30E2 |
 | ya | 30E3 | Modifier
 | ya | 30E4 |
 | yu | 30E5 | Modifier
 | yu | 30E6 |
 | yo | 30E7 | Modifier
 | yo | 30E8 |
 | ra | 30E9 |
 | ri | 30EA |
 | ru | 30EB |
 | re | 30EC |
 | ro | 30ED |
 | wa | 30EE | Modifier
 | wa | 30EF |
 | wi | 30F0 | Deprecated - use 30A4
 | we | 30F1 | Deprecated - use 30A8
 | wo | 30F2 |
 | nn | 30F3 |
 | vu | 30F4 |
 | ka | 30F5 |
 | ke | 30F6 |
 | va | 30F7 |
 | vi | 30F8 |
 | ve | 30F9 |
 | vo | 30FA |
 |  | 30FB | Middle dot
 |  | 30FC | Prolonged sound
 |  | 30FD | Iteration
 |  | 30FE | Voiced iteration


Further Reading (Microsoft Speech Platform)

 Microsoft Speech Platform

Further Reading

Further information about the following items can be found at MSDN.

IStream
IServiceProvider


White Papers SAPI 5.4

 Microsoft Speech Platform

White Papers

The following items are covered in this section:

  • Speech Recognition Properties
  • TTS Engine Vendor Porting Guide
  • SR Engine Vendor Porting Guide
  • Object Tokens and Registry Settings
  • VendorPreferred Attribute
  • Simple TTS Guide
  • SAPI 5.1 64-bit Issues
  • Speech Telephony Application Guide
  • Using the SpAudioPlug Sample Audio Object
  • Audio Object
  • XML TTS Tutorial
  • Text Normalization
  • Using Microsoft Foundation Class (MFC) to Automate SAPI
  • Persisting Recognized WAV Audio from the SR Engine
  • Using WAV File Input with the SR Engines


Speech Recognition Properties - Microsoft Speech Platform (Server)

 Microsoft Speech Platform (Server)

Speech Recognition Properties

Introduction

This document describes the ISpProperties elements for speech recognition (SR) engines that comply with SAPI 5. This whitepaper will serve to define these attributes only for SR engines. Application developers hoping to build a speech recognition engine compliant with SAPI 5 should reference this document. For more information, refer to the help documents in the Microsoft Speech Platform (Server) SDK.

ISpProperties

ISpProperties is an interface that enables the SR and TTS engines to get or set various attributes for an object. The attributes are passed to the engine via the ISpProperties interface. ISpProperties are identified by a unique LONG value. SAPI defines certain attributes known as system attributes. The range of these attributes is from 0x0001 to 0xffff. Vendor ISpProperties attributes are defined by a unique high word value (two ANSI Characters that identify the engine vendor).

Attributes may be LONGs, strings, or memory addresses.

SR Properties

The following table lists the SR properties that are set by the application and passed to the SR engine via SAPI. These attributes are not required for SAPI compliance. However, the ranges accompanied by the attributes are required values and the exact interpretation of the values is left to the SR engine. The different implementation is defined by each property. The SAPI ranges and defaults for each property are also shown.

dwAttrib Value

WCHAR Value

Meaning

Range

SPPROP_RESOURCE_USAGE

ResourceUsage

The ResourceUsage specifies the engine CPU consumption. As the resource usage increases, so does the required CPU power.

0 - 100

default = 50

SPPROP_HIGH_CONFIDENCE_THRESHOLD

SPPROP_NORMAL_CONFIDENCE_THRESHOLD

SPPROP_LOW_CONFIDENCE_THRESHOLD

HighConfidenceThreshold

NormalConfidenceThreshold

LowConfidenceThreshold

The threshold values are used to divide a confidence scale into four portions: rejected, low, medium, and high. The location of the low confidence, normal confidence, and high confidence markers control how the confidence of a word is labeled. The HighConfidenceThreshold (HCT) separates the high and medium confidence range. The NormalConfidenceThreshold (NCT) separates the medium and the low confidence thresholds. The LowConfidenceThreshold (LCT) separates the low and rejected confidence range.

Note: SPPROP_LOW_CONFIDENCE_THRESHOLD is not used by the Microsoft Speech Platform (Server).

If the all three confidences are equal to 0, then all words will have high confidence. If all three confidences are equal to 100, then all words will have low confidence.

0 - 100

default

LCT = 20

NCT = 50

HCT = 80

SPPROP_REJECTION_CONFIDENCE_THRESHOLD

CFGConfidenceRejectionThreshold

The speech recognition engine accepts full utterances with confidence scores above or equal to this threshold, and rejects full utterances with phrase confidence scores below this threshold. This property accepts the following values:

  • The value -1 causes the engine to use its default value.
  • A value in the range of 0-100 sets the phrase confidence rejection threshold to the specified value. If this value is set to 0, the speech recognition accepts all utterances. If this value is set to 100, the speech recognition engine rejects all utterances.

This property is not to be confused with SPPROP_HIGH_CONFIDENCE_THRESHOLD, SPPROP_NORMAL_CONFIDENCE_THRESHOLD, or SPPROP_LOW_CONFIDENCE_THRESHOLD, which are used to determine how any given confidence value is categorized (low, medium, or high).

-1

0-100

SPPROP_RESPONSE_SPEED

ResponseSpeed

This indicates the amount of silence the engine looks for before completing a recognition. This attribute is used when the recognition is not ambiguous. For example, in the case of a context-free grammar (CFG) which has two sentences: 1) new game please and 2) new game, a non-ambiguous recognition would be "new game please."

0 - 10,000 ms

SPPROP_COMPLEX_RESPONSE_SPEED

ComplexResponseSpeed

This indicates the amount of silence that the engine will look for before completing a recognition. This attribute is used when the recognition is ambiguous. For example, in the case of a CFG which has two sentences: 1) new game please and 2) new game, an ambiguous recognition would be "new game." This property's value must be greater than the ResponseSpeed value.

ResponseSpeed - 10,000

SPPROP_ENGINE_THREAD_PRIORITY

EngineThreadPriority

Sets the priority of the engine thread(s). The range of permitted values is defined by the OS.

  • The minimum value is min(THREAD_PRIORITY_IDLE,THREAD_PRIORITY_HIGHEST)
  • The maximum value is max(THREAD_PRIORITY_IDLE,THREAD_PRIORITY_HIGHEST)

The values of these constants are in defined winbase.h.

Defined by the OS

SPPROP_ADAPTATION_ON

AdaptationOn

Indicates whether the recognition engine should adapt the acoustic model.

1 or 0

default = 1

SPPROP_PERSISTED_BACKGROUND_ADAPTATION

PersistedBackgroundAdaptation

Turns background adaptation on or off, and persists the setting in the registry.

0 or any nonzero value

default = 1 (adaptation is on)

SPPROP_PERSISTED_LANGUAGE_MODEL_ADAPTATION

PersistedLanguageModelAdaptation

Controls whether language model adaptation is performed, and persists the setting in the registry. This controls whether new words are learned and the ability to learn how the user combines words to form sentences.

0 or any nonzero value

default = 1 (adaptation is on)

SPPROP_ASSUME_CFG_TRUSTED_SOURCE

AssumeCFGFromTrustedSource

Bypasses file integrity checks when loading a CFG, to reduce load time. This should *only* be used by applications that can guarantee that the CFG they are loading has previously been compiled by the application (or by another application it trusts) and has been stored in a secure location where it could not be edited by a malicious agent.

0 (default - property is OFF)

1 (property is ON)


VendorPreferred Attribute SAPI 5.4

 Microsoft Speech Platform

VendorPreferred Attribute

VendorPreferred is an attribute used by a token. The token may be for either a speech recognition (SR) engine or a text-to-speech (TTS) voice. It indicates that the vendor has a preference for a particular token if the vendor has more than one token installed, and that all tokens satisfy other requirements. However, this preference is considered only if the system does not already have a default selected.

For example, a TTS system may have three voices installed by the same vendor: Mike, Mary, and Sam. At various points in the application or in SAPI, the programmer would want to know what the default engine is for the current user. If the user has already chosen one, or the system administrator has set one up, that default is used and the VendorPreferred key is never evaluated. If no default is available, SAPI selects one based on, among other values, VendorPreferred.

For SAPI to select a default, the language of the user (which can be retrieved by SpGetUserDefaultUILanguage) is considered first. If a specific provider has multiple tokens installed, which all support the specified language, the one marked VendorPreferred becomes the default. Only one token should be marked as the VendorPreferred; however, if more than one is marked, SAPI automatically selects one. In any case, the selected token becomes the default for that category.

This process only applies if the user has not already chosen a default. Once the user chooses a default, VendorPreferred is not looked at further. However, a caller can also use the VendorPreferred attribute to look for a match for a specific vendor. For example, a user could call SpEnumTokens(SPCAT_VOICES, L"Vendor=Microsoft;VendorPreferred", ...) to ensure that they get Microsoft's pick for their voice, or similarly for the SR engine.


Object Tokens and Registry Settings SAPI 5.4

 Microsoft Speech Platform

Object Tokens and Registry Settings

1 Contents

1 Contents. 1

2 Summary.. 2

3 Overview: Tokens, Categories and the Registry.. 2

3.1 Tokens. 2

3.2 Categories. 5

3.3 TokenIDs and CategoryIDs. 7

3.4 User Defaults. 7

3.5 Token Enumerators. 8

4 Using Tokens and Categories. 9

4.1 Helper Function Examples. 9

4.2 Enumerating tokens. 11

4.3 Instantiating an Object from a Token.. 14

5 Tokens and Categories For Engine Developers. 15

5.1 Making Resources Available Through SAPI15

5.2 Associating Files with Tokens. 15

5.3 Inspecting UUnderlying Keys of a Token.. 16

5.4 Creating New Keys in the Registry.. 16

6 Registry Settings. 17

6.1 Category: Voices. 18

6.2 Category: Recognizers. 19

6.3 Category: RecoProfiles. 22

6.4 Category: AudioInput. 23

6.5 Category: AudioOutput. 23

6.6 Category: AppLexicons. 23

6.7 Category: PhoneConverters. 23

6.8 UserLexicons. 24

7 Index of Tables. 24

2 Summary

This document is intended to help developers of speech-enabled applications discover and use resources (Voices/Recognizers) on a computer that has SAPI installed. A speech-enabled application is one that attempts to either recognize or synthesize speech.Developers of speech recognition (SR) and speech synthesis (Text to Speech or TTS) engines make their resources available to applications.

This spec answers the following questions:

· What are Tokens and Categories in SAPI?

· Where is information about tokens stored in the Registry?

· How does an application find tokens and initialize resources (i.e., Voices or Recognizers) from them?

· What are the SAPI-defined attributes that engines should document in the registry?

· How are files associated with tokens?

Note:

The Speech SDK documentation section on Object Tokens, which provides a complete description of the ISpObjectToken and ISpObjectTokenCategory and their methods, complements this document.

3 Overview: Tokens, Categories and the Registry

3.1 Tokens

A token is an object representing a resource that is available on a computer, such as a voice, recognizer, or an audio input device. A token provides an application an easy way to inspect the various attributes of a resource without having to instantiate it. The Vendor of a Recognizer, and Gender of a Voice are examples of attributes of resources. In many cases, applications should use SAPI-provided helper functions for common scenarios. For example, an application can use the SpCreateBestObject helper function to rapidly create the object, given a certain type of resource. The application can also query for tokens meeting certain criteria without using the helper function. To do this, the application calls the EnumTokens method on the ISpObjectTokenCategory interface to get an enumerator, and inspect the tokens in the enumerator further if it chooses to. Finally, the application selects one of the tokens in the enumerator to instantiate a resource. Once the resource (such as SR Engine) is instantiated, if it implements the ISpObjectWithToken interface, then it is handed a pointer to the token that was used to create it. This way, the resource contains a handle to more information about itself.

Conceptually, a token contains the following information:

· The language-independent name. This is the name that should be displayed wherever the name of the token is displayed. It is marked as (Default) in the registry. The implementer of the token may also choose to provide a set of language-dependent names in several languages.

· The CLSID used to instantiate the object from the token.

· A set of Attributes, which are the only set of queriable values in a token. This means SAPI provides a mechanism to query for tokens whose attributes match certain values. Details on how to query for tokens that match a set of attributes are in Sections 4.1 and 4.2.

A token may also contain the following:

· If a token has user interfaces (UIs), such as the properties of a Recognizer or a wizard to customize a Voice to display, then the token will also contain the CLSID for the COM object used to instantiate each type of UI.

· The set of Files from which SAPI returns the paths to all the associated files for the token.

SAPI stores information about tokens in the registry. A token is represented in the registry by a key and the keys underlying keys and values. When an application queries SAPI for tokens of all the female voices on the computer, SAPI will look at the HKEY_LOCAL_MACHINE\Software\Microsoft\Speech\Voices area. This corresponds to a Category and categories are discussed in the Section 3.2. SAPI searches for tokens that match the criteria (in this case, a voice with the Gender attribute set to female) and uses one of these matching tokens to initialize the voice. The application may also specify a different fully qualified registry path to specify any non-standard (from a SAPI) location in the registry for SAPI to search for a token. In addition to the keys SAPI recommends, the entry for the token may contain any other bits of information that the implementer of the token can store here. In the registry, a token looks like this:

Table 1 Parts of a Token in the Registry

RegKey

ValueName

Sample Value

Comments

SampleTokenKey

Required - This is the RegKey for the Token.

(Default)

Joe

Required - Language Independent Name.

409

Joe

Name in Hex LangID 409, which is English. There may be several of these rows, one for each LangID in which the Token has a name. Note, no leading 0x before the LangID.

809

Joe

CLSID

{8021D50E-D93C-4075-8504-FC4E124D64E9}

Required - Sample CLSID for object which instantiates the token.

SampleTokenKey/Attributes

Attributes for the token are under this key.

Language

409;809

There may be several of these rows, one for each attribute that is queriable. See Section 4 for an explanation of each of the attributes.

Vendor

VoiceVendor

In the registry, this looks like:

Figure 1 A Token Key in the Registry

The Attributes key contains all the queriable values for the token. Section 4.2 discusses in detail how an application queries a token.

Figure 2 Attributes of a Token

If the token is capable of displaying UI, then each UI has its own key under the token. Fig 3 shows the token for a Recognizer that supports four types of UI: AddWord, EngineProperties, MicTraining and UserTraining, as well as the CLSID underlying each UI type.

Figure 3 A Token that supports UI has a token for each UI type

SAPI provides a comprehensive set of helper functions for the common scenarios using tokens. Section 4.1 provides a number of examples. SAPI also provides a way for engines and applications to implement tokens in their own proprietary manner. See Section 3.4 on token enumerators, for further discussion. Sections 4 and 5 explore common scenarios using these interfaces from application and engine coding perspectives.

3.2 Categories

A ObjectTokenCategory (hereafter referred to as category) is the highest level of grouping of registry entries in SAPI. A category is a class of tokens (or of resources, since each token represents an actual resource on the computer). Intuitively, a category is a type of SAPI resource. It is represented in the registry by a key containing one or more token keys under it. It is created and manipulated using helper functions such as SpCreateDefaultObjectFromCategoryID or methods on the ISpObjectTokenCategory interface. Please refer to the SAPI documentation for details on either of these. Examples of categories are Recognizers and Voices. Figure 4 shows the default SAPI categories, with the category Voices selected.

Figure 4 The Category Voices

SAPI organizes tokens in the Registry under seven categories.

By default, the following tokens for six of the SAPI categories are located under HKEY_LOCAL_MACHINE\Software\Microsoft\Speech (HKLMS). This is where all system-specific SAPI keys and values should be stored as recommended by Windows Application guidelines. Examples include settings and files for Voices and the Recognizers ( also known as Speech Recognition engines) installed on a computer, as shown in Figure 1.

1. Voices

2. Recognizers

3. AppLexicons

4. AudioInput

5. AudioOutput

6. PhoneConverter

The tokens for the other category, Recoprofiles, are located under HKEY_CURRENT_USER\Software\Microsoft\Speech (HKCUS).HKCUS also contains all other user-specific keys and values in the registry, such as user defaults for Voices, Recognizers, as well the location of the user lexicon file.

Categories contain the following items:

· A single key called Tokens, and the keys for the tokens that belong to that category under it. For example, the Voices category has a key for the voice called Manuel. All the keys and values for Manuel are located under HKLMS/Tokens/Manuel.

· Keys for token enumerators. A token enumerator is a special type of token that generates other tokens for the same category. This token provides a way for Vendors to generate tokens that are generated in non-standard way, such as, reading data from a stored file stored. Those engine vendors following SAPI guidelines for registering resources (Sections 4 and 5) can safely ignore these and regard them as generators for another set of tokens. Section 3.4 explains token enumerators in more detail.

3.3 TokenIDs and CategoryIDs

A CategoryID uniquely identifies a category in the registry. For SAPI defined categories they take the form of HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\{CategoryName}. For example, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Recognizers\ for the Recognizers category. All SAPI CategoryIDs should be referenced using the constants defined in sapi.idl file:

1. SPCAT_AUDIOOUT

2. SPCAT_AUDIOIN

3. SPCAT_VOICES

4. SPCAT_RECOGNIZERS

5. SPCAT_APPLEXICONS

6. SPCAT_PHONECONVERTERS

7. SPCAT_RECOPROFILES

Similarly, TokenIDs uniquely identify tokens in the registry. For tokens located in SAPI defined categories, they take the form of:

· CATID\Tokens\TokenKeyName - a static token from the registry. For example, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Recognizers\MSASREnglish

· CATID\TokenEnums\TokenEnumKeyName - a static token from the registry that represents a token enumerator. This token instantiates a token enumerator used to enumerate dynamic tokens. SAPI uses this for its own implementation of audio input and output to list just the channels available on the computer at runtime. Token enumerators can also read tokens from other areas of the registry, or from remote computers. For example, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\AudioOutput\DSoundAudioIn

· CATID\TokenEnums\TokenEnumKeyName\ - a dynamic token representing the default token that the specified token enumerator generates. For example, SPDSOUND_AUDIO_IN_TOKEN_ID creates the default Dsound audio in an object. For example: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\AudioOutput\DSoundAudioIn\

· CATID\TokenEnums\TokenEnumKeyNameEnumExtra - a specific dynamic token from the specified token enumerator. For example: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\AudioOutput\DSoundAudioIn\Direct Sound Crystal WDM Audio, which generates the Direct Sound Crystal WDM audio object.

3.4 User Defaults

In addition to the category defaults mentioned in Section 3.2, the categories Voices, Recognizers, AudioInput, AudioOutput and RecoProfile, also have user defaults and settings. As shown in Figure 5, these are located in the HKCUS area, under their respective category keys. Section 6 explains each category of tokens. This section also lists out the user-specific entries in the HKCUS and the system-wide entries in HKLMS.

Figure 5 The User category for Recognizers

3.5 Token Enumerators

Note: This section is relevant only forEngine or Application developers who need to store tokens in a separate part of the registry or even on the file system, and dynamically enumerate them.

SAPI provides a way for third parties to store their registry settings without following any of the SAPI-recommended guidelines. SAPI can find these tokens as long as the parties have implemented token enumerators. Token enumerators are COM objects that enumerate the necessary entries for the tokens under it. All token enumerators are stored under CategoryName/TokenEnums. Each token enumerator listed under a category needs to have the CLSID of the COM object that implements it under the token enumerator.

The token enumerator

· Must implement the methods Next, Skip, Reset, Clone, Item, GetCount on the IEnumSpObjectToken interface.

· May choose to implement methods SetObjectToken and GetObjectToken on ISpObjectWithToken interface. As mentioned in the end of Section 3.1, these give a resource a handle to the token that was used to instantiate it.

These tokens can be located in a separate part of the registry or somewhere else (possibly on the flusters). It is the responsibility of the token enumerator to return correctly on the above methods so an application does not know the difference between tokens coming from the token enumerator and tokens coming from the SAPI-specific part of the registry.

SAPI itself uses token enumerators only for the AudioInput and AudioOutput categories. Refer to Sections 6.4 and 6.5 for more details. Note that the token enumerator for the MMSYS audio object creates its tokens from keys that are under it.

The following is an example of what a TokenID for a token located under a token enumerator looks like: CategoryName/TokenEnums/TE1/XXX where (i) TE1 is a sample token enumerator and (ii) XXX is a reference to one of the tokens generated by TE1. On a call to the helper function SpCreateCreateNewToken giventhe TokenID above, the IEnumSpObjectToken returned by the token enumerator TE1 to SAPI includes all tokens. SAPI then goes through each token (those returned by token enumerators and those under the tokens key) to find the one that has a Token name matching XXX.

Table 2 Parts of the AudioInput token enumerator

RegKey

ValueName

Sample Value

Comments

HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Speech\AudioInput\

This is the category.

DefaultDefaultTokenID

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\AudioInput\TokenEnums\MMAudioIn\

This is the TokenID for the default token for this category. If the DefaultTokenID is present, it will supercede this default token for the category. Details in section 4.2

HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Speech\AudioInput\TokenEnums

HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Speech\AudioInput\TokenEnums\MMSys

This is the MMSys token enumerator

CLSID

{GUID}

This is the CLSID for the COM object that implements the MMSound token enumerator.

Figure 6 AudioInput token enumerator in the registry

Figure 6 illustrates how the AudioInput token enumerator looks in the registry.

4 Using Tokens and Categories

4.1 Helper Function Examples

A SAPI 5 application needs to find tokens and instantiate objects that meet certain criteria from the resources available on a computer. Helper functions distributed in the sphelper.h file are the recommended way for applications to interact with tokens and categories whenever possible. Table 3 provides a list of helper functions and the scenarios they address. The helper functions have been broken up into Common Helper Functions and Engine Developer Helper Functions based on likelihood of use. If the specific helper function is not found in either section, refer to the SAPI documentation for the comprehensive listing.

Table 3 Common Helper Functions

Helper Function | Action | Example Helper Function Call
SpGetDefaultTokenFromCategoryID | Creates the default token from a CategoryID. The last argument tells SAPI to create the token if it does not currently exist. | CcomPtr<ISpObjectToken> m_cpEngineToken; hr = SpGetDefaultTokenFromCategoryId(SPCAT_RECOGNIZERS, &m_cpEngineToken);
SpFindBestToken | Finds the most appropriate token given a set of required and optional criteria. For details on attribute matching see Section 4.2 | CComPtr<ISpObjectToken> cpTokenEng; hr = SpFindBestToken(SPCAT_RECOGNIZERS, L"Language=409", L"VendorPreferred", &cpTokenEng);
SpEnumTokens | Returns a token enumerator containing all tokens meeting a set of required and optional attributes. Tokens in the enumerator are sorted in the order specified in the Section 4.2. | CcomPtr<IEnubjectTokens> cpIEnum; hr = SpEnumTokens(SPCAT_VOICES, L"Gender=Female;Language=409", L"Vendor=VoiceVendor1;Age=Child , &pEnum);
SpCreateDefaultObjectFromCategoryID | Creates the default object in a category, such as AudioInput or Recognizer | CComPtr<ISpVoice> cpVoice; SpCreateDefaultObjectFromCategoryID(SPCAT_VOICES, &cpVoice);
SpCreateBestObject | Instantiates a resource that best matches a set of required and optional criteria. For details on attribute matching see Section 4.2 | CComPtr<ISpVoice> cpVoice; SpCreateBestObject(SPCAT_VOICES, L"Vendor=VoiceVendor1;Age=Child", LGender=Female, &cpVoice);
SpCreateObjectFromToken | Creates an object from a token. | CComPtr<ISpVoice> cpVoice; CComPtr<ISpObjectToken> cpVoiceToken; //--like last step SpFindBestToken(SPCAT_VOICES, L"Language=409", L"VendorPreferred", &cpVoiceToken); /--now create object SpCreateObjectFromToken(cpVoiceToken, &cpVoice); }

Table 4 Engine Developer Helper Functions

Helper Function | Action | Example Helper Function Call
SpCreateNewToken | Creates a new object token in the registry with CategoryID, but without specifying a keyname. This creates a token with a GUID as its registry key. | CComPtr<ISpObjectToken> cpUserToken; hr = SpCreateNewToken(SPCAT_RECOPROFILES, L"", &cpUserToken); cpUserToken;
SpGetTokenFromID | Creates a token from a TokenID of an enumerator or a new token if the token does not already exist. The last argument of FALSE tells SAPI not to create the token if it does not already exist. | CComPtr<ISpObjectToken> cpAudioInTok; hr = SpGetTokenFromID(SPCAT_AUDIOIN, &cpAudioInTok, FALSE)))
SpCreateObjectFromSubToken | Creates an object from a subtoken of a token. In this case, the engine token pEngineToken has the Lts key under it, which in turn has a CLSID value under it. This CLSID is used to instantiate the object. | CComPtr<ISpObjectToken> m_cpEngineToken; hr = SpGetDefaultTokenFromCategoryId(SPCAT_RECOGNIZERS, &m_cpEngineToken); ISpLexicon * m_pLtsLex; HRESULT hr = SpCreateObjectFromSubToken(pEngineToken, L"Lts", &m_pLtsLex);
SpGetSubTokenFromToken | Creates a subtoken under a token. This is useful, for example, when an Engine vendor would like to create a subtoken for custom data under its Recognizer token. | CComPtr<ISpObjectToken> cpSubSubToken; hr = SpGetSubTokenFromToken(&m_cpEngineToken, L"EngineProperties", &cpSubSubToken, TRUE );

4.2 Enumerating tokens

The principal tasks related to tokens and categories that an application needs to accomplish are:

· Enumerating tokens

· Inspecting and instantiating tokens

The two primary ways to enumerate tokens are by the helper function SpEnumTokens, or by the method ISpObjectTokenCategory::EnumTokens. Both methods allow the caller to specify a category and a set of required and optional attributes. The call then returns a token enumerator containing all the tokens matching those criteria. The method is defined as:

HRESULT EnumTokens(

        [in] const WCHAR *pszCatName,

        [in, string] const WCHAR *pReqAttrs,

        [in, string] const WCHAR *pOptAttrs,

        [out] IEnumSpObjectTokens **ppEnum);

When identifying matching tokens under in a category, an application needs to specify a fully qualified category identifier (FQCID). An FQCID is the full registry path to a category, such as H KEY_CURRENT_USER\Software\Microsoft\Speech\Voices. It is recommended that these categories be referenced using the constants defined in the sapi.idl file below, and not using the full string to minimize typos in commonly used registry paths. SAPI maps the constant to the correct hive in the registry and returns matching tokens from the category. For instance, the SAPI defined AudioInput constant (from the sapi.idl file) is:

//--- Categories for speech resource management

const WCHAR SPCAT_AUDIOOUT[]    = L"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\AudioOutput";

Similarly, there are constants for the AudioInput, Voices, Recognizer, Applexicon, PhoneConverter, and RecoProfile categories.

An application may also specify a non-standard registry location by simply providing its FQCID, such as HKEY_CURRENT_USER\Software\TTSVendor1\Speech\Voices

In both SpEnumTokens and ISpObjectTokenCategory::EnumTokens the following clauses are permitted in the ReqAttrs and OptAttrs strings, separated by semicolons.

Table 5 Query Operators

Condition | Example | Explanation
Exists | Telephony;Dictation | The valuenames Name and Dictation exist in the list of attributes for this token.
One of | Language=409 | At least one of the values of the Valuename Language is 409. There may be other values, like 809, 512 as well.
Not Equals | Age!=Child;Age!=Teen | Values of Age that are neither Child nor Teen.

The tokens are sorted best matches first using the following intuitive rules:

1. Only tokens matching the required attributes are returned.

2. Those tokens matching the optional attributes as well will be before those that just match the required attributes.

3. If there are no required or optional attributes (i.e., both are set to NULL), the first token is the default token for that category. If there is a valid DefaultTokenID in HKLMS/Category, that is returned as the default tokenID. If not, if there is a default tokenID in HKCUS/Category, that is returned. If none of these exist, SAPI searches for a DefaultdefaultTokenID in HKLMS/CategoryName, and that is returned.

4. Matching Rules: If a token matches an optional attribute, it gets a score of 1, otherwise, 0 for that attribute. The optional attributes mentioned earlier in the query string are more significant. These scores are concatenated as shown in Table 7. The tokens are then placed in descending order. This is illustrated in Tables 6 and 7.

5. Tokens having the same score are returned in random order in the enumerator.

A call to EnumTokens could look like:

CComPtr<IEnumSpObjectTokens>  cpEnum;

CComPtr<ISpObjectTokenCategory> cpVoiceCat;

HRESULT hr = cpTokenCategory.CoCreateInstance(CLSID_SpObjectTokenCategory);

const WCHAR Req_Attrs[ ]=L"LanguagesSupported=409";

const WCHAR Opt_Attrs[]=L"Vendor=VoiceVendor1;Age=Child;Gender=Female;

HRESULT hr = cpVoiceCat->EnumTokens(ReqAttrs , OptAttrs , &cpEnum);

// SPCAT_VOICES is defined in sapi.idl

If the following voices are installed on a computer as shown in Table 6:

Table 6 Voices installed on a computer

Voice | Vendor | Age | LanguagesSupported | Gender
Michelle | VoiceVendor1 | Child | 409; 411 | Female
Mary | VoiceVendor1 | Adult | 409 | Female
Jane | VoiceVendor2 | Child | 409 | Female
Frank | VoiceVendor2 | Adult | 411 | Male
Anna | VoiceVendor2 | Adult | 411 | Female

Then the order of the Voices returned in cpEnum will be as shown in Table 7:

Table 7 Scoring of tokens matching optional criteria

Optional Criteria -> | Vendor | Age | Gender | Net Score
Michelle | 1 | 1 | 1 | 111
Mary | 1 | 0 | 1 | 101
Jane | 0 | 1 | 1 | 011

The final order is:

1. Michelle (meets all required criteria, scored 111 on optional criteria)

2. Mary (meets all required criteria, scores 101 on optional criteria)

3. Jane (meets only required criteria, score 11 optional criteria)

If the call to EnumTokens is changed to:

HRESULT hr = cpVoiceCat->EnumTokens(SPCAT_VOICES, NULL, NULL, &cpEnum);

and the users default token in HKCUS\Voices\DefaultTokenID is set to: HKEY_LOCAL_MACHINE\Software\Microsoft\Speech\Voices\Tokens\Jane

then the enumerator cpEnum will contain all the tokens, with Jane being the first token.

What does SAPI do when ISpObjectTokenCategory::EnumTokens is called?

Consider a fictitious category that has both tokens and token enumerators under it. When an application calls the SAPI ISpObjectTokenCategory::EnumTokens, the following things happen:

1. SAPI creates an enumerator called IEnumSpObjectTokens that can enumerate all the matching tokens from these keys under HKLMS/Voices/Tokens.

2. Token enumerators Step (skip this step if not using token enumerators).

a. SAPI searches for a CategoryName/TokenEnums key. If found, it instantiates a token enumerator from each of the tokens under this key, one by one.

b. Each of the token enumerators return an IEnumSpObjectToken containing matching tokens under it that is merged with the IEnumSpObjectToken created in (i).

3. SAPI applies the required attributes so that the IEnumSpObject enumerator contains only those tokens that match these Attributes, then it sorts them according to how well they match the optional attributes (exact rules earlier in Section 4.2).

4. The application searches for an appropriate token and until one is found, it steps through each token, and further checks attributes and strings of each token with ISpObjectToken methods GetData, GetStringValue, and GetDWORD (inherited from ISpDataKey).

5. The application identifies the token it is interested in and calls ISpObjectToken::CreateInstance and QIs the newly created object to see if the newly created object supports the ISpObjectWithToken interface. If it does, SAPI calls ISpObjectWithToken::SetDataKey to give the newly instantiated object a pointer to the token it was instantiated from.

4.3 Instantiating an Object from a Token

Continuing with this example, the application now has a pointer to the enumerator IEnumSpObjectTokens. An application may choose to step through the enumerator with the methods Next, Skip or Reset to find an ISpObjectToken that best meets its needs. Assume that the application is searching for a voice that sounds clear over a telephone. Also assume that such voices typically have a ValueName called SupportsTelephony, which is set to 1. There is no such protocol in SAPI; this is for illustration only. Because this is not a value under Attributes, it cannot be picked up by the standard query mechanism of required attributes. The variable pCurVoiceToken represents a token for that category. In the example below, the category is populated with tokens in cpEnum until a voice is found that also supports Telephony.

ISpObjectToken         *pCurVoiceToken;

bool             fFeature = false;

while (cpEnum->Next(1, &pToken, NULL) = S_OK)

    {

// At this point, all we know is that pToken is a pointer to a Voice token.

      hr = pToken->GetData(L"SupportsTelephony", fFeature);

// Note, ISpObjectToken inherits from ISpDataKey

      if (( SUCCEEDED( hr ) ) && fFeature )

      {

        // this is the token for the Voice we want

        pCurVoiceToken =pToken;

        break;

      }

    }

At this point, store the selected Voice token in pCurVoiceToken. Now create the voice object from this token, so that Speak and other methods on it may be called. To create a voice object, ISpVoice must be created.

EXTERN_C const CLSID CLSID_SpVoice;

CComPtr<ISpVoice>      cpVoice;

// The Application may want to check to see if the token has any associated UI that it needs to display

hr = pCurVoiceToken->IsUISupported(SPDUI_EngineProperties, NULL, 0, NULL, &fSupported);

// The Application calls the UI, or maybe enables a button in its own UI so the user can call the UI

// Next, CoCreate an instance of SpVoice called cpVoice

hr = cpVoice.CoCreateInstance(CLSID_SpVoice);

    if( SUCCEEDED( hr ) )

    {

      // set cpVoice to our selected voice token

      hr = cpVoice->SetVoice(pCurVoiceToken);

    }

At this point the cpVoice object (of type ISpVoice) has been instantiated and is ready to speak, with a call such as:

hr = cpVoice->Speak( L"This audio file was created using SAPI five text to speech.", 0, NULL);

5 Tokens and Categories For Engine Developers

In addition to the enumerating and instantiating tokens, an engine vendor also needs to be able to:

· Create new tokens

· Associate files with tokens

5.1 Making Resources Available Through SAPI

There are several straightforward steps for an SR or TTS engine to be discoverable by SAPI:

1. Make an appropriate entry under the correct CategoryID/Tokens in the registry (details in Section 6).

2. Make an entry under CategoryID/TokenEnums if the vendor prefers dynamic tokens (i.e., the engine registry information is already stored in some other registry location or file). The enumerator should implement the interfaces outlined in Section 3.4.

3. Look at the standard attributes for a category in SAPI and identify the characteristics of the engines so that applications can query the engine for these properties.

4. Hand the SR engine a pointer to the recognition profile token once the RecoInstance has been created.

5.2 Associating Files with Tokens

One of the key issues for an engine vendor is to associate files with tokens in the registry, such as the language model files for a Recognizer or a RecoProfile token. A token can query for all the files under its Files key using the ISpObjectToken::GetStorageFileName method. SAPI searches for the file in a number of known locations. Because of the possibility of roaming, SAPI does not store fully qualified file paths in the registry (such as C:/Documents and Settings/JoeUser/Local Settings/Application Data), but stores paths such as %1c%\Microsoft\Speech\Files\MSASR\SP_81738BE4B81F42F0BFC4BB98B72EB81A.spz instead. SAPI queries the ShGetFolderPath .dll for the users non-roaming directory on the individual computers. The calling application can specify (i) the specific name of the file if any, and (ii) the subdirectory to put the file in. Refer to the GetStorageFileName documentation for the exact interfaces. The engine may append any additional vendor-identifying directory names to indicate engine-specific data. Deleting the tokens with which the files are associated by calling ISpObjectToken::RemoveStorageFileName, will remove files from the file system as well.

Caveat: If roaming is enabled, the users RecoProfiles in the HKCUS hive of the registry will roam (because the entire HKCUS hive roams); the associated files, situated in a non-roaming directory will not. This causes two unexpected effects:

1. When the Recognizer is initiated on the second computer, the Recoprofiles are likely to be missing. The Recognizer needs to be able to handle this and copy the necessary new-profile files. Known issue: Upon roaming the Microsoft SR Engine currently creates a new set of files, but these have entirely different names from the names on the original computer. As a result, when the registry is roamed back to the original computer, the original profile files become orphaned.

2. Subsequently, upon deleting the Recoprofiles from one computer, all the associated files and registry entries on that computer will be deleted. The rest will become orphans, that is, files without pointers to them.

5.3 Inspecting Underlying Keys of a Token

Besides helper functions, keys under a token can be inspected using a recognizer token, and opening the attributes key under it as a DataKey. Then all the ISpDataKey methods are available to inspect the values under the Attributes key. The sample below goes from the Recognizer token, to the attributes key under it, and finally to the Desktop and Telephony strings under that.

hr = SpGenericSetObjectToken(pToken, m_cpEngineObjectToken);

  if(FAILED(hr))

  {

    return hr;

  }

  // Read attribute information

  CComPtr<ISpDataKey> cpAttribKey;

  hr = pToken->OpenKey(L"Attributes", &cpAttribKey);

  if(SUCCEEDED(hr))

  {

    WCHAR *psz = NULL;

    hr = cpAttribKey->GetStringValue(L"Desktop", &psz);

::CoTaskMemFree(psz);

    if(SUCCEEDED(hr))

    {

      // This instance of the engine is for doing desktop recognition

    }

    else if(hr = SPERR_NOT_FOUND)

    {

      hr = cpAttribKey->GetStringValue(L"Telephony", &psz);

      ::CoTaskMemFree(psz);

      if(SUCCEEDED(hr))

      {

        // This instance of the engine is for doing telephony recognition

      }

    }

  }

5.4 Creating New Keys in the Registry

Below is another snippet of code where the Microsoft Sample Engine creates a new entry under a recognition profile. If the Recognition Profile does not exist for the engine (pszCLSID contains a pointer to the Engine GUID), it needs to be created it as well as the Gender and Age values under it.

// Read attribute information from Engine key;pProfile is the RecoProfile token we obtain by calling GetRecoProfile on the Recognition Instance.

hr = pProfile->OpenKey(pszCLSID, &dataKey);

  if(hr = SPERR_NOT_FOUND)

  {

    // This user profile has not been seen before, so create a new registry key to hold info for it

    hr = pProfile->CreateKey(pszCLSID, &dataKey);

    // Now set some default values

    if(SUCCEEDED(hr))

    {

      hr = dataKey->SetStringValue(L"GENDER", L"UNKNOWN");

    }

    if(SUCCEEDED(hr))

    {

      hr = dataKey->SetStringValue(L"AGE", L"UNKNOWN");

    }

    // Now create some temporary file storage for trained models

    // this will create a valuename called SampleEngTrainingFiles and value C:\Documents and Settings\username\application data\microsoft

speech\files\MSASR\LM7454901D23334AAF87707147726EC235.dat

    if(SUCCEEDED(hr))

    {      hr = pProfile->GetStorageFileName(CLSID_SampleSREngine, L"SampleEngTrainingFile", "MSASR\LM%d.dat", CSIDL_FLAG_CREATE, &pszPath);

    }

    // and request a UI for user training or properties - SPDUI_RecoProfileProperties

    hr = AddEventString(SPEI_REQUEST_UI, 0, SPDUI_UserTraining);

6 Registry Settings

This section documents in some detail, the registry settings of each category of tokens in both the HKCUS and the HKLMS hives. Each token entry needs to have the required keys and values for a token as outlined in Table 1. To find the most suitable token on the computer for the Recognizers, Voices, and Phone Converters categories of tokens, an application needs to define a standard set of attributes that applications can query for. It is important for engine vendors to implement these keys exactly as specified because the engines/voices must be discoverable through SAPI to applications.

It is important to note that in addition to the specified keys and values, a vendor may create any keys and values necessary to use as a resource in the registry. SAPI will ignore these values and not disturb them in any way, unless SAPI is uninstalled from the computer.

6.1 Category: Voices

The Voices category enumerates every voice installed on the computer by all TTS engines. The voice tokens should be located under the key:

HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Speech\Voices\Tokens

The requirements for a voice token are listed below, with some sample values.

· Each voice token should meet the requirements for a standard token.

· Voices should document the SAPI-specific attributes that describe them so applications can search for them. Table 8 contains a full listing of Voices attributes and their locations. All Voice attributes are required. Section 3.1 and Section 4.2 have more information about attributes and querying them.

· Voices may have their own Vendor-specific UI implemented by the TTS Engine rendering the voice. If such UI is present, then the UI needs a separate token in the location described in Table 8. The minimum requirement is that the token contain the CLSID of the COM object implementing the UI. Click Properties on the Text-to-Speech tab of the Speech Control Panel to access the Vendor-specific UI. The Properties button will be unavailable if the EngineProperties token for the current default Voice is not supported

Table 8 provides a detailed listing of the registry entries that constitute a sample voice token called VoiceToken1 under HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Speech\Voices\Tokens

Table 8 Voice Registry and Attributes

RegKey

ValueName

Comments

VoiceToken1

Required - This is the RegKey for the Token.

(Default)

Required - language independent name.

409

Name in Hex_LangID 409, which is English. There may be several of these rows, one for each LangID in which the token has a name. Note, no leading 0x before the LangID

809

CLSID

Required - Sample CLSID for object which instantiates the voice.

VoiceToken1/Attributes

Attributes for the Token are under this key.

Age

Required - Value should be Child, Teen, Adult, or Senior depending on Age of TTS Voice. Senior indicates an elderly voice. Vendors may choose to classify some voices as both Senior and Adult.

Vendor

Required  TTS engine Vendor name.

Language

Required - The LCID in hex of language this engine speaks.

Gender

Required - Value should be Male if Male voice, Female if female.

VendorPreferred

Required - If this is the Default voice for the vendor named in vendor.

Name

Required - String representing language independent name

VoiceToken1\UI

Required, if the Voice has UI - UI tokens for the voice token will be stored under this key.

VoiceToken1\UI\EngineProperties

The only SAPI-specific UI token is EngineProperties. Called when the user clicks Properties on the Text-to-speech tab.

CLSID

Required - Sample CLSID for object which instantiates engine-specific UI from Speech properties in Control Panel.

Note: Please refer to the registry entries of the Microsoft recognizer and the Sample Engine, which ship in the SAPI 5 SDK, as an example of how the are entries are created.

There is also a Voices category in the HKCUS hive that stores the following:

· The default TTS rate selected by the user using Speech properties in Control Panel.

· The default voice selected by the user.

Table 9 provides a listing of the user registry entries that constitute a voice token in

HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\Speech\Voices\

Table 9 Voices - User Registry Settings

ValueName

Value

Comments

VoiceToken1

DefaultTokenID

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\MSMary

This points to the default voice selected by the user in Speech properties in Control Panel. It is empty at installation time and gets populated when the user selects a voice.

TTSRate

5

{Scale is 0 to +10, with 0 being slowest}. This applies to all voices on the system for the currently logged on user.

Note: The TTS engine does not need to store any of these values, SAPI takes care of that.

Vendors may choose to store any additional keys and values in the same areas of the registry. Following is additional information relating to voice tokens:

· User specific entries for the voice (such as volume, pitch, rate, and any other information) should be stored in keys and values under HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\Speech\Voices\Tokens\VoiceToken1

This creates a structure in the HKCUS hive parallel to the one in the HKLMS hive.

· Entries applying to all the voices using an engine should be stored under HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\Speech\Voices\Tokens\EngineGUID1

· Non-user entries (pertaining to all users on the computer) for a voice should be stored in keys and values under the category HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Speech\Voices\Tokens

6.2 Category: Recognizers

SAPI enumerates all the SR Engines installed on the computer from the tokens and token enumerators under

HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Speech\Recognizers

Below are the guidelines for registering recognizer tokens:

· Each recognizer token should meet the requirements for a standard token (Table 1).

· Each speech recognition engine installed on the computer should have a recognizer token. If vendors use a single recognizer for recognition in multiple languages (with different acoustic models), or a discrete and a continuous recognizer, they may choose to store the relevant data files and other initialization information under separate tokens, but use the same value for the CLSID. For example, a vendor may use the same recognition engine to recognize both Japanese and English. In this case, there are two tokens, both containing the CLSID of the same recognizer, but associated with different language and acoustic model files stored with the token.

· Recognizers should document the SAPI-specific attributes shown in Table 10 so that applications can search for them. Required attributes are also indicated Table 10.

· Most speech applications written with SAPI will be tested for a specific engine, or a few specific engines, if the application has a clear need for multiple engines. Typically applications will query for and use this engine by default. Use attributes when the application cannot find its preferred engine (or doesnt have one), and needs to locate the most suitable engine installed on the computer for its needs.

· Recognizer tokens may have an Alternate CLSID if they implement alternates.

· Recognizer tokens may have a RecoExtension CLSID for objects that extend SAPI's recognition context.

· The Recognizer may also have a number of engine-specific UIs that it exposes to SAPI. There should be a separate key under {Recognizer TokenID}/UI/ for each such UI supported. The keys are listed and documented in Table 10 below.

Table 10 provides a detailed listing of the registry entries that constitute a sample voice token called VoiceToken1 under HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Speech\Recognizers\Tokens

Table 10 Sample Entries of a Recognizer token

RegKey

ValueName

Comments

RecognizerToken1

Required - This is the RegKey for the Token.

(Default)

Required - Language Independent Name

409

Name in Hex_LangID 409, which is English There may be several of these rows, one for each LangID in which the token has a name. Note, no leading 0x before the LangID

AlternatesCLSID

CLSID for the object that implements alternates.

RecoExtension

CLSID for the object that extends the recognition context provided by SAPI.

RecognizerToken1\Attributes

Vendor

Required - Company Name

Language

Required - The LCIDs in hex of the language(s) this engine recognizes. Typically this is only one per recognizer token. Recognizers recognizing multiple languages can expose that in the manner shown. In addition, a value of 409;9 indicates that the Recognizer recognizes generic English (American, British, Australian, etc.).

SpeakingStyle

Required - Value should be Discrete if the engine requires pauses between words for recognition. Recognizers without this requirement should have Discrete;Continuous for this value.

Dictation

Required - If the engine supports dictation, it must contain this value.

CommandAnd Control

Required - If the engine supports command and control. This value must be there if the engine supports Command and Control.

Desktop

The engine supports desktop audio.

Telephony

The engine is configured to recognize audio coming in from a telephony channel.

VendorPreferred

This token is the vendors default token.

Alternates

Value is CC if the engine supports Command and Control alternates. Value is Dictation if it supports dictation alternates. If both types of alternates are supported, then the value should be CC;Dictation

Hypotheses

The engine returns hypotheses before final recognition.

WordSequences

Value is Trailing if the engine supports word sequence elements in CFGs, at the end of rule. Value should be Anywhere;Trailing if word sequence elements is supported anywhere in a rule. The presence of this attribute indicates the SR engine supports the Text-Buffer functionality. Applications can test for the presence of this attribute and if available, ISpRecoGrammar::SetWordSequenceData and ISpRecoGrammar::SetTextSelection may be used.

DictationInCFG

Value is Trailing if the engine supports dictation element in CFGs, as defined by SAPI at the end of rule. Value should be Anywhere;Trailing if dictation element is supported anywhere in a rule. Dictation elementisan element in a CFG that loads a SLM and returns the recognition result to the application. Refer to SAPI documentation for additional information.

WildcardInCFG

Value should be Trailing if the engine supports garbage elements at the end of a rule in a CFGs, as defined by SAPI. Value should be Anywhere;Trailing if garbage elements are supported anywhere in a rule. Garbage is an element in a rule that the engine doesnt recognize but recognizes the rest of the phrase from a CFG. Refer to SAPI documentation for additional information on Garbage.

UPSPhoneSet

Indicates whether an engine supports the Universal Phone Set (UPS), a phonetic alphabet created by Microsoft for specifying pronunciations. If the attribute is present, the engine supports UPS.

RecognizerToken1\UI

Required - If the Voice has UI this key stores UI tokens for the voice token.

RecognizerToken1\UI\EngineProperties

Required - If engine supports a separate UI for Engine properties. A dialog box appears when the user clicks the Properties button next to the list of Engines on the Speech Recognition tab. If the engine does not support a UI for Engine properties, the Properties button will be unavailable.

CLSID

Required - Sample CLSID for object which instantiates engine-specific UI from Speech properties in Control Panel.

RecognizerToken1\UI\ AddRemoveWord

Required - If engine provides a separate UI for Engine properties. This brings up the dialog box for the user to add a word to the user lexicon and language model, typically from within an application.

CLSID

Required - Sample CLSID for object which instantiates an engine-specific UI from Speech properties in Control Panel.

RecognizerToken1\UI\MicTraining

Required - If the engine provides a separate UI for Microphone wizard. The microphone wizard sets the microphone gain. It appears from within Speech properties in Control Panel or any application that calls it. SAPI checks to see if RecognizerToken1\UI\MicTraining is populated. Click Configure Microphone on the Speech Recognition tab to invoke the CLSID below, which invokes the microphone training wizard. If the MicTraining token is not supported on the current default engine, the button is unavailable in the Speech Control Panel.

CLSID

Required - Sample CLSID for object which instantiates engine-specific UI from Speech properties in Control Panel.

RecognizerToken1\UI\UserTraining

Required - If the engine provides an engine-specific training wizard. The training wizard trains the current default Recognition profile. The training wizard appears from within the Speech properties in Control Panel or any application that calls it. SAPI checks to see if RecognizerToken1\UI\UserTraining is populated. Click Train Profile on the Speech Recognition tab to invoke the CLSID below, which invokes the training wizard. If the UserTraining token under the current default engine is not supported, the button is unavailable in Speech properties in Control Panel.

CLSID

Required - Sample CLSID for object which instantiates an engine-specific UI from Speech properties in Control Panel.

RecognizerToken1\UI\RecoProfileProperties

Required - If the engine-specific profile wizard exists. To set any additional properties on the Recognition Profile such as sensitivity, background adaptation, etc. Click Properties on the Speech Recognition tab next to the list of recognition profiles.

CLSID

Required - Sample CLSID for object which instantiates an engine-specific UI from Speech properties in Control Panel.

There is also a Recognizers category in the HKCUS hive that stores the selected default Recognizer. This is done exactly as for Voices, as shown in Table 8. The CategoryID is:

HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\Speech\Recognizers\

6.3 Category: RecoProfiles

RecoProfiles (RP) is a user-specific, engine-specific data file in which an SR Engine stores the user-specific acoustic and language data. The RP can be thought of as a bag of information that only the engine knows about. The RP also stores the attributes in a few keys under the RPs key in the registry (this is current Speech Recognition tab of Speech properties in Control Panel).

There are two key reasons for a user to have multiple acoustic profiles:

1. In a shared login case (for example, with a Win98 or Millennium home computer where the users typically press cancel to the login dialog box to enter the computer), multiple files allow two or more users to keep languages and acoustic data separate. In this case, the user will need to manually change the profile to the correct one in Speech properties in Control Panel before starting recognition (or an application may provide its own UI to do this).

2. On a laptop, to offer the user the choice of having different acoustic profiles for different acoustic settings, such as home and office.

A typical RP token is located in the user hive in the following location in the registry

HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\Speech\RecoProfiles\Tokens\{ProfileGUID 1}

Initially, SAPI creates only one GUID, called Default User, for the RecoProfile. When the Recognizer is used for the first time, it should create a key under this GUID token of the Recognizer. For instance, if the default recognizer has the GUID XXX, the token HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\Speech\RecoProfiles\Tokens\{ProfileGUID 1}\XXXis created. RecoProfile stores all the files and settings under this key. These settings may include paths to the acoustic and language model files for the profile that are modified during speaker enrollment and subsequently during recognition. It may also contain additional data about the profile that may improve the recognizer accuracy, such as age, gender, microphone gain setting and so on.

Under the Recoprofile token, there is a key for the GUID of each engine that has a profile. When keeping the profile the same, a user switches the default engine (say to YYY) in Speech properties in Control Panel. The new engine, on instantiation (or termination of the session) should create thekey HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\Speech\RecoProfiles\Tokens\{ProfileGUID 1}\YYY FullPathToFil A

All engine-specific (YYY-specific for instance) settings for its RecoProfile should be stored under this key.

6.4 Category: AudioInput

The HKEY_LOCAL_MACHINE/SOFTWARE/MICROSOFT/Speech/AudioInput category contains token enumerators that enumerate all the AudioInput devices present on the computer. There is a token enumerator for each class of AudioInput Device. By default, SAPI 5 will have only a single token enumerator for the MMSys technology. This token enumerator will create an audio token for each AudioInput device (microphone) on the computer and return it when an application or engine calls SpEnumTokens or IenumSpObjectTokens.

The AudioInput category does not have standard attributes, and if multiple technologies are installed, an application needs to inspect each token to find the most suitable one.

Any additional AudioIn token enumerators must meet the requirements for a token enumerator laid out in Table 2. Example of the AudioInput category at:

HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Speech\Recognizers\

Table 11 AudioInput Category

RegKey | ValueName | Comments
TokenEnums\MMSys |  | This is the category.
 | DefaultTokenID | This Default can point to a token enumerator or token.
AudioInput1 |  | This is the key for the audio input device.
AudioInput1\Attributes |  | Attributes for the Token are under this key.
 | Technology | This is the technology, for example, "MMSys"
 | Vendor | This is the vendor name.

6.5 Category: AudioOutput

The HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Speech\AudioOutput category contains token enumerators that enumerate all the audio output devices present on the computer. As in the AudioInput category, there is a token enumerator for each technology of audio output Devices. By default, there will be a single token enumerator for MMsys. Under this, there will be entries for each audio output device installed on the computer.

RegKey | ValueName | Comments
TokenEnums\MMSys |  | This is the category.
 | DefaultTokenID | This Default can point to a token enumerator or token.
AudioOutput1 |  | This is the key for the audio output device.
AudioOutput1\Attributes |  | Attributes for the Token are under this key.
 | NoSerializeAccess | Optional: Override serialization of multiple voices.
 | Technology | This is the technology, for example, "MMSys"
 | Vendor | This is the vendor name.

6.6 Category: AppLexicons

The AppLexicons category stores all the application lexicons SAPI knows about. As in other categories, the lexicons are located under HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Speech\Applexicons\Tokens. When called, the SpLexicon interface enumerates all the applexicons. Applexicons have no attributes, and therefore, there is no way to load only specific Applexicons. These keys will be created by applications to make their own lexicons available through SAPI.

6.7 Category: PhoneConverters

The ISpPhoneConverter interface enables the application to convert from the SAPI character phoneset to the ID phoneset. Phone Converter keys should go under HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Speech\PhoneConverters,

SAPI has a single phoneconverter for each language. An engine can query for the phoneconverter whose language attribute matches the applications language of interest.

6.8 Category: UserLexicons

SAPI stores the user lexicon keys under the HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\Speech\CurrentUserShortcut key. SAPI 5.3 and later support a new feature called "user shortcuts". This is a UserLexicon that maps a spoken term to an expanded printed term. For example, a user may define "my home address" as "12345 NE 678 Av NE Someplace WA 98888" to save them having to dictate and correct the full address. SPCURRENT_USER_SHORTCUT_TOKEN_ID is the token ID used to access this lexicon.

7 Index of Tables

Table 1: Parts of a Token in the Registry. 3

Table 2 Parts of the AudioInput token enumerator9

Table 3 Common Helper Functions. 10

Table 4 Engine Developer Helper Functions. 11

Table 5 Query Operators. 12

Table 6 Voices installed on a computer. 13

Table 7 Scoring of tokens matching optional criteria. 13

Table 8 Voice Registry and Attributes. 18

Table 9: Voices - User Registry Settings. 19

Table 10 Sample Entries of a Recognizer token. 20

Table 11: AudioInput Category. 23


Simple TTS Guide SAPI 5.4

 Microsoft Speech Platform

Simple TTS Guide

This topic explains how to speak to a file and how to speak a file.

Overview

This document is intended to help developers of text-to-speech (TTS) applications use SAPI TTS functionality to speak text into a wav file and to speak a text file. The example illustrates how to use the Speak and SpeakStream methods, how to select a specific voice, and how to set the output audio stream to a wav file. The examples are written in both C++ and Visual Basic.

Speak to a wav file in C++

The following is an example that speaks a text string, "Hello World", to a wav file, "ttstemp.wav" in C++/ATL COM. The SAPI helper class, CSpStreamFormat, and helper method, SPBindToFile, which are defined in sphelper.h, are used in this example to set the audio wav format and bind the audio stream to the specific file. Since SPSF_22kHz16BitMono is the preferred wav format of the Microsoft English TTS engine, it is selected as the output audio format for the better audio effect. In the following example, the ISpVoice::SetOutput() method must be called to set the audio outputs to the right stream. This is because, by default, the output is set to the default audio device. For the simplification, ISpVoice::Speak() is called synchronously. If you want to speak asynchronously, change the speak flag to SPF_ASYNC and call ISpVoice::WaitUntilDone() after the ISpVoice::Speak() waiting for the completion of the speak process.

    HRESULT				hr = S_OK;
    CComPtr <ISpVoice>		cpVoice;
    CComPtr <ISpStream>		cpStream;
    CSpStreamFormat			cAudioFmt;

    //Create a SAPI Voice
    hr = cpVoice.CoCreateInstance( CLSID_SpVoice );

    //Set the audio format
        if(SUCCEEDED(hr))
    {
        hr = cAudioFmt.AssignFormat(SPSF_22kHz16BitMono);
    }

    //Call SPBindToFile, a SAPI helper method,  to bind the audio stream to the file
    if(SUCCEEDED(hr))
    {

        hr = SPBindToFile( L"c:\\ttstemp.wav",  SPFM_CREATE_ALWAYS,
            &cpStream, & cAudioFmt.FormatId(),cAudioFmt.WaveFormatExPtr() );
    }

    //set the output to cpStream so that the output audio data will be stored in cpStream
        if(SUCCEEDED(hr))
    {
        hr = cpVoice->SetOutput( cpStream, TRUE );
    }

     //Speak the text "hello world" synchronously
        if(SUCCEEDED(hr))
    {
        hr = cpVoice->Speak( L"Hello World",  SPF_DEFAULT, NULL );
    }

    //close the stream
    if(SUCCEEDED(hr))
    {
        hr = cpStream->Close();
    }

    //Release the stream and voice object
    cpStream.Release ();
    cpVoice.Release();

Speak to a wav file in automation

The following example is written in Visual Basic. It has the same functionality as the above in C++. After the creation of an SpFileStream object, a default format, SAFT22kHz16BitMono, is assigned to the object so that user does not need to explicitly assign a wav format to it unless a specific wav format is needed. In this example, ISpeechFileStream.Open creates a wav file, ttstemp.wav, and binds the FileStream to the file. The third parameter of ISpeechFileStream.Open is the Boolean, DoEvents. The default of this parameter is set to False. However, the user should always set it to True to display SAPI events while playing back the wav file. If the parameter is set to False, no engine events will be stored in the file, resulting in that no engine events will be fired during the wav file play back.

Dim FileName As String
Dim FileStream As New SpFileStream
Dim Voice As  SpVoice

'Create a  SAPI voice
Set Voice = New SpVoice

'The output audio data will be saved to ttstemp.wav file
FileName = "c:\ttstemp.wav"

'Create a file; set DoEvents=True so TTS events will be saved to the file
FileStream.Open FileName, SSFMCreateForWrite, True

'Set the output to the FileStream
Set Voice.AudioOutputStream = FileStream

'Speak the text
Voice.Speak "hello world"

'Close the Stream
FileStream.Close

'Release the objects
Set FileStream = Nothing
Set Voice = Nothing

Speak a Text File in C++

The following code snippet demonstrates how to speak a text file with a specific voice. In the example, SpEnumTokens, a SAPI helper method, is used to enumerate available voice tokens under the key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens. SpEnumTokens returns a token enumerator containing all tokens meeting a set of required and optional attributes. Tokens in the enumerator are sorted in the order of "best matches" rule. In the following example, the required voice attribute is "Name=Microsoft Sam" and there are no optional attributes. SpEnumTokens here will return all of the voice tokens with "Name=Microsoft Sam" voice attribute. Through IEnumSpObjectTokens ::Next() method, you can find the best voice token and then set it as a current voice by calling ISpVoice::SetVoice() method. Now the "Microsoft Sam" voice has been chosen as a current voice.

Since the voice is speaking text from a file, the ISpVoice::Speak call, a speech flag, SPF_IS_FILENAME, must be set. Please note, you may choose to use ISpVoice:: SpeakStream to speak a file. In that case, you need to call SPBindToFile, a helper function, to bind the text file to an ISpStream object, and then call ISpVoice::SpeakStream.

    HRESULT				hr = S_OK;
    CComPtr <ISpVoice>		cpVoice;
    CComPtr <ISpObjectToken>	cpToken;
    CComPtr <IEnumSpObjectTokens>	cpEnum;

    //Create a SAPI voice
    hr = cpVoice.CoCreateInstance( CLSID_SpVoice );

    //Enumerate voice tokens with attribute "Name=Microsoft Sam"
    if(SUCCEEDED(hr))
    {
        hr = SpEnumTokens(SPCAT_VOICES, L"Name=Microsoft Sam", NULL, &cpEnum);
    }

    //Get the closest token
    if(SUCCEEDED(hr))
    {
        hr = cpEnum ->Next(1, &cpToken, NULL);
    }

    //set the voice
    if(SUCCEEDED(hr))
    {
        hr = cpVoice->SetVoice( cpToken);
    }

    //set the output to the default audio device
    if(SUCCEEDED(hr))
    {
        hr = cpVoice->SetOutput( NULL, TRUE );
    }

    //Speak the text file (assumed to exist)
    if(SUCCEEDED(hr))
    {
        hr = cpVoice->Speak( L"c:\\ttstemp.txt",  SPF_IS_FILENAME, NULL );
    }

    //Release objects
    cpVoice.Release ();
    cpEnum.Release();
    cpToken.Release();

Speak a Text File in Automation

The following code illustrates how to speak a text file in a specific voice in Visual Basic. This example assumes a text file (ttstemp.txt) containing the text to be spoken already exists. ISpeechVoice.SpeakStream is used here to speak an SpFileStream that has been bound to the file.

Dim FileName As String
Dim FileStream As New SpFileStream
Dim Voice As  SpVoice

'Create SAPI voice
Set Voice = New SpVoice

'Assume that ttstemp.txt exists
FileName = "c:\ttstemp.txt"

'Open the text file
FileStream.Open FileName, SSFMOpenForRead, True

'Select Microsoft Sam voice
Set Voice.voice = voice.GetVoices("Name=Microsoft Sam", "Language=409").Item(0)

'Speak the file stream
Voice.SpeakStream FileStream

'Close the Stream
FileStream.Close

'Release the objects
Set FileStream = Nothing
Set Voice = Nothing


SAPI 64-bit Issues SAPI 5.4

 Microsoft Speech Platform

SAPI 64-bit Issues

Overview

This document is intended to help application developers understand and use SAPI functionality on a 64-bit platform. All the discussions below are based on native Win64 programming.

64-bit Programming

Data types:

Win64 supports large memory requirements with 64-bit addressing. All pointers (including handles) are 64 bits long. LONG, INT, BOOL, etc. are still 32 bits long. WPARAM, LPARAM, and LRESULT are pointer based, thus are 64 bits long. Some new data types are defined. For example, fixed-precision data types such as INT32 and INT64; polymorphic data types such as LONG_PTR; specific pointer-precision data types like POINTER_32.

API changes:

There are some API changes in Win64. The constants GWL_xxx, GCL_xxx and DWL_xxx have been undefined. This allows the Win64 compiler to catch errors using the old Get/SetWindowLong APIs. Change your API calls to the new Get/SetWindowLongPtr, and use the newly defined GWLP_xxx, GCLP_xxx, and DWLP_xxx constants. For example, use SetWindowLong(hWnd, GWL_WNDPROC, (LONG)MyWndProc); in Win64 you will receive an error that GWL_WNDPROC is undefined. It should be changed to:SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)MyWndProc); To write code that is compatible with both 32-bit and 64-bit versions of Windows, use SetWindowLongPtr.

The following functions have been added to basetsd.h: PtrToLong() and PtrToUlong(), IntToPtr() and UIntToPtr(), HandleToLong() and LongToHandle(), etc. These can help convert values of one type to another. However, IntToPtr sign-extends the INT value, UIntToPtr zero-extends the unsigned int value, LongToPtr sign-extends the long value, and ULongToPtr zero-extends the unsigned long value. Also note that PtrToLong and HandleToLong will truncate the pointer to a 32bit value. These values should not be used as pointers again.

Compiling the code:

Set /W3 compiler option, and clean up all Win64 related compiler warnings, particularly the following codes:

  • C4305: Truncation warning. For example, "return": truncation from "unsigned int64" to "long."
  • C4311: Truncation warning. For example, "type cast": pointer truncation from "int*_ptr64" to "int."
  • C4312: Conversion to bigger-size warning. For example, "type cast": conversion from "int" to "int*_ptr64" of greater size.
  • C4318: Passing zero length. For example, passing constant zero as the length to memset.
  • C4319: Not operator. For example, "~": zero extending "unsigned long" to "unsigned _int64" of greater size.
  • C4313: Calling the printf() family of routines with conflicting conversion type specifiers and arguments. For example, "printf": "%p" in format string conflicts with argument 2 of type "_int64." Another example is calling printf("%x", pointer_value); This causes a truncation of the upper 32 bits. The correct method is to call printf("%p", pointer_value).
  • C4242 and C4244: return conversion. For example, "return": conversion from "_int64" to "unsigned int," possible loss of data.

Fix all Win64 related Compiler Errors, particularly --GWL_xxx and GCL_xxx not defined as discussed above.

SAPI issues

SAPI speech recognition (SR) interfaces are disabled in a 64-bit SAPI. SR-related objects such as Recognizer (both Inproc and Shared) cannot use CoCreateInstance on a 64-bit platform. Following is a list of the disabled interfaces: IspRecognizer, IspRecoContext, IspPhraseBuilder, ISpCFGEngine, IspGrammarCompiler, IspGramCompBackend, and ISpITNProcessor.

However, SAPI still supports TTS functionalities on a 64-bit platform. Because there is not a 64-bit version of sapi.lib, you cannot get the CLSIDs directly. But you can use CLSIDFromProgID() to get them. Here are the available SAPI ProgIDs on a 64-bit Windows:

CLSIDs | ProgIDs
CLSID_SpVoice | SAPI.SpVoice
CLSID_SpLexicon | SAPI.SpLexicon
CLSID_SpUnCompressedLexicon | SAPI.SpUnCompressedLexicon
CLSID_SpCompressedLexicon | SAPI.SpCompressedLexicon
CLSID_SpPhoneConverter | SAPI.SpPhoneConverter
CLSID_SpNullPhoneConverter | SAPI.SpNullPhoneConverter
CLSID_SpObjectTokenCategory | SAPI.SpObjectTokenCategory
CLSID_SpObjectTokenEnum | SAPI.SpObjectTokenEnum
CLSID_SpObjectToken | SAPI.SpObjectToken
CLSID_SpDataKey | SAPI.SpDataKey
CLSID_SpMMAudioEnum | SAPI.SpMMAudioEnum
CLSID_SpMMAudioIn | SAPI.SpMMAudioIn
CLSID_SpMMAudioOut | SAPI.SpMMAudioOut
CLSID_SpStreamFormatConverter | SAPI.SpStreamFormatConverter
CLSID_SpRecPlayAudio | SAPI.SpRecPlayAudio
CLSID_SpStream | SAPI.SpStream
CLSID_SpResourceManager | SAPI.SpResourceManager
CLSID_SpNotifyTranslator | SAPI.SpNotifyTranslator

The following are used in Automation:

CLSIDs | ProgIDs
CLSID_SpTextSelectionInformation | SAPI.SpTextSelectionInformation
CLSID_SpAudioFormat | SAPI.SpAudioFormat
CLSID_SpWaveFormatEx | SAPI.SpWaveFormatEx
CLSID_SpCustomStream | SAPI.SpCustomStream
CLSID_SpFileStream | SAPI.SpFileStream
CLSID_SpMemoryStream | SAPI.SpMemoryStream

Here is a simple example of how to use the ProgIDs on 64-bit applications:

LPCOLESTR pProgID;
CLSID clsid = GUID_NULL;
CComPtr<ISpVoice> cpVoice;
pProgID = L"SAPI.SpVoice";
hr = CLSIDFromProgID(pProgID, &clsid);
if(SUCCEEDED(hr))
{
    hr = cpVoice.CoCreateInstance(clsid);
    if(SUCCEEDED(hr))
        hr = cpVoice->Speak(L"This is a 64 bit test.", SPF_DEFAULT, 0);
    //do some more stuff here.
}


Using the SpAudioPlug Sample Audio Object SAPI 5.4

 Microsoft Speech Platform

Using the SpAudioPlug Sample Audio Object

Overview

This paper presents a overview to assist writing a custom audio object. It is intended to be used with the SAPI 5.1 SDK sample Visual Basic Audio Application. That application allows a user to enters the text in a edit box and perform speech recognition dictation on that text. A custom audio object is used to replace the traditional speaker. Rather than having the text talk over the speakers, the voice is redirected through the custom audio object to the speech recognition (SR) engine. At that point the voice is attempted to be recognized.

Implementation

The Visual Basic example VB Audio Application uses the automation interface provided by the sample audio object to do the audio data management. The application creates two instances of sample audio objects. One audio object is for text-to-speech (TTS) output, the other one is for SR input. The application would route the audio data from TTS output to SR input.

The white paper Speech Telephony Application Guide. VB SAPI with Internet provides implementation details.

Set up the TTS output

For TTS, we create an instance of the sample audio object and set to write mode.

Set AudioPlugOut = New SpAudioPlug
AudioPlugOut.Init True, AUDIOFORMAT

Then the Voice's output is set to point to this audio object.

Set Voice = New SpVoice
Set Voice.AudioOutputStream = AudioPlugOut

Set up the SR input

For SR, we create an instance of the sample audio object and set to read mode.

Set AudioPlugIn = New SpAudioPlug
AudioPlugIn.Init False, AUDIOFORMAT

Then the Recognizer's input is set to point to this audio object.

Set Recognizer.AudioInputStream = AudioPlugIn

Start processing

The following code starts the TTS and SR processes, and routes audio data from TTS output to SR input

output = AudioPlugOut.GetData
'Output the audio data to the input audio object
   If (Len(output) * 2 <> 0) Then
      AudioPlugIn.SetData (output)
   End If


Audio Object SAPI 5.4

 Microsoft Speech Platform

Audio Object

Overview

This document is intended to help developers write custom audio objects. Application developers can use this tool to direct speech data from memory into SAPI for speech recognition (SR) and for text-to-speech (TTS). The object does not generate or consume any audio data. Instead, it works as an audio buffer manager. For SR, audio data is passed to this object using a custom method ISpAudioPlug::SetData. SAPI retrieves the audio data from this object using IStream::Read. For TTS, audio data is passed from SAPI to this object using Istream::Write and the audio data can be retrieved calling a custom method ISpAudioPlug::GetData.

In order to use audio object for TTS output, the application uses asynchronous speak because the audio object does not consume the audio data. The application must consume the audio data by calling ISpAudioPlug.GetData. If the application uses synchronous speak, SAPI blocks the client thread. SAPI's write call on the audio object will block if the internal queue does not allocate more space. If the application retrieves the audio data on a different thread, the problem is averted.

Interface description

SAPI ISpAudio

The SAPI audio object needs to implement the ISpAudio interface.

Custom interface ISpAudioPlug

ISpAudioPlug inherits from ISpeechAudio. It provides methods to send and retrieve audio data. The interface is automation compliant and can be used easily in languages that support automation.

ISpAudioPlug::Init(VARIANT_BOOL fWrite, SpeechAudioFormatType FormatType)

This method is used to initialize the audio object's basic mode, including the read/write mode, as well as initialize the audio data format. If fWrite is TRUE, then the object is in write mode; if fWrite is FALSE the object is in read mode. FormatType specifies the audio format. By default, the object is in write mode and the format is set to SPSF_22kHz16BitMono. If the method is called while the object is processing audio data, SPERR_DEVICE_BUSY is returned.

ISpAudioPlug::SetData(VARIANT vData, long * pWritten)

SR uses this method when the object is set to read mode. The caller uses this method to send audio data so that SAPI can retrieve the audio data by Istream::Read.

ISpAudioPlug::GetData(VARIANT* vData)

TTS uses this method when the object is set to be write mode. The caller uses this method to retrieve audio data.

SAPI automation ISpeechAudio

The sample audio object provides an empty implementation of ISpeechAudio. In order to make the audio object usable in languages that support automation, SAPI requires that the object implement ISpeechAudio, which inherits from IDispatch. Internally, SAPI would not use ISpeechAudio directly. It uses QueryInterface on ISpAudio and calls the methods on ISpAudio. This way, the audio object only needs to provide an empty implementation of ISpeechAudio.

Buffer management

Internally, the audio object uses a queue object CBasicQueueByArray to manage the incoming and outgoing audio data. The queue internally uses an array to store data. When the data reaches the end of the array, it would move the head of the array to fill the data. The methods on the queue objects are thread safe.

State management

When SAPI starts an audio stream, the audio state changes to SPAS_RUN. When SAPI closes an audio stream, the audio state changes to SPAS_CLOSE. The audio object must perform the appropriate action according to the audio state. For example, when the audio state changes to SPAS_CLOSE, the audio object needs to free the audio buffer and signal other threads waiting for audio data.

Threading

Because the thread calling IStream::Read on the audio object is the same one that the SR engine uses to call SAPI, the client thread calling SetData/GetData is different from SAPI's IStream::Read thread. The audio object needs to be thread safe.

Event rerouting

The audio object implements ISpEventSink and ISpEventSource. SAPI forwards the SR/TTS events to the audio object. The audio object forwards SAPI the events with the audio position later than the current device position.


XML TTS Tutorial SAPI 5.4

 Microsoft Speech Platform

XML TTS Tutorial

SAPI XML TTS for Application Developers

SAPI text-to-speech (TTS) extensible markup language (XML) was developed before the W3C's Speech Synthesis Markup Language (SSML) specification was completed. Although SSML is now the preferred markup language for speech synthesis, SAPI TTS XML is still supported and is documented here for backward compatibility. For information about SSML, see the Speech Synthesis Markup Language Reference under Speech Users Guide in this help file, or the SSML specification.

SAPI text-to-speech (TTS) extensible markup language (XML) tags fall into several categories.

  • Voice state control
  • Direct item insertion
  • Voice context control
  • Voice selection

Voice state control tags

SAPI TTS XML supports five tags that control the state of the current voice: Volume, Rate, Pitch, Emph, and Spell.

Volume

The Volume tag controls the volume of a voice. The tag can be empty, in which case it applies to all subsequent text, or it can have content, in which case it only applies to that content.

The Volume tag has one required attribute: Level. The value of this attribute should be an integer between zero and one hundred. Values outside of this range will be truncated.

<volume level="50">
This text should be spoken at volume level fifty.

   <volume level="100">
      This text should be spoken at volume level one hundred.
   </volume>

</volume>

<volume level="80"/>
All text which follows should be spoken at volume level eighty.

One hundred represents the default volume of a voice. Lower values represent percentages of this default. That is, 50 corresponds to 50% of full volume.

Values specified using the Volume tag will be combined with values specified programmatically (using ISpVoice::SetVolume). For example, if you combine a SetVolume( 50 ) call with a <volume level="50"> tag, the volume of the voice should be 25% of its full volume.

Rate

The Rate tag controls the rate of a voice. The tag can be empty, in which case it applies to all subsequent text, or it can have content, in which case it only applies to that content.

The Rate tag has two attributes, Speed and AbsSpeed, one of which must be present. The value of both of these attributes should be an integer between negative ten and ten. Values outside of this range may be truncated by the engine (but are not truncated by SAPI). The AbsSpeed attribute controls the absolute rate of the voice, so a value of ten always corresponds to a value of ten, a value of five always corresponds to a value of five.

<rate absspeed="5">
   This text should be spoken at rate five.
   <rate absspeed="-5">
      This text should be spoken at rate negative five.
   </rate>
</rate>
<rate absspeed="10"/>

All text which follows should be spoken at rate ten.

Speed

The Speed attribute controls the relative rate of the voice. The absolute value is found by adding each Speed to the current absolute value.

<rate speed="5">
   This text should be spoken at rate five.
      <rate speed="-5">
         This text should be spoken at rate zero.
      </rate>
</rate>

Zero represents the default rate of a voice, with positive values being faster and negative values being slower. Values specified using the Rate tag will be combined with values specified programmatically (using ISpVoice::SetRate).

Pitch

The Pitch tag controls the pitch of a voice. The tag can be empty, in which case it applies to all subsequent text, or it can have content, in which case it only applies to that content.

The Pitch tag has two attributes, Middle and AbsMiddle, one of which must be present. The value of both of these attributes should be an integer between negative ten and ten. Values outside of this range may be truncated by the engine (but are not truncated by SAPI).

The AbsMiddle attribute controls the absolute pitch of the voice, so a value of ten always corresponds to a value of ten, a value of five always corresponds to a value of five.

<pitch absmiddle="5">
This text should be spoken at pitch five.
   <pitch absmiddle="-5">
      This text should be spoken at pitch negative five.
   </pitch>
</pitch>
<pitch absmiddle="10"/>

All text which follows should be spoken at pitch ten.

The Middle attribute controls the relative pitch of the voice. The absolute value is found by adding each Middle to the current absolute value.

<pitch middle="5">
This text should be spoken at pitch five.
   <pitch middle="-5">
      This text should be spoken at pitch zero.
   </pitch>
</pitch>

Zero represents the default middle pitch for a voice, with positive values being higher and negative values being lower.

Emph

The Emph tag instructs the voice to emphasize a word or section of text. The Emph tag cannot be empty. The following word should be emphasized.

<emph> boo </emph>!

The method of emphasis may vary from voice to voice.

Spell

The Spell tag forces the voice to spell out all text, rather than using its default word and sentence breaking rules, normalization rules, and so forth. All characters should be expanded to corresponding words (including punctuation, numbers, and so forth). The Spell tag cannot be empty.

<spell>
These words should be spelled out.
</spell>
These words should not be spelled out.

Direct item insertion tags

Three tags are supported that applications the ability to insert items directly at some level: Silence, Pron, and Bookmark.

Silence

The Silence tag inserts a specified number of milliseconds of silence into the output audio stream. This tag must be empty, and must have one attribute, Msec.

Five hundred milliseconds of silence <silence msec="500"/> just occurred.

Pron

The Pron tag inserts a specified pronunciation. The voice will process the sequence of phonemes exactly as they are specified. This tag can be empty, or it can have content. If it does have content, it will be interpreted as providing the pronunciation for the enclosed text. That is, the enclosed text will not be processed as it normally would be.

The Pron tag has one attribute, Sym, whose value is a string of white space separated phonemes.

<pron sym="h eh 1 l ow & w er 1 l d "/>
<pron sym="h eh 1 l ow & w er 1 l d"> hello world </pron>

Bookmark

The Bookmark tag inserts a bookmark event into the output audio stream. Use this event to signal the application when the audio corresponding to the text at the Bookmark tag has been reached. The Bookmark tag must be empty.

The Bookmark tag has one attribute, Mark, whose value is a string. This value can then be used to differentiate between bookmark events (each of which will contain the string value from their corresponding tag).

The application will receive an event here,

<bookmark mark="bookmark_one"/>

and another one here

<bookmark mark="bookmark_two"/>

Voice context control tags

Two tags provide context to the current voice: PartOfSp and Context. Those tags enable the voice to determine how to deal with the text it is processing. With both of these tags, the extent to which voices use the context may vary.

PartOfSp

The PartOfSp tag provides the voice with the part of speech of the enclosed word(s). Use this tag to enable the voice to pronounce a word with multiple pronunciations correctly depending on its part of speech. The PartOfSp tag cannot be empty.

The PartOfSp tag has one attribute, Part, which takes a string corresponding to a SAPI part of speech as its attribute. Only SAPI defined parts of speech are supported - "Unknown", "Noun", "Verb", "Modifier", "Function", "Interjection".

<partofsp part="noun"> A </partofsp> is the first letter of the alphabet.
Did you <partofsp part="verb"> record </partofsp> that <partofsp part="noun"> record </partofsp>?

Context

The Context tag provides the voice with information which the voice may then use to determine how to normalize special items, like dates, numbers, and currency. Use this tag to enable the voice to distinguish between confusable date formats (see the example, below). The Context tag cannot be empty.

The Context tag has one attribute, Id, which takes a string corresponding to the context of the enclosed text. Several contexts are defined by SAPI and are more likely to be recognized by SAPI compliant voices, but any string may be used. See documentation for a particular voice for more details.

<context id="date_mdy"> 03/04/01 </context> should be March fourth, two thousand one.
<context id="date_dmy"> 03/04/01 </context> should be April third, two thousand one.
<context id="date_ymd"> 03/04/01 </context> should be April first, two thousand four.

Voice Selection Tags

There are two tags which can be used (potentially) to change the current voice: Voice and Lang.

Voice

The Voice tag selects a voice based on its attributes, Age, Gender, Language, Name, Vendor, and VendorPreferred. The tag can be empty, in which case it changes the voice for all subsequent text, or it can have content, in which case it only changes the voice for that content.

The Voice tag has two attributes: Required and Optional. These correspond exactly to the required and optional attributes parameters to ISpObjectTokenCategory_EnumerateTokens and SpFindBestToken functions. The selected voice follows exactly the same rules as the latter of these two functions. That is, all the required attributes are present, and more optional attributes are present than with the other installed voices (if several voices have equal numbers of optional attributes one is selected at random). See Object Tokens and Registry Settings for more details.

In addition, the attributes of the current voice are always added as optional attributes when the Voice tag is used. This means that, a voice which is more similar to the current voice will be selected over one which is less similar.

If no voice is found that matches all of the required attributes, no voice change will occur.

The default voice should speak this sentence.

<voice required="Gender=Female;Age!=Child">

A female non-child should speak this sentence, if one exists.

<voice required="Age=Teen">
   A teen should speak this sentence - if a female, non-child teen is present, she will be selected over a male teen, for example.
   </voice>
</voice>

Lang

The Lang tag selects a voice based solely on its Language attribute. The tag can be empty, in which case it changes the voice for all subsequent text; or it can have content, in which case it only changes the voice for that content.

The Lang tag has one attribute, LangId. This attribute should be a LANGID, such as 409 (U.S. English) or 411 (Japanese). Note that these numbers are hexadecimal, but without the typical "0x".

The Lang tag is a shortened version of the Voice tag with the Required attribute containing "Language=xxx". So the following examples should produce exactly the same results:

<voice required="Language=409">
A U.S. English voice should speak this.
</voice>
<lang langid="409">
   A U.S. English voice should speak this.
</lang>


Using MFC to Automate SAPI SAPI 5.4

 Microsoft Speech Platform

Using MFC to Automate SAPI

Introduction

The Microsoft Foundation Classes (MFC) provides an easy and convenient way to automate calls to SAPI using its Class Wizard to generate wrappers for the SAPI layer from the SAPI Type Library.

In order to accomplish this, perform the following steps:

  1. Create a new MFCAppWizard(exe) project in Visual C++.
  2. Based on the type of application you are creating, follow the wizard prompts. In Step 3 of the wizard prompts, (or Step 2 if you are creating a Dialog Based application) make sure that the Automation check box is selected under the heading, What other support would you like to include?

Once the new project is ready, access Class Wizard.

  1. Click the Automation tab, and then click Add Class and select From a type library in the drop-down list.
  2. Browse for the sapi.dll file and open it.
  3. Select the classes you would like Class Wizard to generate a wrapper for. The resulting default header and implementation files are sapi.h and sapi.cpp respectively. The rest of this document assumes that you have chosen to use these default file names. Click OK.
  4. You should now be back in the Class Wizard window. Click OK.
After you are done with the above steps, Visual C++ will automatically add the Class Wizard generated files sapi.cpp and sapi.h to your project.

Upon viewing the sapi.h file, you should notice that it is nothing more than an automation wrapper that has been generated for all the classes you selected. Notice that all the classes inherit from COleDispatchDriver, hence the dispatch interface needs to be set up. This only requires a few lines of simple code, after which the wrapper class can be used just like any other C++ class.

Example

This example assumes that you chose to generate a wrapper for the ISpeechVoice class from among any other classes you may have selected. Using the project created above, include the sapi.h file within a source file in the project that will make automation calls to SAPI using the wrapper. In that source file, type the following code.

CLSID CLSID_SpVoice;    // class ID for the SAPI SpVoice object
LPDISPATCH pDisp;       // dispatch interface for the class
ISpeechVoice voice;     // use the MFC Class Wizard generated wrapper

CLSIDFromProgID(L"SAPI.SpVoice", &CLSID_SpVoice);
voice.CreateDispatch(CLSID_SpVoice);
pDisp = voice.m_lpDispatch;

HRESULT hr = pDisp->QueryInterface(CLSID_SpVoice, (void**)&voice.m_lpDispatch);

if (hr == S_OK) {
    pDisp->Release();
}
else {
    voice.AttachDispatch(pDisp, TRUE);
}

voice.Speak("hello world", 1);   // asynchronous call to Speak method of ISpeechVoice interface

If you have been following the steps outlined above properly, you should hear your computer say "hello world!" That's all there is to using MFC to make automation calls to SAPI. Currently however, not all the wrapper classes generated by MFC's Class Wizard work properly. For instance, the ISpeechLexicon interface does not work. The work around for this is to implement your own automation wrapper classes using C++. The steps to do that are beyond the scope of this document. Of course, you can always use the COM interfaces in C++ and Automation in Visual Basic to ensure that every interface in SAPI works easily and flawlessly.

Further Reading

The following links are recommended to learn more about the IDispatch interface and automation.

  • MSDN Automation: Overview. This is a starting point for those new to automation programming and will outline fundamental concepts and procedures.
  • MSDN's Automation: IDispatch Interface. This is the interface used to expose objects for automation.


Persisting Recognized WAV Audio from the SR Engine SAPI 5.4

 Microsoft Speech Platform

Persisting Recognized WAV Audio from the SR Engine

Overview

This document is intended to help developers of speech recognition (SR) applications use the Microsoft speech recognition and audio APIs to persist or store the wav audio recognized by a SR engine. The topics covered include:

  • Typical file input scenario
  • Typical audio storage scenario
  • Relevant APIs for C++ and Visual Basic/Scripting developers
  • Sample recognized audio storage source code for developers (written in both C++ and Visual Basic 6.0)

    • Typical file input scenario

    The following are typical scenarios that would need to store the wav audio recognized by the SR engine:

  • Transcription applications (e.g., convert voice mail to email)
  • Audio correction user interface (e.g., replay and/or re-recognize audio snippets)
  • SR engine testing (e.g., measure and improve engine accuracy with reproducible audio input data)

    • Typical audio storage scenario

    Follow these basic steps to retrieve and store recognized wav audio:

    1. Create an SR engine (InProc or shared).
    2. Enable retained audio on the relevant recognition context.
    3. Set the retained audio format (specify lower quality for smaller storage size, higher quality for clearer audio). Default is the SR engine's audio format.
    4. Set up and receive recognition events for relevant recognition context.
    5. Retrieve audio stream from recognition result.
    6. Copy result's audio stream to file-bound stream.

    Relevant wav audio file input APIs for COM/C/C++ Developers:

  • SpStream object, ISpStream interface: Basic SAPI audio stream
  • ISpStream::BindToFile: Setup audio stream for wav file input
  • SpBindToFile: Helper function to setup stream with a wav file
  • ISpRecoContext::SetAudioOptions: To enable/disable retained audio
  • ISpRecoResult::GetAudio: To retrieve recognized audio
  • ISpStreamFormat::GetFormat: To retrieve audio format
  • CSpStreamFormat helper object: Helper for handling audio formats
  • ISpStream::Read/Write: Methods for reading and writing stream data
  • SPEI_RECOGNITION/SPEI_FALSE_RECOGNITION: Events sent by SAPI when a recognition or false recognition has occurred

    • Relevant wav audio file input APIs for Automation/Visual Basic/Scripting Developers:

  • SpFileStream object: Basic file-based SAPI audio stream
  • SpMemoryStream object: Basic memory-based SAPI audio stream
  • ISpeechRecoContext::RetainedAudio property: To enable/disable retained audio
  • ISpeechBaseStream::Read/Write: Methods for reading and writing stream data
  • ISpeechBaseStream::Format property: To retrieve audio format
  • SpFileStream::Open/Close: Methods for opening and closing a file-based stream
  • ISpeechRecoContext::Recognition/FalseRecognition: Events sent by SAPI when a recognition or false recognition has occurred

    • Sample recognized audio storage source code

    Note: Error handling is omitted for brevity

    COM/C++ Developers (C-style is very similar)

    {
   HRESULT hr = S_OK;
   CComPtr<ISpRecoContext> cpRecoContext;
   CComPtr<ISpRecoGrammar> cpRecoGrammar;
   CComPtr<ISpRecoResult> cpRecoResult;
   CComPtr<ISpStreamFormat> cpStreamFormat;
   CSpEvent spEvent;
   WAVEFORMATEX* pexFormat = NULL;
   SPAUDIOOPTIONS eAudioOptions = SPAO_NONE;

   ' format for storing the audio
   const SPSTREAMFORMAT spFormat = SPSF_22kHz8BitMono;
   CSpStreamFormat Fmt( spFormat, &hr);
   // Check hr

   // Create shared recognition context for receiving events
   hr = cpRecoContext.CoCreateInstance(CLSID_SpSharedRecoContext);
   // Check hr

   // Create a grammar
   hr = cpRecoContext->CreateGrammar(NULL, &cpRecoGrammar);
   // Check hr

   // Load dictation
   hr = cpRecoGrammar->LoadDictation(NULL, SPLO_STATIC);
   // Check hr

   // Enabled audio retention in the SAPI runtime, and set the retained audio format
   hr = cpRecoContext->SetAudioOptions( SPAO_RETAIN_AUDIO, &Fmt.FormatId(), Fmt.WaveFormatExPtr());
   // Check hr

   // activate dictation
   hr = cpRecoGrammar->SetDictationState(SPRS_ACTIVE);
   // Check hr

   // wait 15 seconds for an event to occur (specifically, the default event, recognition)
   hr = cpRecoContext->WaitForNotifyEvent(15000);
   if (S_OK == hr)
   {
      // retrieve the event from the recognition context
      hr = spEvent.GetFrom(cpRecoContext);
      if (S_OK == hr)
      {
         // verify that the event is a recognition event
         if (SPEI_RECOGNITION == spEvent.eEventId)
         {
            // store the recognition result pointer
            cpRecoResult = spEvent.RecoResult();
            // release recognition result pointer in event object
            spEvent.Clear();
         }
      }
   }

   // deactivate dictation (only processing one recognition in sample code)
   hr = cpRecoGrammar->SetDictationState(SPRS_INACTIVE);
   // Check hr
   // unload dictation
   hr = cpRecoGrammar->UnloadDictation();
   // Check hr

   // if recognition received, and result stored then store the audio
   if (cpRecoResult)
   {
      // get stream pointer to recognized audio
      // Note: specifying NULL for the start element and element length defaults to the entire recognized audio stream. Correction UI may only need a subset of the audio for playback
      hr = cpRecoResult->GetAudio( 0, 0, &cpStreamFormat );
      // Check hr

      // basic SAPI-stream for file-based storage
      CComPtr<ISpStream> cpStream;
      ULONG cbWritten = 0;

      // create file on hard-disk for storing recognized audio, and specify audio format as the retained audio format
      hr = SPBindToFile(L"c:\\recognized_audio.wav", SPFM_CREATE_ALWAYS, &cpStream, &Fmt.FormatId(), Fmt.WaveFormatExPtr(), SPFEI_ALL_EVENTS);
      // Check hr

      ' Continuously transfer data between the two streams until no more data is found (i.e. end of stream)
      ' Note only transfer 1000 bytes at a time to creating large chunks of data at one time
      while (TRUE)
      {
         // for logging purposes, the app can retrieve the recognized audio stream length in bytes
         STATSTG stats;
         hr = cpStreamFormat->Stat(&stats, NULL);
         // Check hr

         // create a 1000-byte buffer for transferring
         BYTE bBuffer[1000];
         ULONG cbRead;

         // request 1000 bytes of data from the input stream
         hr = cpStreamFormat->Read(bBuffer, 1000, &cbRead);
         // if data was returned??
         if (SUCCEEDED(hr) && cbRead > 0)
         {
            ' then transfer/write the audio to the file-based stream
            hr = cpStream->Write(bBuffer, cbRead, &cbWritten);
            // Check hr
         }

         // since there is no more data being added to the input stream, if the read request returned less than expected, the end of stream was reached, so break data transfer loop
         if (cbRead < 1000)
         {
            break;
         }
      }
   }

   ' explicitly close the file-based stream to flush file data and allow app to immediately use the file
   hr = cpStream->Close();
   }
}

    Automation/Visual Basic 6.0 Developers

    Scripting code is similar to Visual Basic.

    Option Explicit

Dim WithEvents RecoContext As SpSharedRecoContext ' context for receiving SR events
Dim Grammar As ISpeechRecoGrammar ' grammar

' Setup/Initialization code for application startup
Private Sub Form_Load()
    ' Create new shared recognition context (inproc works similarly)
    Set RecoContext = New SpSharedRecoContext
    ' Create grammar
    Set Grammar = RecoContext.CreateGrammar
    ' Activate retained audio
    RecoContext.RetainedAudio = SRAORetainAudio
    ' Optionally, set the retained audio format to lower quality for smaller size
    ' RecoContext.RetainedAudioFormat = ???

    ' load and activate dictation
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive
End Sub

' Recognition event was received
Private Sub RecoContext_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    ' Create new file-based stream for audio storage
    Dim FileStream As New SpFileStream
    ' Variable for accessing the recognized audio stream
    Dim AudioStream As SpMemoryStream

    ' Retrieve recognized audio from result object
    ' Note: application can also retrieve smaller portions of the audio stream by specifying a starting phrase element and phrase element length
    Set AudioStream = Result.Audio

    ' Setup the file-based stream format with the same format as the audio stream format
    Set FileStream.Format = AudioStream.Format
    ' Create a file on the hard-disk for storing the recognized audio
    FileStream.Open "c:\recognized_audio.wav", SSFMCreateForWrite

    Dim Buffer As Variant ' Buffer for storing stream data
    Dim lRead As Long ' Amount of data read from the stream
    Dim lWritten As Long ' Amount of data written to the stream

    ' Continuously transfer data between the two streams until no more data is found (i.e. end of stream)
    ' Note only transfer 1000 bytes at a time to creating large chunks of data at one time
    Do While True
   ' read 1000 bytes of stream data
        lRead = AudioStream.Read(Buffer, 1000)
        ' if data was retrieved, then transfer/write it to the file-based stream
        If (lRead > 0) Then
            lWritten = FileStream.Write(Buffer)
        End If

        ' Since the input stream will not increase in size, the number of bytes read will only be less than requested if there is no more data to be transferred
        If lRead < 1000
            Exit Do ' exit if no more data
        End If
    Loop
    ' close the file-based stream
    ' Note: The stream will be closed automatically when the object is released, but explicit closing enables app to immediately use the file stream's data
    FileStream.Close

    ' Sample code will deactivate and unload dictation, then shutdown after one recognition
    Grammar.DictationSetState SGDSInactive
    Grammar.DictationUnload
    Unload Me ' shutdown app
End Sub


Using WAV File Input with SR Engines SAPI 5.4

 Microsoft Speech Platform

Using WAV File Input with SR Engines

Overview

This document is intended to help developers of speech recognition (SR) applications use the Microsoft Speech API's speech recognition and audio APIs to connect a wav file with an SR engine. The topics covered include:

  • Typical file input scenario
  • In-process (InProc) versus shared engines
  • Relevant to setting up and using wav files as input to the speech recognizer
  • Sample source code (written in both C++ and Visual Basic 6.0) to help guide developers.

    • Typical file input scenario

    There are many different types of audio input configurations used by SR applications, which include:

  • A microphone shared by all desktop applications
  • A telephony card communicating with one or more SR engines
  • Sending audio from a persisted wav file to an SR engine

    • The shared desktop microphone scenario uses the default SR engine and the default audio input. The user selects each in Speech properties in Control Panel, and each is hosted in the shared speech server.

    The telephony scenario can use either the SAPI 5 standard multimedia audio input object or a custom audio object combined with an InProc SR engine.

    The wav file input scenario is special because it uses controlled, reproducible audio input and requires a dedicated SR engine, without interference from other applications (e.g., a shared desktop microphone). The file input scenario should use a generic SAPI audio stream connected to the input wav file and an InProc SR engine.

    Typical scenarios that would use the wav file audio input configuration include:

  • Offline transcription applications (e.g., convert voice mail to email)
  • SR engine testing (e.g., measure and improve engine accuracy with reproducible audio input data)
  • SR application testing (e.g., verify and improve application behavior when responding to reproducible voice commands)

    • Follow these basic steps to perform SR on a wav file:

    1. Create and configure basic SAPI audio stream object for wav file input
    2. Create an InProc SR engine using the code samples in this document
    3. Set the audio stream object from step 1 as the SR engine's input
    4. Activate grammars and begin SR
    5. Respond to recognition events until end of audio stream is reached

    Relevant wav audio file input APIs for COM/C/C++ Developers:

  • SpStream object, ISpStream interface: Basic SAPI audio stream
  • ISpStream::BindToFile: Set up audio stream for wav file input
  • SpBindToFile: Helper function to setup stream with a wav file
  • SpInprocRecognizer, ISpRecognizer: InProc SR engine
  • ISpRecognizer::SetInput: Set stream object as engine's input
  • SPEI_START_SR_STREAM, SPEI_END_SR_STREAM: Event signaling engine has reached the beginning or the end of the wav file, respectively

    • Relevant wav audio file input APIs for Automation/Visual Basic/Scripting Developers:

  • SpFileStream object: Basic file-based SAPI audio stream
  • SpInprocRecognizer, ISpeechRecognizer: InProc SR engine
  • SpInprocRecoContext, ISpeechRecoContext: InProc SR context
  • ISpeechRecognizer::AudioInputStream property: Set file stream object as engine's input
  • ISpeechRecoContext::EndStream/StartStream events

    • Wav audio file input outcome specific to SAPI

    Finite-length audio input stream

    Unlike microphone input which has no predetermined stream length, a finite-length audio input stream is a file which has a specific length that is known before recognition begins. Similarly, applications that use microphone input will toggle between actively listening and not listening states until the speech application is closed. However, transcription applications are typically designed to listen to one continuous audio stream, and then close when the stream ends. Consequently, the application must specifically acknowledge the end audio stream event (SPEI_SR_END_STREAM for C/C++, ISpeechRecoContext::EndStream event for Automation). Transcription applications can potentially record multiple recognitions on a single audio stream, if the speaker pauses or breaks between sections of audio. If the transcription application exits after the first recognition event is received, it will miss any further recognizable audio that remains.

    Non-real-time audio input

    Microphone input and networked audio streams are typically real-time audio objects. This means that the audio object is designed to support audio buffering and dynamic state manipulation (e.g. stop->play->pause->play->stop) to handle delays and latency in the audio source and/or the SR engine's processing.

    Sample wav audio file input source code

    COM/C++ Developers

    C-style is very similar to C++ and COM

    {
   CComPtr<ISpStream> cpInputStream;
   CComPtr<ISpRecognizer> cpRecognizer;
   CComPtr<ISpRecoContext> cpRecoContext;
   CComPtr<ISpRecoGrammar> cpRecoGrammar;

   // Create basic SAPI stream object
   // NOTE: The helper SpBindToFile can be used to perform the following operations
   hr = cpInputStream.CoCreateInstance(CLSID_SpStream);
   // Check hr
   CSpStreamFormat sInputFormat;
   // generate WaveFormatEx structure, assuming the wav format is 22kHz, 16-bit, Stereo
   hr = sInputFormat.AssignFormat(SPSF_22kHz16BitStereo);
   // Check hr

   // setup stream object with wav file MY_WAVE_AUDIO_FILENAME
   //   for read-only access, since it will only be access by the SR engine
   hr = cpInputStream->BindToFile(MY_WAVE_AUDIO_FILENAME,
      SPFM_OPEN_READONLY,
      sInputFormat.FormatId(),
      sInputFormat.WaveFormatExPtr(),
      SPFEI_ALL_EVENTS);

   // Check hr

   // Create in-process speech recognition engine
   hr = cpRecognizer.CoCreateInstance(CLSID_SpInprocRecognizer);
   // Check hr

   // connect wav input to recognizer
   // SAPI will negotiate mismatched engine/input audio formats using system audio codecs, so second parameter is not important - use default of TRUE
   hr = cpRecognizer->SetInput(cpInputStream, TRUE);
   // Check hr

   // Create recognition context to receive events
   hr = cpRecognizer->CreateRecoContext(&cpRecoContext);
   // Check hr

   // Create grammar, and load dictation
   // ignore grammar ID for simplicity's sake
   // NOTE: Voice command apps would load CFG here
   hr = cpRecognizer->CreateGrammar(NULL, &cpRecoGrammar);
   // Check hr
   hr = cpRecoGrammar->LoadDictation(NULL,SPLO_STATIC);
   // Check hr

   // check for recognitions and end of stream event
   hr = cpRecoContext->SetInterest(SPFEI(SPEI_RECOGNITION) | SPFEI(SPEI_SR_END_STREAM), SPFEI(SPEI_RECOGNITION) | SPFEI(SPEI_SR_END_STREAM));

   // use Win32 events for command-line style application
   hr = cpRecoContext->SetNotifyWin32Event();
   // Check hr

   // activate dictation, and begin recognition
   hr = cpRecoGrammar->SetDictationState(SPRS_ACTIVE);
   // Check hr

   // while events occur, continue processing
   // timeout should be greater than the audio stream length, or a reasonable amount of time expected to pass before no more recognitions are expected in an audio stream
   BOOL fEndStreamReached = FALSE;
   while (!fEndStreamReached && S_OK == cpRecoContext->WaitForNotifyEvent(MY_REASONABLE_TIMEOUT))
   {
      CSpEvent spEvent;
      // pull all queued events from the reco context's event queue

      while (!fEndStreamReached && S_OK == spEvent.GetFrom(cpRecoContext))
      {
         // Check event type
         switch (spEvent.eEventId)
         {
            // speech recognition engine recognized some audio
            case SPEI_RECOGNITION:
            // TODO: log/report recognized text
            break;

            // end of the wav file was reached by the speech recognition engine
            case SPEI_SR_END_STREAM:
               fEndStreamReached = TRUE;
               break;
         }

         // clear any event data/object references
         spEvent.Clear();
         }// END event pulling loop - break on empty event queue OR end stream
      }// END event polling loop - break on event timeout OR end stream

   // deactivate dictation
   hr = cpRecoGrammar->SetDictationState(SPRS_INACTIVE);
   // Check hr

   // unload dictation topic
   hr = cpRecoGrammar->UnloadDictation();
   // Check hr

   // close the input stream, since we're done with it
   // NOTE: smart pointer will call SpStream's destructor, and consequently ::Close, but code may want to check for errors on ::Close operation
   hr = cpInputStream->Close();
   // Check hr
}

    Automation/Visual Basic 6.0 Developers

    Scripting code is similar to Visual Basic.

    Option Explicit
Dim WithEvents RecoContext as ISpeechRecoContext ' context for receiving SR events
Dim Grammar as ISpeechRecoGrammar	' grammar
Dim InputFile as SpeechLib.SpFileStream	' wav audio input file stream

' Setup InProc reco context and wav audio input file
Private Sub MyForm_Load()
   ' Create new recognizer
   Dim Recognizer as New SpInprocRecognizer

   ' create input file stream
   Set InputFile as New SpFileStream
   ' Defaults to open for read-only, and DoEvents false
   InputFile.Open MY_WAVE_AUDIO_FILENAME

   ' connect wav audio input to speech recognition engine
   Set Recognizer.AudioInputStream = InputFile

   ' create recognition context
   Set RecoContext = Recognizer.CreateRecoContext

   ' create grammar
   Set Grammar = RecoContext.CreateGrammar
   ' ... and load dictation
   Grammar.DictationLoad

   ' start dictating
   Grammar.DictationSetState SGDSActive
End Sub

' Event fired on app shutdown
Private Sub MyForm_Unload(Cancel as Boolean)
   InputFile.Close ' close audio input file
End Sub

' Event fired when speech recognition engine recognizes audio
Private Sub RecoContext_Recognition(StreamNumber as Long, StreamPosition as Variant, RecognitionType As SpeechRecognitionType, Result As ISpeechRecoResult)
   ' Log/Report recognized phrase/information
End Sub

' End of wav Input Stream reached by speech recognition engine
Private Sub RecoContext_EndStream(StreamNumber as Long, StreamPosition as Variant)
   ' Disable dictation and unload grammars on app close
   Grammar.DictationSetState SGDSInactive
   Grammar.DictationUnload

   Unload Me ' shutdown app on end of stream
End Sub


Automation Interfaces and Objects (Microsoft Speech Platform)

 Microsoft Speech Platform

Automation Interfaces and Objects

The Automation Interfaces provide object-oriented access to the speech recognition and text-to-speech capabilities of SAPI.

Please note that all automation interface names begin with "ISpeech" and that all automation object names begin with "Sp." Applications can explicitly create object variables which instantiate automation objects, using the "CreateObject" statement or the "New" keyword in a "Dim" or "Set" statement. Object variables which instantiate automation interfaces, on the other hand, are only created by the methods, properties and events of automation objects.

Additionally, some automation interfaces are implemented by automation objects, and the properties and methods of those interfaces are inherited by the objects. For example, the ISpeechBaseStream interface defines a set of properties and methods for storing and manipulating audio data in memory. The SpFileStream, SpMemoryStream and SpCustomStream objects implement the ISpeechBaseStream interface; as a result, the methods and properties of the ISpeechBaseStream interface are available in all three objects.

Automation Interfaces and Objects

SAPI 5.1 Automation consists of the following interfaces and objects:

Interfaces | Description
ISpeechAudio | Supports the control of real-time audio streams, such as those connected to a live microphone or telephone line.
ISpeechAudioBufferInfo | Defines the audio stream buffer information.
ISpeechAudioStatus | Provides control over the operation of real-time audio streams.
ISpeechBaseStream | Defines properties and methods common to all audio stream objects.
ISpeechDataKey | Provides access to the speech configuration database.
ISpeechGrammarRule | Defines the properties and methods of a speech grammar rule.
ISpeechGrammarRules | Represents a collection of ISpeechGrammarRule objects.
ISpeechGrammarRuleState | Presents the properties and methods of a speech grammar rule state.
ISpeechGrammarRuleStateTransition | Returns data about a transition from one rule state to another, or from a rule state to the end of a rule.
ISpeechGrammarRuleStateTransitions | Represents a collection of ISpeechGrammarRuleStateTransition objects.
ISpeechLexiconPronunciation | Provides access to the pronunciations of a speech lexicon word.
ISpeechLexiconPronunciations | Represents a collection of ISpeechLexiconPronunciation objects.
ISpeechLexiconWord | Provides access to a speech lexicon word.
ISpeechLexiconWords | Represents a collection of ISpeechLexiconWord objects.
ISpeechObjectTokens | Represents a collection of SpObjectToken objects.
ISpeechPhraseAlternate | Enables applications to retrieve alternate phrase information from an SR engine, and to update the SR engine's language model to reflect committed alternate changes.
ISpeechPhraseAlternates | Represents a collection of ISpeechPhraseAlternate objects.
ISpeechPhraseElement | Provides access to information about a word or phrase.
ISpeechPhraseElements | Represents a collection of ISpeechPhraseElement objects.
ISpeechPhraseInfo | Contains properties detailing phrase elements.
ISpeechPhraseProperties | Represents a collection of ISpeechPhraseProperty objects.
ISpeechPhraseProperty | Stores the information for a semantic property.
ISpeechPhraseReplacement | Specifies a replacement, or text normalization, of one or more spoken words.
ISpeechPhraseReplacements | Represents a collection of ISpeechPhraseElement objects.
ISpeechPhraseRule | Contains information about a speech phrase rule.
ISpeechPhraseRules | Represents a collection of ISpeechPhraseRule objects.
ISpeechRecognizerStatus | Returns the status of the speech recognition engine represented by the recognizer object.
ISpeechRecoGrammar | Enables applications to manage the words and phrases for the SR engine.
ISpeechRecoResult | Returns information about the recognition engine's hypotheses, recognitions, and false recognitions.
ISpeechRecoResultDispatch | Cannot be QI'd for but allows IDispatch access to both ISpeechRecoResult and ISpeechXMLRecoResult.
ISpeechRecoResultTimes | Contains the time information for speech recognition results.
ISpeechVoiceStatus | Contains status information about an SpVoice object.
ISpeechXMLRecoResult | Is used to acquire the semantic results of speech recognition and return them as an SML document.
Objects | Description
SpAudioFormat | Defines an audio format.
SpCustomStream | Supports supports the use of existing IStream objects in SAPI.
SpFileStream | Provides the ability to open files as audio streams and save audio streams as files.
SpInProcRecoContext | Defines a recognition context, or a collection of settings, that requests a specific type of recognition as determined by the needs of an application.
SpInProcRecoContext (Events) | Defines the types of events that a recognition context can receive.
SpInProcRecognizer | Represents a speech recognition engine.
SpLexicon | Provides access to lexicons, which contain information about words that can be recognized or spoken.
SpMemoryStream | Supports audio stream operations in memory.
SpMMAudioIn | Represents the audio implementation for the standard Windows wave-in multimedia layer.
SpMMAudioOut | Represents the audio implementation for the standard Windows wave-out multimedia layer.
SpObjectToken | Supports object token entries.
SpObjectTokenCategory | Represents a class of object tokens.
SpPhoneConverter | Supports conversion from the SAPI character phoneset to the Id phoneset.
SpPhraseInfoBuilder | Provides the ability to rebuild phrase information from audio data saved to memory.
SpSharedRecoContext | Defines a recognition context, or a collection of settings, that requests a specific type of recognition as determined by the needs of an application.
SpSharedRecoContext (Events) | Defines the types of events that a recognition context can receive.
SpSharedRecognizer | Represents a speech recognition engine.
SpTextSelectionInformation | Provides access to the text selection information pertaining to a word sequence buffer.
SpUnCompressedLexicon | Provides access to lexicons, which contain information about words that can be recognized or spoken.
SpVoice | Enables an application to perform text synthesis operations.
SpVoice (Events) | defines the types of events that can be received by an SpVoice object.
SpWaveFormatEx | Defines the format of waveform-audio data.


Automation Overview (Microsoft Speech Platform)

 Microsoft Speech Platform

Automation Overview

Automation is the ability of one entity (or object) to communicate with another object. These entities may be applications or ActiveX® controls, although ultimately they all use COM (component object model) as the common denominator. The underling complexity is removed for the Visual Basic programmer. The result is that your application can access features and information from other sources. This interaction can be as involved as sharing information between the two applications, such as between your Visual Basic application exporting or importing data form a database or spreadsheet. Automation also allows you to issue basic commands such as Open and Print. This way, developers can integrate their favorite spreadsheet or word processor capabilities with methods unique to a particular corporate environment. For example, while you could write your own spell checker for your Visual Basic application, your application could access the Microsoft Word spell checker, thus saving time and effort. In Visual Basic, this scenario using standard applications is commonly referred to as Visual Basic for Applications (VBA). VBA is a specialized subset of Visual Basic and is designed to manage applications for custom solutions.

A second use of automation includes components. A component can be considered an additional functionality provided outside of the capabilities of any programming language itself. For example, Visual Basic provides a basic text box for displaying text and although that text may be italic or bold, all the text must share the same characteristics. For example, it must all be bold, or all the same font size. On the other hand, a rich text edit box may be added to the Visual Basic Toolbox. Using this rich text edit box, you can change the font, size and appearance of the text. However, this capability must be explicitly added using the appropriate component on the Components menu. In reality, that rich text edit box is a COM object. Because COM is intended to offer programmers flexibility, there is a robust set of components available. Many come with the Visual Basic package, others are available through third party sources, and some are designed for specific purposes such as in-house corporate environments. This ability to compartmentalize features and functionality gives components their popularity.

A third use of automation is its ability to access dynamic link libraries (or DLLs). This aspect of automation involves applications without a user interface. SAPI, for instance, has no interface per se. While users can incorporate SAPI functions into their own applications, they cannot run SAPI in a conventional sense and have a user interface, as well as menus and documents. Developers however, have access to all of SAPI's functions in a programmatic way using dynamic link libraries (DLLs). If DLLs exist on the computer, a developer can access them by linking their development environment to them. In the case of Visual Basic, SAPI may be added using the Microsoft Speech Object Library on the References menu. If a particular DLL is not present, it can be installed using the manufacturer's installer. For example, sapi.dll is loaded when developers install SAPI.

DLLs are used frequently. A search for *.dll reveals the true extent of their use. Using them, developers can introduce new components or capabilities to an operating system without compiling them into the system. DLLs may be, and usually are, loaded after the operating system. However, their mere presence does not affect any application. As mentioned, developers need to make calls to DLLs before a DLL can have an effect on an operating system. Since SAPI has no interface, this document is the only guide to accessing its features. The application programming interface (API) acts as a guide and provides a list of all the possible calls, explanations of them, and guidelines for successfully using them. Certain calls must be made in a specific order to keep SAPI automation simple. This API explains these issues and eases development concerns. Also available with this documentation is the software development kit (SDK), which provides supplementary information such as code examples and additional tools. Developers are encouraged to review the sample code and possibly base their applications on it.

Even though three different uses of automation are described above, ultimately all automation uses an identical foundation. Automation itself is a complex technology. It has evolved over the years and, no doubt, will continue to evolve to accommodate changing technologies and the increasing sophistication demanded by the marketplace. Older programmers will remember OLE (object linking and embedding), which evolved into ActiveX, COM, and COM+. All of these programs are progressions of what is commonly called automation. Fortunately automation's complexity is hidden. Support is usually built into the operating system now and accessing these technologies, or individual aspects of them, is nothing more than making a selection from a list within the development environment.

The concept of automation using COM is that of programming language independence. As long as the object complies with COM standards, any programming language may be used. This documentation suite addresses the SAPI automation programming using Visual Basic; however, Visual Basic is not actually required. In fact, many of the same calls and calling syntax may be used in other computer languages, provided they support automation. This includes the ability to use JScript®, Visual C#®, or possibly other solutions that support automation. Visual Basic is used here because of its popular and widespread support in marketplace. Also, it has supported automation virtually since its inception and the Visual Basic tool suite offers a variety of options.


ObjectsAndClasses Overview (Microsoft Speech Platform)

 Microsoft Speech Platform

Objects and Classes Overview

Classes

For automation to work, there must be technology common to all applications. Though still evolving, the current incarnation of that technology is the component object model (COM). Many applications are COM-compliant and the usage is widespread. Using this technology, COM-compliant applications can issue and receive commands from other applications. The details of COM and automation are complex, but almost all of the issues are hidden from the user or application developers.

The functionality of these components is encapsulated in distinct files called type libraries. Type libraries contain all the methods, properties, and supporting data for the applications to use; the application just needs to load the appropriate type library to gain access to the functionality. In Visual Basic, type libraries are also called references. Some type libraries are loaded automatically and others must be loaded explicitly. This will be covered later and in more detail. Once loaded, Visual Basic has complete access to the contents of the type library.

Libraries themselves contain many separate items. For example, The Microsoft Speech Object Library (once loaded, it is called SpeechLib in the references) contains over 400 individual methods and properties, not including supporting data. Therefore, to better organize functionality, related calls and data are grouped together in classes. For example, SAPI has an ISpeechRecoResult class. This class contains functionality needed to assess the results of successful speech recognition. To retrieve the text of the spoken recognition, use the GetText method from ISpeechRecoResult.

However, classes themselves are just a blueprint for the functionality. That is, classes describe the functions, but they cannot execute the function. To execute the function, an object must be created (also called instantiated). In this way, one class may be instantiated any number of times.

Once an object is created, Visual Basic uses a standard notation for making these calls. This is an object.method notation (pronounced "object dot method"). A typical call will look like this: ISpeechRecoResult.PhraseInfo.GetText(). Complete ownership could also be used by including the library name: SpeechLib.ISpeechRecoResult.PhraseInfo.GetText().

To determine what is available from a particular type library after loading it, Visual Basic offers an object browser. The browser is available by either pressing F2 or selecting View->Object Browser from the menu. The object browser displays the information in a graphical format. Clicking or double-clicking an item reveals additional information about it including properties, methods, events, or classes that it contains. The bottom pane displays a quick reference guide for the selection and includes the owning object memberships up through the library. This method of browsing available objects can be useful when learning a new library. In addition, two additional modules SpeechConstants and SpeechStringConstants, are available for viewing. These two modules contain names for numeric and string constants used by SAPI.

Objects

As mentioned, classes are just blueprints for a certain functionality. To use the calls of a class, an object must be created. An object can allocate memory and assign values to various elements contained by the object. Making an instance of the object is similar to declaring variables. For example, the variable type String is a common occurrence in Visual Basic programs. The type allows a character string to be used, saving information in it, and later retrieving information from it. However, before using the variable an instance must be created. In the following example, one String instance is created:

Dim myString As String

After this appears in the code, the variable myString is valid and may be referenced and changed as needed. In this sense, String can be considered the class and myString is an instance of the class. Likewise, it is possible to declare several instances of String.

Dim myString, userName, fileName As String

Now three strings are available for use, presumably to record information for vastly different purposes. Perhaps userName may be used to track the user's identity, and fileName for recording the location and name of a file. This is an example of one data type having several instances. The same will hold true for classes and interfaces.

Instantiating an object is similar, but requires slight modifications. The additional modifications are in the second line:

   Dim myVoice As SpVoice
   Set myVoice = New SpVoice

The additional keywords are Set and New. Classes require these two keywords since classes are more complex than variables. Once declared and allocated, the object may be used and referenced. However, simply creating an object may not be enough and additional initialization may be required. Just as creating myString allocates the variable for use, the programmer must assign a value to it. In fact, it is possible for an object to have no valid reference. In this case, the value will be Nothing. The following code tests for an object which is Nothing.

If myVoice Is Nothing Then
   'Handle the situation here. You might want to allocate it or
   'warn the user an error could have occurred.
End If


VB Events Overview (Microsoft Speech Platform)

 Microsoft Speech Platform

Events Overview

Taken in the most general sense, the concept of automation is that of two objects communicating with each other. These objects may be two applications, or an application and a COM component. Ultimately, however, it comes down to two COM components, although that is not really the point. The point is two items are exchanging information between them.

In the case of SAPI, it is easy to get the impression that the Visual Basic application makes all the calls to SAPI and receives nothing in return. You can get that impression because most of the emphasis of this documentation suite features the several hundred available calls to SAPI. But in fact, there is a two-way communication going on. The feedback from SAPI and the speech engines plays a critical role in a speech application.

SAPI interacts with the host application using events. An event is a signal sent to the application by an outside source. The event indicates that some condition exists outside of the application that may be of interest to the user. The outside source in this case is SAPI and examples of events may indicate that a recognition is available or that the SAPI engine is ready to accept input.

Events are not limited or unique to SAPI. They are the standard method to get information back to the host application. It is common for other applications to send events. An example of an event sent back to an application is that of an e-mail application running in the background notifying users whenever a new e-mail arrives. Unlike a conventional method or property, which must be explicitly coded by the programmer and called at a specific time, events may be sent or received at any time. It is even possible for events to be sent faster than the host application can process. Yet this rarely is disruptive to the user or the current application.

Far from interfering with the application, events intend to enhance the user experience. For example, moving the pointer over menu items alters the appearance of individual buttons and indicates that the menu item is available. This type of event is handled transparently to users, and they do not need to respond in any way. It is even transparent to programmers because the change in appearance is automatic and requires no code implementation. Nevertheless, the application is responding to an event.

Events can be considered to be of one of two types: user-initiated or background generated. As the name implies, a user-initiated event is one initiated by the user. A common instance is that of the user clicking a command button. This actually generates several events including a MouseDown event and Click event. A graphical user interface (GUI, pronounced gooey) is an example of many user-initiated events; that is, the user starts various activities such as clicking a menu, opening an application, or entering text. Conventional GUI programming relies extensively on an event loop. This endless loop waits for events. After receiving one, the event is dispatched and whatever action it is intended to do begins. Visual Basic applications have an event loop, although it is hidden from the programmer.

Background generated events, on the other hand, are events initiated not by the user but by some other source such as another application (such as SAPI) or the operating system. This is how applications inform one another about something of interest. For instance, if an application were using automation with Microsoft Word, it is possible for Word to send an event whenever a file is deleted, printed, or opened. The application could respond or even ignore the event if it were unimportant. SAPI sends back events in the same way. For example, when SAPI finishes processing a phrase and has a recognition ready, it sends a recognition event to the host application. Handling an event is similar to a function or subroutine except an event is invoked automatically.


Types of Automation Events (Microsoft Speech Platform)

 Microsoft Speech Platform

Types of Automation Events

Introduction

Chances are you have already have used events and may not have known it. If your application has a command button, (a common interface tool) events generate the action for it. For example, clicking the command button when the application is running usually initiates a certain action. Clicking the button sends out a button Click event. However the programmer had to write the code for the action and chances are that code is contained in a procedure perhaps called Command1_click. The word click indicates that it is an action. This is an example of a user-initiated event; that is, the user must click the button to perform its action.

There are other examples of user initiated events. For example, the first time a form is displayed, a Form_Load event is generated. Perhaps not as common as a Command_Click event, the Form_Load event initializes information on a particular form. Though still considered to be a user-initiated event, the Form_Load event may or may not be a direct result of user interaction. You could have chosen a menu item that displays a new dialog box (and hence a form). Or perhaps the form could also be the result of an error handling routine initiated by an activity you caused indirectly. Regardless of what caused the event, the application can have code to handle the situation. The particular event could be ignored completely, in which case you do not need code for the event.

Background-generated events work in a similar fashion as user-initiated events. The difference is the background-generated event may be fired at anytime and is not the direct result of user interaction, at least not in the same way as clicking a button. SAPI events fall into this category. For either speech recognition or text-to-speech, SAPI returns events to the application. The application then addresses or ignores the event. Furthermore, the application can selectively reject certain types of events if there is no need to work with them. Speech recognition returns a spectrum of events from noise interference prohibiting recognition to notifications (successful or otherwise). SAPI returns additional events for activities such as the start and end of media streams, or the start or end of sound input, which are required for potential recognition attempts. Text-to-speech has events related to it as well.

Speech Recognition Events

The enumeration SpeechRecoEvents contains the speech recognition events. Upon review of these events, many appear logical and obvious. The speech recognition event SRERecognition is returned upon a successful recognition; SREPhraseStart handles the start of a new phrase. Other events are less obvious and have specialized functions. For example, SRERecoOtherContext indicates that a successful recognition occurred but cannot be associated with the current recognizer context. For a detailed explanation of events and some situations where they might be used, please see the appropriate SAPI documentation.

For a complete list of speech recognition events see ISpeechRecoContext (Events)

Text-To-Speech Events

The enumeration SpeechVoiceEvents contains all the text-to-speech events. Similar to recognition events, some voice events may seem obvious, and others less so. See the appropriate SAPI documentation.

For a complete list of text-to-speech events see SpVoice (Events)

Exploring Types of Events

In general, there are two ways to discover what events are available. First, the application programming interface (API) reference lists them and describes their use in detail. In order to gain a better understanding of any event or method, it is important to review those event topics first.

A second method is to view the Object browser from within Visual Basic. Click F2 to display the browser or select View->Object Browser from the menu. Events, like other items, have an associated icon, in this case a lightning bolt.

In any case, SAPI has only two interfaces with events associated with them:

  • SpVoice
  • ISpeechRecoContext


Automation Event Handling (Microsoft Speech Platform)

 Microsoft Speech Platform

Automation Event Handling

Event Handlers

In order to respond to an event, the application needs a corresponding event procedure (also called an event handler). If an event does not have an associated procedure, then that event is not considered handled and the application does not act upon it. By default, no event procedures are included in any Visual Basic applications. For example, a programmer may include a command button on a form. But the mere presence of the button does not mean that there is an associated activity if the user clicks the button. Instead, the programmer must explicitly define the activity. In the same way SAPI returns several types of events by default. However, unless the host application has the code to process the event, it will appear that the event is not handled.

In Visual Basic, defining the procedure is simple and can be done in one of three ways.

1. Double-click the control while in design mode. Visual Basic programmer are probably most familiar with this method. For example, double-click the command button while in design mode. Visual Basic automatically includes the code necessary to support the function. This code includes the event type (again, for this example, the event type is button Click) and nay necessary parameters. In fact, programmers do not need to know the number or kinds of parameters. Visual Basic includes them automatically.

2. Use the Object or Procedures drop-down list boxes in the Visual Basic editor. The Object list presents all the available objects on the form. From this list, the programmers can directly choose the procedure they want rather than scrolling through the code or searching for the item name.

The Object Menu in Visual Basic. This lists all the objects on the form. In this example, the form only contains a single item: a button named Command1. However, the form itself is an object and can have events associated with it. By default, there is also a General item. This includes functions not associated with directly with any control.

The Procedures list presents all the events available for the selected object. Keep in mind that clicking a specific control in the forms window only brings up one kind of event, usually the click event. Objects often have many other events associated with it. New events may be added for the item selected in the Object menu. Select the intended event from the Procedures menu. Visual Basic automatically opens the code window, and includes the supporting code necessary to the event. Again, programmers do not need to know parameter information.

The Procedures menu in Visual Basic. With an object selected from the Object menu, the available events are listed. Using the previous example, the events listed are for the Command1 button. Choosing an event (the click event is highlighted) will automatically insert the subroutine or function along with the required parameters.

3. Consult the API documentation for the event. This presents the information and parameter requirements for the event. The function can then be written or pasted in manually as code. This is the least automated method of the three. However, not all development environments support automatic generation of code and this may be the only option in some cases.

In the simple case of a command button Click, any of the three methods above results in the following code:

Private Sub Command1_Click()

End Sub

Whenever Command1 is clicked, it uses the code in this routine. Naturally, it is up to programmers to write the procedure to handle the event as they see fit.

SAPI Event Handlers

Adding SAPI event handlers is similar to other controls. First, the object associated with the events must be declared. For example, declare a new recognizer object in the project

Public WithEvents RC As SpSharedRecoContext

Notice also the declaration has an additional keyword in it: WithEvents. This keyword is required to identify the object as an event source and thus allowing events to be associated with the recognition object. It may also be misleading since the application will still compile and run if it is omitted. If the key word is missing, no events will be returned. Once declared, the Procedures menu will then list the events.

With the same ease as selecting an event for a conventional control, you can select an event for the SAPI object. For instance, selecting Recognition from the Procedures menu inserts the appropriate code in the open project file.

An example of the Procedures menu with the Microsoft Speech Platform. The recognition context is declared as the RC object. The Procedures menu lists all the available events for the recognition context. The two in bold indicate those events are already defined. The other events listed will have the code generated for them if event is selected.

A Recognition event is defined as

Private Sub RecoContext_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)

End Sub

Events in Scripting Languages

In scripting languages, use the HTML object tag to instantiate a SAPI object. Event procedures for such an object are identified by the object-ID and the event name. For example, the following JavaScript code snippet demonstrates the definition and creation of an SpVoice object and the definition of a typical Word event procedure.

...
<OBJECT ID="VoiceObj" CLASSID="clsid:96749377-3391-11D2-9EE3-00C04F797396"></OBJECT>

<SCRIPT LANGUAGE="JScript">

function VoiceObj::Word(Number, Position, CharacterPosition,Length)
{
    idTextBox.select();
    var CurrentRange = document.selection.createRange();
    var MyLen = CurrentRange.text.length;
    CurrentRange.moveStart("character", CharacterPosition);
    CurrentRange.moveEnd("character", CharacterPosition + Length - MyLen);
    CurrentRange.select();
    idTextBox.focus();
}
...

There are two ways for applications developers to create a recognizer and a recognition context. The first is to create a recognizer object and then to derive a recognition context from the recognizer. The other is to create a recognition context and then to derive the recognizer from the context.

But in a scripting environment, events can only be received by objects created by the scripting host. And since recognition results are received exclusively through recognition context events, consequently, in a scripting environment, the recognition context must be created first. As a further consequence, the recognizer created from the recognition context will be associated with the default SR engine.

Event Parameters

The SAPI engines return information back to the application through the event handler's parameters. SAPI events can come from different sources and there can even be multiple instances of recognition contexts or voices. However each event is self-contained and has enough information to relate the event to a specific and unique source. If the recognition context or even the recognizer itself is important, you can derive the source by tracing back information through the parameters.

In the case of a Recognition event, a common situation is that the application is interested only in the last parameter, the recognition result. This contains information about the recognized phrase including the associated text. Parameters are not required to be used. In some instances, it may be important to know only that a recognition occurred; the application may not process any information any further.

Note also the event's parameters represent one-way communications, that of SAPI to the application. It is not possible to change the parameter information and send the changed parameters back to the engine.


Using Events in Code (Microsoft Speech Platform)

 Microsoft Speech Platform

Using Events in Code

Associated With Recognition Contexts

Once the event handler is created, using that particular event is simple. No additional code is needed to initiate the event. That is, if the application receives a Recognition event from SAPI, the Recognition code is invoked automatically and immediately. For example, if the recognition event code were as follows for, notice two issues.

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Form1.Label1.Caption = Result.PhraseInfo.GetText
End Sub

First, a hypothetical Label1 text box on Form1 of the application would be updated with the text from the successful recognition. Second, notice each event is associated with a particular recognition context. In this case recognition context is presumed to be named RC. A possible declaration could be

Public WithEvents RC As SpSharedRecoContext

Associating each event with a recognition context simplifies handling the event. Since each application can have more than one recognition context, a particular recognition context can be active or inactive at any moment, and recognition contexts are generally used to isolate specific application areas (such as one recognition context for the menus, another for general dictation, and possible others for dialog boxes), when an event is received, the scope of the event is automatically defined. For example, in the RC_Recognition listed above, the event simply displays the results to a text box. The application does not have to test if the event related to menus, which would probably require a different set of actions.

Applications, however, can have additional processing within the event. For example, assuming there is one recognition context for all the menus, the following recognition event does have to test for which menu is intended. It uses a context free (CFG) grammar and all the rule names are defined inside that file.

Private Sub MenuBar_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)

    Set RecoResult = Result
    Dim rp As ISpeechPhraseInfo
    Set rp = RecoResult.PhraseInfo

    If rp.Rule.Name = "filemenu" Then Form2.Command1_Click
    If rp.Rule.Name = "editmenu" Then Form2.EditMenu_Click
    If rp.Rule.Name = "aboutapplication" Then frmAbout.Show vbModal
End Sub

Event Interests

Both speech recognition and text-to-speech have a wide variety of events. By default, SAPI using automation has all events active except for SREAudioLevel for speech recognition and SVEAudioLevel for text-to-speech. That means all the other kinds of events will be returned by SAPI to the application. Remember, the application does not have to support any particular events; it could simply omit an event handler for it. Nevertheless, the application still receives the event and it takes a minimal amount of time to process it through the queue. For simple applications, this processing time is negligible and has little or no effect. For other applications this additional time could represent an undesirable lag. For instance, if the application were animating a face by using visemes to change the mouth position of the on screen character, speed and timing is important. For speech recognition, a game application could rely on speed as well to process a voice command. While some amount of lag time is inherent to all speech systems (speech processing is not instantaneous), removing unwanted events is one way to minimize the demands on the application.

Controlling the flow of events is done by setting event interests. Event interests is a filtering mechanism by which specific events may be sent back to the application or repressed by the engine to begin with. All, none, or selective events may be chosen to be received. Both groups of events have a similar call for setting interests: speech recognition has ISpeechRecoContext.EventInterests and text-to-speech uses SpVoice.EventInterests. Both methods sets event interest but for the appropriate set of interests.

Event interests work the same way for either technology. The SetInterests specifies only the events to be sent by the engines. Therefore the following call allows a single event to be sent, that of the successful recognition. The sample also assumes a valid RecoContext.

RecoContext.EventInterests = SRERecognition

Additional interests may be set by adding the values together. So that the next sample now allows two events be sent, a recognition and a sound start.

RecoContext.EventInterests = SRERecognition + SRESoundStart

If addition is used, the new value completely replaces the previous set of interests. For example, if the last two samples were executed in the reverse order than presented, the recognition context would only use one event afterward: the recognition. It is not recommended to use subtraction to modify interests. Instead, use logical operators.

Logical operators may also be applied to event interests. For example, an application may need to add one specific event for the moment. Instead of having to refine the entire set of interests, a potentially laborious task if many interests are currently set, use the logical And operator. For example, the following code tests if the current set of interests excludes SRERecognition (by using the logical And) and it not, adds it (by using the logical Or).

If (RC.EventInterests And SREAudioLevel) <> SREAudioLevel Then
    RC.EventInterests = RC.EventInterests Or SREAudioLevel
End If

Setting interests is more simple than retrieving them. Symbolic equivalent may be to set interests. That means to add recognition events the Symbolic equivalent SRERecognition. However, in retrieving the current set of interests, a numeric value is returned instead. For example, by default voice event interests are set to 33,287. The value is the sum of all the individual events. An event interest of SVEWordBoundary, SVEVoiceChange , and SVEViseme would have a value of 296.


Programming Notes (Microsoft Speech Platform)

 Microsoft Speech Platform

Programming Notes for Visual Basic

Hidden members

Certain methods or properties (collectively called members) are designated as hidden. This indicates that member does not display in a browser such as Visual Basic's IntelliSense (or automatic statement completion) menu or in the Object Browser list. Members may be designated as hidden for several reasons. Most commonly, it represents an advanced feature or capability that is not needed in normal situations. Hidden members should be considered carefully before using them.

To view hidden members

  1. On the View menu, click Object Browser.
  2. Right-click the Object Browser window, and then click Show Hidden Members. Drag the scroll box to view hidden members that appear in gray text. With Show Hidden Members selected, these will appear in the IntelliSense menu as well.
  3. Right-click the Object Browser window, and then select Show Hidden Members again to hide the members.

Determining Microsoft Speech Platform's presence

Microsoft Speech Platform requires no special error handling outside of Visual Basic's standard procedures. That is, Microsoft Speech Platform errors may be trapped and handled using the same techniques presented by Visual Basic.

However, there are two special considerations when working with the Microsoft Speech Platform. First, the computer on which the application is being developed must have the SAPI library loaded. Second, the computer running the application with SAPI automation must have SAPI 5.1 or later installed.

The easiest way to determine if an appropriate version of the Microsoft Speech Platform is present on a computer is to simply make calls to the Microsoft Speech Platform and see if they fail. Use error trapping to catch and work around failed Microsoft Speech Platform calls. If all the SAPI calls are caught, it is possible to run Microsoft Speech Platform-enabled applications on computers without a compatible version of Microsoft Speech Platform. Although, those applications cannot use Microsoft Speech Platform functions or functionality, but a separate version of the application does not have to be created or maintained.

For instance, if the following code snippet is executed and the Microsoft Speech Platform is not installed, a run-time error results.

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive
End Sub

The error would be related to creating an object from nonexistent source. On a computer with no version of the Microsoft Speech Platform loaded, this would commonly display

Run-time error '459':
Object or class does not support the set of events

Therefore, the Microsoft Speech Platform calls need an error handler for them. For example, the same code above could be trapped by the following version. The code intends to use gSAPIPresent as a flag marking Microsoft Speech Platform's presence. If all the Microsoft Speech Platform-related calls are conditional based on gSAPIPresent, the application could run on computers lacking Microsoft Speech Platform support. Although those applications could run, voice features could not be used.

Private Sub Form_Load()
    On Error GoTo SAPINotFound

    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive
    gSAPIPresent = True
    Exit Sub

SAPINotFound:
    If Err.Number = 459 Then
        MsgBox "SAPI not found"
    Else
        MsgBox "Error encountered : " & Err.Number
    End If

    gSAPIPresent = False
End Sub

If an application needs to explicitly test for the presence of a compatible version of the Microsoft Speech Platform, use the following code to load a small Microsoft Speech Platform object. If the call fails, Microsoft Speech Platform is not present.

Private Sub Form_Load()
{
   'Use Visual Basic's built in error checking
   On Error GoTo Err_SAPILoad

   Dim PIB As ISpeechPhraseInfoBuilder
   'Now if this call fails Visual Basic's Error handling will kick in and send the program flow to Err_SAPILoad
   Set PIB = New SpPhraseInfoBuilder

Err_SAPILoad:
   MsgBox "Error loading SAPI objects! Please make sure SAPI5.1 or later is correctly installed.", vbCritical
}

Error Codes

Microsoft Speech Platform error codes are listed in Error Codes.

COM Reliance

Microsoft Speech Platform automation is built on a COM foundation. As a result many of the SAPI automation calls are virtually identical to correspondingly named calls the C/C++ section of the Microsoft Speech Platform documentation. It may be helpful read the related sections for additional insight and suggestions for automation calls. While the C/C++ references will specify C-style programming terms and code samples, in many cases the principles will be the same.


Automation Enumerations (Microsoft Speech Platform)

 Microsoft Speech Platform

Automation Enumerations

The Automation Enumerations specify the possible values for many of the types of data used in speech automation.

Automation Enumerations

The automation enumerations include the following:

Enumerations | Description
SpeechAudioFormatType | Lists the supported stream formats.
SpeechAudioState | Sets the audio input or output state to one of four possible states.
SpeechBookmarkOptions | Specifies whether or not the bookmark will pause a speech recognition(SR) engine.
SpeechDataKeyLocation | Specifies the top-level speech configuration database keys.
SpeechDiscardType | Indicates portions of a recognition result to be removed or eliminated once they are no longer needed.
SpeechDisplayAttributes | Specifies information about the display of a word.
SpeechEmulationCompareFlags | Specifies information about the display of a word.
SpeechEngineConfidence |
SpeechFormatType | Used to request either the input format for the original audio source, or the format actually arriving at the speech engine.
SpeechGrammarRuleStateTransitionType | Lists the types of transitions for the speech recognition engine.
SpeechGrammarState | Defines the possible states of a speech grammar.
SpeechGrammarWordType | Specifies the type of the word(s) to be added to a grammar.
SpeechInterference | Lists possible causes of interference or poor recognition with the input stream.
SpeechLexiconType | Specifies the allowed lexicon types.
SpeechLoadOption | indicates how a speech grammar is loaded.
SpeechPartOfSpeech | Defines the parts-of-speech categories used in SAPI.
SpeechRecoContextState | Provides lists levels of control for setting and restoring recognition states for each recognition context.
SpeechRecoEvents | Lists the event interests for the recognition context.
SpeechRecognitionType | Specifies the state of the SR engine.
SpeechRecognizerState | Enumerates the states of a Recognizer object.
SpeechRetainedAudioOptions | Indicates the options for an audio stream.
SpeechRuleAttributes | Lists attribute's information about grammar rules.
SpeechRuleState | Defines the states of a speech grammar rule.
SpeechRunState | Lists the voice running state.
SpeechSpecialTransitionType | Lists special transitions for the speech recognition engine.
SpeechStreamFileMode | Specifies the file opening states.
SpeechStreamSeekPositionType | Lists the methods to seek a location within a stream.
SpeechTokenContext | Lists the context in which the code managing the newly created object runs.
SpeechTokenShellFolder | Lists possible locations storing token information.
SpeechVisemeFeature | Contains constants specifying features of phonemes and visemes.
SpeechVisemeType | Contains constants for each of the visemes supported by the SpVoice object.
SpeechVoiceEvents | Enumerates the types of events which the SpVoice object can raise.
SpeechVoicePriority | Enumerates the possible Priority settings of an SpVoice object.
SpeechVoiceSpeakFlags | Contains flags that control the SpVoice.Speak method.
SpeechWordPronounceable | Defines the set of return values from the IsPronounceable method of the SpRecoGrammar object.
SpeechWordType | Specifies the change state of a word/pronunciation combination in a lexicon.


SpeechAudioFormatType (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechAudioFormatType Enum

The SpeechAudioFormatType enumeration lists the supported stream formats.

These enumeration elements are all common audio formats ranging from the uncompressed PCM formats to highly compressed formats. They are available as standard formats on the Windows operating systems and are supported by SAPI 5.

Definition

Enum SpeechAudioFormatType
    SAFTDefault = -1
    SAFTNoAssignedFormat = 0
    SAFTText = 1
    SAFTNonStandardFormat = 2
    SAFTExtendedAudioFormat = 3

    // Standard PCM wave formats
    SAFT8kHz8BitMono = 4
    SAFT8kHz8BitStereo = 5
    SAFT8kHz16BitMono = 6
    SAFT8kHz16BitStereo = 7
    SAFT11kHz8BitMono = 8
    SAFT11kHz8BitStereo = 9
    SAFT11kHz16BitMono = 10
    SAFT11kHz16BitStereo = 11
    SAFT12kHz8BitMono = 12
    SAFT12kHz8BitStereo = 13
    SAFT12kHz16BitMono = 14
    SAFT12kHz16BitStereo = 15
    SAFT16kHz8BitMono = 16
    SAFT16kHz8BitStereo = 17
    SAFT16kHz16BitMono = 18
    SAFT16kHz16BitStereo = 19
    SAFT22kHz8BitMono = 20
    SAFT22kHz8BitStereo = 21
    SAFT22kHz16BitMono = 22
    SAFT22kHz16BitStereo = 23
    SAFT24kHz8BitMono = 24
    SAFT24kHz8BitStereo = 25
    SAFT24kHz16BitMono = 26
    SAFT24kHz16BitStereo = 27
    SAFT32kHz8BitMono = 28
    SAFT32kHz8BitStereo = 29
    SAFT32kHz16BitMono = 30
    SAFT32kHz16BitStereo = 31
    SAFT44kHz8BitMono = 32
    SAFT44kHz8BitStereo = 33
    SAFT44kHz16BitMono = 34
    SAFT44kHz16BitStereo = 35
    SAFT48kHz8BitMono = 36
    SAFT48kHz8BitStereo = 37
    SAFT48kHz16BitMono = 38
    SAFT48kHz16BitStereo = 39

    // TrueSpeech format
    SAFTTrueSpeech_8kHz1BitMono = 40

    // A-Law formats
    SAFTCCITT_ALaw_8kHzMono = 41
    SAFTCCITT_ALaw_8kHzStereo = 42
    SAFTCCITT_ALaw_11kHzMono = 43
    SAFTCCITT_ALaw_11kHzStereo = 4
    SAFTCCITT_ALaw_22kHzMono = 44
    SAFTCCITT_ALaw_22kHzStereo = 45
    SAFTCCITT_ALaw_44kHzMono = 46
    SAFTCCITT_ALaw_44kHzStereo = 47

    // u-Law formats
    SAFTCCITT_uLaw_8kHzMono = 48
    SAFTCCITT_uLaw_8kHzStereo = 49
    SAFTCCITT_uLaw_11kHzMono = 50
    SAFTCCITT_uLaw_11kHzStereo = 51
    SAFTCCITT_uLaw_22kHzMono = 52
    SAFTCCITT_uLaw_22kHzStereo = 53
    SAFTCCITT_uLaw_44kHzMono = 54
    SAFTCCITT_uLaw_44kHzStereo = 55
    SAFTADPCM_8kHzMono = 56
    SAFTADPCM_8kHzStereo = 57
    SAFTADPCM_11kHzMono = 58
    SAFTADPCM_11kHzStereo = 59
    SAFTADPCM_22kHzMono = 60
    SAFTADPCM_22kHzStereo = 61
    SAFTADPCM_44kHzMono = 62
    SAFTADPCM_44kHzStereo = 63

    // GSM 6.10 formats
    SAFTGSM610_8kHzMono = 64
    SAFTGSM610_11kHzMono = 65
    SAFTGSM610_22kHzMono = 66
    SAFTGSM610_44kHzMono = 67

    // Other formats
    SAFTNUM_FORMATS = 68
End Enum

Remarks

SAFTNonStandardFormat
SAFTNonStandardFormat is a non-SAPI 5 standard format without a WAVEFORMATEX description.
SAFTExtendedAudioFormat
SAFTExtendedAudioFormat is a non-SAPI 5 standard format but has WAVEFORMATEX description.


SpeechAudioState (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechAudioState Enum

The SpeechAudioState enumeration lists the four possible audio input and output states.

This is used by ISpeechAudioStatus.State property and ISpeechAudio.SetState method.

Definition

Enum SpeechAudioState
    SASClosed = 0
    SASStop = 1
    SASPause = 2
    SASRun = 3
End Enum

Elements

SASClosed
Audio is stopped and closed. For multimedia audio input devices (sound cards etc.), the device will be released. It can be opened by other processes and potentially made unavailable to SAPI.
SASStop
Audio is stopped. For multimedia audio input devices (sound cards etc.), the audio device will not be closed. This guarantees that SAPI can restart it without an intervening process opening it.
SASPause
Audio is paused. Staying in this state for too long a period will cause audio loss.
SASRun
Audio is enabled.


SpeechBookmarkOptions (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechBookmarkOptions Enum

The SpeechBookmarkOptions enumeration lists bookmark options.

Definition

Enum SpeechBookmarkOptions
    SBONone = 0
    SBOPause = 1
End Enum

Elements

SBONone
The recognition context will not pause when it encounters the bookmark.
SBOPause
The recognition context will pause when it encounters the bookmark. This is the same as calling ISpeechRecoContext.Pause. The pause stops the speech recognition engine from processing any more data until Resume is called. In a paused state, the application can perform tasks such as changing grammars while the engine is at a known position in the stream. The application must explicitly begin processing afterward with ISpeechRecoContext.Resume.


SpeechDataKeyLocation (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechDataKeyLocation Enum

The SpeechDataKeyLocation enumeration lists the top-level speech configuration database keys.

Used with ISpeechObjectTokenCategory.GetDataKey to read and write token categories.

Definition

Enum SpeechDataKeyLocation
    SDKLDefaultLocation = 0
    SDKLCurrentUser = 1
    SDKLLocalMachine = 2
    SDKLCurrentConfig = 5
End Enum

Elements

SDKLDefaultLocation
The default location is set by ISpObjectTokenCategory.
SDKLCurrentUser
The speech configuration database key HKEY_CURRENT_USER.
SDKLLocalMachine
The speech configuration database key HKEY_LOCAL_MACHINE.
SDKLCurrentConfig
The speech configuration database key HKEY_CURRENT_CONFIG.


SpeechDiscardType (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechDiscardType Enum

The SpeechDiscardType enumeration lists flags indicating portions of a recognition result to be removed or eliminated once they are no longer needed.

Definition

Enum SpeechDiscardType
    SDTProperty = 1
    SDTReplacement = 2
    SDTRule = 4
    SDTDisplayText = 8
    SDTLexicalForm = 16
    SDTPronunciation = 32
    SDTAudio = 64
    SDTAlternates = 128
    SDTAll = 255
End Enum

Elements

SDTProperty
Removes the property tree.
SDTReplacement
Removes the phrase replacement text for inverse text normalization.
SDTRule
Removes the non-top level rule tree information for a phrase.
SDTDisplayText
Removes the display text.
SDTLexicalForm
Removes the lexicon from text.
SDTPronunciation
Removes the pronunciation text.
SDTAudio
Removes the audio data that is attached to a phrase. However, the audio has to have been both set and retained.
SDTAlternates
Removes the alternate data that is attached to a phrase. Discarding alternates loses the words permanently and they cannot be retrieved.
SDTAll
Remove all the features above.


SpeechDisplayAttributes (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechDisplayAttributes Enum

The SpeechDisplayAttributes enumeration lists the possible ways of displaying a word.

Used by ISpeechPhraseReplacement.DisplayAttributes and ISpeechPhraseElement.DisplayAttributes to retrieve SpeechDisplayAttributes for the recognition. This property cannot be set and it is determined by the particular engine and is specific for the language.

Definition

Enum SpeechDisplayAttributes
    SDA_No_Trailing_Space = 0
    SDA_One_Trailing_Space = 2
    SDA_Two_Trailing_Spaces = 4
    SDA_Consume_Leading_Spaces = 8
End Enum

Elements

SDA_No_Trailing_Space
Does not insert any trailing spaces after words.
SDA_One_Trailing_Space
Inserts one trailing space, used for most words.
SDA_Two_Trailing_Spaces
Inserts two trailing spaces, often used after a sentence's final period.
SDA_Consume_Leading_Spaces
Consume leading space, often used for periods. If this is absent, the word should have a leading space by default.


SpeechEngineConfidence (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechEngineConfidence Enum

The SpeechEngineConfidence enumeration specifies levels of confidence.

Results returned by the speech recognition (SR) engine may be assigned one of these values to indicate the degree of confidence of the recognition. Alternatively, the engine may be assigned one of these values as a minimum requirement before passing back a recognition.

Definition

Enum SpeechEngineConfidence
    SECLowConfidence = -1
    SECNormalConfidence = 0
    SECHighConfidence = 1
End Enum

Elements

SECLowConfidence
Indication of low confidence.
SECNormalConfidence
Indication of normal confidence.
SECHighConfidence
Indication of high confidence.


SpeechEmulationCompareFlags (Microsoft Speech Platform)

Microsoft Speech Platform

SpeechEmulationCompareFlags Enum

New in SAPI 5.3

Enumerates values of comparison options in emulation.

typedef enum SpeechEmulationCompareFlags
{
    SECFIgnoreCase = 1
    SECFIgnoreKanaType = 65536
    SECFIgnoreWidth = 131072
    SECFNoSpecialChars = 536870912
    SECFEmulateResult = 1073741824
    SECFDefault = SECFIgnoreCase + SECFIgnoreKanaType + SECFIgnoreWidth
} SpeechEmulationCompareFlags;

Elements

SECFIgnoreCase
The comparison is case insensitive.
SECFIgnoreKanaType
The comparison ignores Kana types.
SECFIgnoreWidth
The comparison ignores width.
SECFNoSpecialChars
The comparison does not allow for special characters.
SECFEmulateResult
The comparison....
SECFDefault
The default comparison options (ignore case, Kana types, and width).


SpeechFormatType (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechFormatType Enum

The SpeechFormatType enumeration requests either the input format for the original audio source, or the format that actually arrives at the speech engine.

SAPI may be dynamically converting the stream to a different format and as a result, the original stream format may be different than the format received by the speech recognition (SR) engine.

Definition

Enum SpeechFormatType
    SFTInput = 0
    SFTSREngine = 1
End Enum

Elements

SFTInput
Request the format of the original audio input.
SFTSREngine
Request the format received by the SR engine.


SpeechGrammarRuleStateTransitionType (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechGrammarRuleStateTransitionType Enum

The SpeechGrammarRuleStateTransitionType enumeration lists the types of transitions for the speech recognition engine.

Definition

Enum SpeechGrammarRuleStateTransitionType
    SGRSTTEpsilon = 0
    SGRSTTWord = 1
    SGRSTTRule = 2
    SGRSTTDictation = 3
    SGRSTTWildcard = 4
    SGRSTTTextBuffer = 5
End Enum

Elements

SGRSTTEpsilon
Indicates there should be an epsilon transition. These are NULL transitions that can be traversed without recognizing anything.
SGRSTTWord
Indicates there should be a word transition. These represent single words that the recognizer will recognize before advancing to the next state.
SGRSTTRule
Indicates there should be a rule transition. These represent transitions into sub-rules. This transition is only passed when a path through the sub-rule has been recognized.
SGRSTTDictation
Indicates there should be a dictation transition. SGRSTTDictation is a special transition and may not be supported by all engines. This is used to embed dictation within a context-free grammar (CFG). Each transition means one word should be recognized.
SGRSTTWildcard
Indicates there should be a wildcard transition. SGRSTTWildcard is a special transition and may not be supported by all engines. This indicates a transition that matches any word or words. The engine does not try and recognize the spoken words. The engine includes the string value WildcardInCFG as an attribute in its object token to inform the application that it is capable of supporting this.
SGRSTTTextBuffer
Indicates there should be a text buffer transition. SGRSTTTextBuffer is a special transition and may not be supported by all engines. This indicates that the engine is to recognize a sub-string of words from the text buffer, if it has been set.


SpeechGrammarState (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechGrammarState Enum

The SpeechGrammarState enumeration lists the possible states of a speech grammar.

Definition

Enum SpeechGrammarState
    SGSDisabled = 0
    SGSEnabled = 1
    SGSExclusive = 3
End Enum

Elements

SGSEnabled
SGSEnabled indicates that the grammar can receive recognitions and that its rules are active. This is the default speech grammar state.
SGSDisabled
SGSDisabled indicates that the grammar cannot receive recognitions and that its rules are inactive. Rules can still be added to a grammar in this state.
SGSExclusive
SGSExclusive indicates that this grammar is the only active grammar and disables all rules that are not part of this grammar. Currently not implemented.


SpeechGrammarWordType (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechGrammarWordType Enum

The SpeechGrammarWordType enumeration lists the types of words in a grammar.

Definition

Enum SpeechGrammarWordType
    SGDisplay = 0
    SGLexical = 1
    SGPronounciation = 2
    SGLexicalNoSpecialChars = 3
End Enum

Elements

SGDisplay
Each word to be added is in display form. That is, it possibly will have to be converted into lexical form(s). For example, the word "23" (display form) would have to converted into "twenty three" (lexical form). This is currently not implemented.
SGLexical
Each word to be added is in lexical form and can be used to access the lexicon. This type is specified in the speech text grammar format as <GRAMMAR WORDTYPE="LEXICAL">.
SGPronounciation
Each word is specified solely by its pronunciation. This is currently not implemented.
SGLexicalNoSpecialChars
Switches off the handling of special characters in the grammar. For example "*" normally means dictation and "?" means wildcard, but this flag means that "*" means asterisk, and "?" means ellipsis.


SpeechInterference (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechInterference Enum

The SpeechInterference enumeration lists possible causes of interference or poor recognition with the input audio stream.

Definition

Enum SpeechInterference
    SINone = 0
    SINoise = 1
    SINoSignal = 2
    SITooLoud = 3
    SITooQuiet = 4
    SITooFast = 5
    SITooSlow = 6
End Enum

Elements

SINone
Private. Do not use.
SINoise
The sound received is interpreted by the speech recognition engine as noise. This event is generated when there is a SOUND_START followed by a SOUND_END without an intervening PHRASE_START. The event will be also generated during dictation if, after a series of hypotheses, it is determined that the signal is noise.
SINoSignal
A sound is received but it is of a constant intensity. This also includes the microphone being unplugged or muted.
SITooLoud
A sound is received but the stream intensity is too high for discrete recognition.
SITooQuiet
A sound is received but the stream intensity is too low for discrete recognition.
SITooFast
The words are spoken too quickly for discrete recognition.
SITooSlow
The words are spoken too slowly and indicates excessive time between words.


SpeechLexiconType (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechLexiconType Enum

The SpeechLexiconType enumeration lists the allowed lexicon types.

Currently there are only two types in use: user and application lexicons. Additional types may be added in the future or created uniquely by the application.

Definition

Enum SpeechLexiconType {
   SLTUser   = 1
   SLTApp    = 2
} End Enum

Elements

SLTUser
Indicates the user lexicon. Each Windows user has a unique user lexicon.
SLTApp
Indicates the application lexicon. An application lexicon is shared by all users.


SpeechLoadOption (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechLoadOption Enum

The SpeechLoadOption enumeration lists the options available when loading a speech grammar.

Definition

Enum SpeechLoadOption
    SLOStatic = 0
    SLODynamic = 1
End Enum

Elements

SLOStatic
Specifies that the grammar is loaded statically.
SLODynamic
Specifies that the grammar is loaded dynamically, meaning that rules can be modified and committed at run time.


SpeechPartOfSpeech (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechPartOfSpeech Enum

The SpeechPartOfSpeech enumeration lists the parts-of-speech categories used in SAPI.

This list of known parts-of-speech types is intentionally small and broad and will be expanded and refined in future releases. SpeechPartOfSpeech in its minimal form is required to support look ups from the standard SAPI lexicon. This information is useful to TTS engines in order to determine the correct pronunciation of ambiguous words based on their context.

Definition

Enum SpeechPartOfSpeech
    SPSNotOverriden = -1
    SPSUnknown = 0
    SPSNoun = 4096
    SPSVerb = 8192
    SPSModifier = 12288
    SPSFunction = 16384
    SPSInterjection = 20480
    SPSSuppressWord = 61440
End Enum

Elements

SPSNotOverriden
Indicates that the part of speech already present in the lexicon should not be overridden.
SPSUnknown
Indicates that the part of speech is unknown and is probably from the user lexicon.
SPSNoun
Indicates that the part of speech is a noun.
SPSVerb
Indicates that the part of speech is a verb.
SPSModifier
Indicates that the part of speech is a modifier.
SPSFunction
Indicates that the part of speech is a function.
SPSInterjection
Indicates that the part of speech is an interjection.
SPSSuppressWord
Marks works in the user lexicon as not to be recognized. Essentially, this removes words from the vocabulary.


SpeechRecoContextState (Speech API (SAPI) SDK 5.4)

 Microsoft Speech SDK Version 5.4

SpeechRecoContextState Enum

The SpeechRecoContextState enumeration lists the states of a recognition context.

Used by ISpeechRecoContext.State

Definition

Enum SpeechRecoContextState
    SRCS_Disabled = 0
    SRCS_Enabled = 1
End Enum

Elements

SRCS_Disabled
Specifies that grammars associated with this recognition context are disabled.
SRCS_Enabled
Specifies that grammars associated with this recognition context are enabled.


SpeechRecoEvents (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechRecoEvents Enum

The SpeechRecoEvents enumeration lists speech recognition (SR) events.

Used in ISpeechRecoContext.VoicePurgeEvent and ISpeechRecoContext.EventInterests.

Definition

Enum SpeechRecoEvents
    SREStreamEnd = 1
    SRESoundStart = 2
    SRESoundEnd = 4
    SREPhraseStart = 8
    SRERecognition = 16
    SREHypothesis = 32
    SREBookmark = 64
    SREPropertyNumChange = 128
    SREPropertyStringChange = 256
    SREFalseRecognition = 512
    SREInterference = 1024
    SRERequestUI = 2048
    SREStateChange = 4096
    SREAdaptation = 8192
    SREStreamStart = 16384
    SRERecoOtherContext = 32768
    SREAudioLevel = 65536
    SREPrivate = 262144
    SREAllEvents = 393215
End Enum

Elements

SREStreamEnd
SR engine has reached the end of an input stream.
SRESoundStart
SR engine has detected the start of non-trivial audio data.
SRESoundEnd
SR engine has detected the end of non-trivial audio data.
SREPhraseStart
SR engine has detected the start of a recognizable phrase.
SRERecognition
SR engine's best hypothesis for the audio data.
SREHypothesis
SR engine's interim hypothesis for the result of the audio data.
SREBookmark
SR engine has reached the specified point in the audio stream.
SREPropertyNumChange
LPARAM points to a string WPARAM that is the attribute value.
SREPropertyStringChange
LPARAM pointer to a buffer. Two concatenated null-terminated strings.
SREFalseRecognition
Apparent speech with no valid recognition.
SREInterference
LPARAM is any combination of SpeechInterference flags.
SRERequestUI
LPARAM is string.
SREStateChange
WPARAM contains new recognition state.
SREAdaptation
The adaptation buffer is now ready to be accepted.
SREStreamStart
SR engine has reached the start of an input stream.
SRERecoOtherContext
Phrase finished and recognized but for other context.
SREAudioLevel
Input audio volume level
SREPrivate
Private engine-specific event.
SREAllEvents
All events listed above.


SpeechRecognitionType (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechRecognitionType Enum

The SpeechRecognitionType enumeration lists the types of speech recognition.

The Recognition method of the SpInProcRecognizer and SpSharedRecognizer objects returns a SpeechRecognitionType member indicating the type of recognition which produced the recognition result.

Definition

Enum SpeechRecognitionType
    SRTStandard = 0
    SRTAutopause = 1
    SRTEmulated = 2
    SRTSMLTimeout = 3
    SRTExtendableParse = 4
    SRTReSent = 5
End Enum

Elements

SRTStandard
Indicates that the recognition result was produced by standard recognition.
SRTAutopause
Indicates that the recognition result was produced by standard recognition and that the engine is paused.
SRTEmulated
Indicates that the recognition result was produced by recognition emulation.
SRTSMLTimeout
Indicates that there was a timeout generating the SML and hence no SML will be returned.
SRTExtendableParse
The user said something that was a valid path through the grammar, but it is possible they could be about to say something else. For example, if the grammar contains "play the ace" and "play the ace of spades" and the user says "play the ace", this flag is set.
SRTReSent
*TODO* SRTReSent does....


SpeechRecognizerState (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechRecognizerState Enum

The SpeechRecognizerState enumeration lists the states of a Recognizer object.

Definition

Enum SpeechRecognizerState
    SRSInactive = 0
    SRSActive = 1
    SRSActiveAlways = 2
    SRSInactiveWithPurge = 3
End Enum

Elements

SRSInactive
The engine and audio input are inactive and no audio is being read, even if there are rules active. The audio device will be closed in this state.
SRSActive
Recognition takes place if there are any active rules. If a rule is active, audio will be read and passed to the SR engine and recognition will take place.
SRSActiveAlways
Indicates the audio is running regardless of the rule state. Even if there are no active rules, audio will still be read and passed to the engine.
SRSInactiveWithPurge
Indicates the engine state is set to inactive and all active audio data is purged. This state is used when an application wishes to shut an engine down as quickly as possible, without waiting for it to finish processing any audio data that is currently buffered.


SpeechRetainedAudioOptions (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechRetainedAudioOptions Enum

The SpeechRetainedAudioOptions enumeration lists the options for retaining data from an audio stream.

Used in ISpeechRecoContext.RetainedAudio.

Definition

Enum SpeechRetainedAudioOptions
    SRAONone = 0
    SRAORetainAudio = 1
End Enum

Elements

SRAONone
Indicates that the audio should not be retained, but discarded after use.
SRAORetainAudio
Flag indicates that the audio stream should be retained (e.g., serialization of recognition object, playback of recognized audio, etc.).


SpeechRuleAttributes (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechRuleAttributes Enum

The SpeechRuleAttributes enumeration lists the possible attributes of a grammar rule.

Used in ISpeechGrammarRules.Add and ISpeechGrammarRule.Attributes.

Definition

Enum SpeechRuleAttributes
    SRATopLevel = 1
    SRADefaultToActive = 2
    SRAExport = 4
    SRAImport = 8
    SRAInterpreter = 16
    SRADynamic = 32
    SRARoot = 64
End Enum

Elements

SRATopLevel
Specifies that the rule is defined as a top-level rule. Top-level rules are the entry points into the grammar and can be activated or deactivated programmatically. Set a rule as top-level by using the TOPLEVEL attribute in the Speech Text Grammar Format.
SRADefaultToActive
Specifies that the rule is defined as a top-level rule that is activated by default. This can be set using the TOPLEVEL="ACTIVE" attribute-value pair in the Speech Text Grammar Format.
SRAExport
Specifies the rule is exported and hence can be referred to by a rule in another grammar. This can be set using the EXPORT="YES" attribute-value pair in the Speech Text Grammar Format.
SRAImport
Specifies the rule is imported from another grammar and is therefore not defined in this grammar.
SRAInterpreter
Specifies the rule has an interpreter (custom C/C++ code implementing the ISpCFGInterpreter interface) associated with it.
SRADynamic
Specifies the rule is dynamic (can be changed programmatically through the ISpGrammarBuilder interface). Note that the CFG must be loaded with the SPLO_DYNAMIC flag to enable changes at run time.
SRARoot
Specifies whether this is the root rule in the grammar. This is only meaningful for SRGS grammars.


SpeechRuleState (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechRuleState Enum

The SpeechRuleState enumeration lists the states of a speech grammar rule.

Definition

Enum SpeechRuleState
    SGDSInactive = 0
    SGDSActive = 1
    SGDSActiveWithAutoPause = 3
    SGDSActiveUserDelimited = 4
End Enum

Elements

SGDSInactive
Grammar rule is inactive.
SGDSActive
Grammar rule is active.
SGDSActiveWithAutoPause
SR engine will be placed in a paused state when the grammar rule is recognized.
SGDSActiveUserDelimited
Indicates that the audio will start when the user starts speaking, and will end when the user stops speaking.


SpeechRunState (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechRunState Enum

The SpeechRunState enumeration lists the running states of a TTS voice.

Used with ISpeechVoiceStatus.RunningState.

Definition

Enum SpeechRunState
    SRSEDone = 1
    SRSEIsSpeaking = 2
End Enum

Elements

SRSEDone
The voice has finished rendering all queued phrases.
SRSEIsSpeaking
The SpVoice currently claims the audio queue.

Remarks

A SpeechRunState value of zero represents a state in which the voice is waiting to speak. This condition is returned by ISpeechVoiceStatus.RunningState before the voice has begun speaking, and when the voice is interrupted by an alert voice.


SpeechSpecialTransitionType (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechSpecialTransitionType Enum

The SpeechSpecialTransitionType enumeration lists special transitions for the speech recognition engine.

Special transitions may not be supported by all speech engines. Used in ISpeechGrammarRuleState.AddSpecialTransition.

Definition

Enum SpeechSpecialTransitionType
    SSTTWildcard = 1
    SSTTDictation = 2
    SSTTTextBuffer = 3
End Enum

Elements

SSTTWildcard
Indicates there should be a wildcard transition. SGRSTTWildcard is a special transition and may not be supported by all engines. This indicates a transition that matches any word or words. The engine does not try to recognize the spoken words. The engine includes the string value WildcardInCFG as an attribute in its object token to inform the application that it is capable of supporting this.
SSTTDictation
Indicates there should be a dictation transition. SGRSTTDictation is a special transition and may not be supported by all engines. This is used to embed dictation within a context-free grammar (CFG). Each transition means one word should be recognized.
SSTTTextBuffer
Indicates there should be a text buffer transition. SGRSTTTextBuffer is a special transition and may not be supported by all engines. This indicates that the engine is to recognize a sub-string of words from the text-buffer, if it has been set.


SpeechStreamFileMode (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechStreamFileMode Enum

The SpeechStreamFileMode enumeration lists the access modes of a file stream.

Used by SpFileStream.Open.

Definition

Enum SpeechStreamFileMode
    SSFMOpenForRead = 0
    [hidden] SSFMOpenReadWrite = 1
    [hidden] SSFMCreate = 2
    SSFMCreateForWrite = 3
End Enum

Elements

SSFMOpenForRead
Opens an existing file as read-only.
SSFMOpenReadWrite
[hidden] Opens an existing file as read-write. Not supported for wav files.
SSFMCreate
[hidden] Opens an existing file as read-write. Else, it creates the file then opens it as read-write. Not supported for wav files.
SSFMCreateForWrite
Creates file even if file exists and so destroys or overwrites the existing file.


SpeechStreamSeekPositionType (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechStreamSeekPositionType Enum

The SpeechStreamSeekPositionType enumeration lists the types of positioning from which a Seek method can be performed.

Used by ISpeechBaseStream.Seek.

Definition

Enum SpeechStreamSeekPositionType
    SSSPTRelativeToStart = 0
    SSSPTRelativeToCurrentPosition = 1
    SSSPTRelativeToEnd = 2
End Enum

Elements

SSSPTRelativeToStart
Calculates the stream offset relative from the start of the stream.
SSSPTRelativeToCurrentPosition
Calculates the stream offset relative from the current position.
SSSPTRelativeToEnd
Calculates the stream offset relative from the end of the stream.


SpeechTokenContext (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechTokenContext Enum

The SpeechTokenContext enumeration lists the context in which the code managing the newly created object runs.

This is associated with COM and the use of CoRegisterClassObject to make new objects. Used in SpObjectToken.CreateInstance

Definition

Enum SpeechTokenContext
    STCInprocServer = 1
    STCInprocHandler = 2
    STCLocalServer = 4
    STCRemoteServer = 16
    STCAll = 23
End Enum

Elements

STCInprocServer
Creates and manages objects in the same process as the caller of the function.
STCInprocHandler
Creates and manages objects as an in process (InProc) handler. This is a DLL running in the client process and implements client-side structures of this class when instances are accessed remotely.
STCLocalServer
Creates and manages objects that are loaded in a separate process space; that is, it runs on same computer but in a different process.
STCRemoteServer
Creates and manages objects on a remote machine context.
STCAll
Creates and manages objects for all class contexts.


SpeechTokenShellFolder (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechTokenShellFolder Enum

The SpeechTokenShellFolder enumeration lists possible locations storing token information.

This is a standard Win32 CSIDL value identifying the folder whose path is returned as a String. Used in SpObjectToken.GetStorageFileName.

Definition

Enum SpeechTokenShellFolder
    STSF_AppData = 26
    STSF_LocalAppData = 28
    STSF_CommonAppData = 35
    STSF_FlagCreate = 32768
End Enum

Elements

STSF_AppData
Stores information in the application data of the user's profile.
STSF_LocalAppData
Stores information in the My Computer folder. This is a virtual folder containing everything on the local computer
STSF_CommonAppData
Stores information in the file system directory that serves as a common repository for application-specific data.
STSF_FlagCreate
Forces the creation of a folder. This flag is used in combination with another CSIDL value to create the item.


SpeechVisemeFeature (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechVisemeFeature Enum

The SpeechVisemeFeature enumeration lists the features of phonemes and visemes.

Definition

Enum SpeechVisemeFeature
    SVF_None = 0
    SVF_Stressed = 1
    SVF_Emphasis = 2
End Enum

Elements

SVF_None
Indicates that a viseme or phoneme has no stress or emphasis.
SVF_Stressed
Indicates that a viseme or phoneme is stressed relative to the other phonemes within a word.
SVF_Emphasis
Indicates that the word containing the viseme or phoneme is emphasized relative to the other words within a sentence.


SpeechVisemeType (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechVisemeType Enum

The SpeechVisemeType enumeration lists the visemes supported by the SpVoice object. This list is based on the original Disney visemes.

Definition

Enum SpeechVisemeType
    SVP_0 = 0       'silence
    SVP_1 = 1       'ae ax ah
    SVP_2 = 2       'aa
    SVP_3 = 3       'ao
    SVP_4 = 4       'ey eh uh
    SVP_5 = 5       'er
    SVP_6 = 6       'y iy ih ix
    SVP_7 = 7       'w uw
    SVP_8 = 8       'ow
    SVP_9 = 9       'aw
    SVP_10 = 10     'oy
    SVP_11 = 11     'ay
    SVP_12 = 12     'h
    SVP_13 = 13     'r
    SVP_14 = 14     'l
    SVP_15 = 15     's z
    SVP_16 = 16     'sh ch jh zh
    SVP_17 = 17     'th dh
    SVP_18 = 18     'f v
    SVP_19 = 19     'd t n
    SVP_20 = 20     'k g ng
    SVP_21 = 21     'p b m
End Enum

Elements

SVP_0
The viseme representing silence.
SVP_1
The viseme representing ae, ax, and ah.
SVP_2
The viseme representing aa.
SVP_3
The viseme representing ao.
SVP_4
The viseme representing ey, eh, and uh.
SVP_5
The viseme representing er.
SVP_6
The viseme representing y, iy, ih, and ix.
SVP_7
The viseme representing w and uw.
SVP_8
The viseme representing ow.
SVP_9
The viseme representing aw.
SVP_10
The viseme representing oy.
SVP_11
The viseme representing ay.
SVP_12
The viseme representing h.
SVP_13
The viseme representing r.
SVP_14
The viseme representing l.
SVP_15
The viseme representing s and z.
SVP_16
The viseme representing sh, ch, jh, and zh.
SVP_17
The viseme representing th and dh.
SVP_18
The viseme representing f and v.
SVP_19
The viseme representing d, t and n.
SVP_20
The viseme representing k, g and ng.
SVP_21
The viseme representing p, b and m.


SpeechVoiceEvents (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechVoiceEvents Enum

The SpeechVoiceEvents enumeration lists the types of events which a text-to-speech (TTS) engine can send to an SpVoice object.

Definition

Enum SpeechVoiceEvents
    SVEStartInputStream = 2
    SVEEndInputStream = 4
    SVEVoiceChange = 8
    SVEBookmark = 16
    SVEWordBoundary = 32
    SVEPhoneme = 64
    SVESentenceBoundary = 128
    SVEViseme = 256
    SVEAudioLevel = 512
    SVEPrivate = 32768
    SVEAllEvents = 33790
End Enum

Elements

SVEStartInputStream
Represents the StartStream event, which occurs when the engine begins speaking a stream.
SVEEndInputStream
Represents the EndStream event, which occurs when the engine encounters the end of a stream while speaking.
SVEVoiceChange
Represents the VoiceChange event, which occurs when the engine encounters a change of Voice while speaking.
SVEBookmark
Represents the Bookmark event, which occurs when the engine encounters a bookmark while speaking.
SVEWordBoundary
Represents the WordBoundary event, which occurs when the engine completes a word while speaking.
SVEPhoneme
Represents the Phoneme event, which occurs when the engine completes a phoneme while speaking.
SVESentenceBoundary
Represents the SentenceBoundary event, which occurs when the engine completes a sentence while speaking.
SVEViseme
Represents the Viseme event, which occurs when the engine completes a viseme while speaking.
SVEAudioLevel
Represents the AudioLevel event, which occurs when the engine has completed an audio level change while speaking.
SVEPrivate
Represents a private engine event.
SVEAllEvents
Represents all speech voice events.


SpeechVoicePriority (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechVoicePriority Enum

The SpeechVoicePriority enumeration lists the possible Priority settings of an SpVoice object.

The priority level defines the order in which the text-to-speech (TTS) engine processes a voice object's speech requests relative to requests from other voice objects. Higher priority levels are assigned to error-handling voices and the lowest priority level is assigned to normal voices.

The default Priority setting of a voice is SVPNormal.

Definition

Enum SpeechVoicePriority
    SVPNormal = 0
    SVPAlert = 1
    SVPOver = 2
End Enum

Elements

SVPNormal
The priority of a normal voice. Text streams spoken by a normal voice are added to the end of the voice queue. A voice with SVPNormal priority cannot interrupt another voice.
SVPAlert
The priority of an alert voice. Text streams spoken by an alert voice are inserted into the voice queue ahead of normal voice streams. An alert voice will interrupt a normal voice, which will resume speaking when the alert voice has finished speaking.
SVPOver
The priority of an over voice. Text streams spoken by an over voice go into the voice queue ahead of normal and alert streams. An over voice will not interrupt, but speaks over (mixes with) the voices of lower priorities.


SpeechVoiceSpeakFlags (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechVoiceSpeakFlags Enum

The SpeechVoiceSpeakFlags enumeration lists flags that control the SpVoice.Speak method.

Definition

Enum SpeechVoiceSpeakFlags
    'SpVoice Flags
    SVSFDefault = 0
    SVSFlagsAsync = 1
    SVSFPurgeBeforeSpeak = 2
    SVSFIsFilename = 4
    SVSFIsXML = 8
    SVSFIsNotXML = 16
    SVSFPersistXML = 32

    'Normalizer Flags
    SVSFNLPSpeakPunc = 64

    'TTS Format
    SVSFParseSapi =
    SVSFParseSsml =
    SVSFParseAutoDetect =

    'Masks
    SVSFNLPMask = 64
    SVSFParseMask =
    SVSFVoiceMask = 127
    SVSFUnusedFlags = -128
End Enum

Elements

SVSFDefault
Specifies that the default settings should be used. The defaults are:
  • To speak the given text string synchronously (override with SVSFlagsAsync),
  • Not to purge pending speak requests (override with SVSFPurgeBeforeSpeak),
  • To parse the text as XML only if the first character is a left-angle-bracket (override with SVSFIsXML or SVSFIsNotXML),
  • Not to persist global XML state changes across speak calls (override with SVSFPersistXML), and
  • Not to expand punctuation characters into words (override with SVSFNLPSpeakPunc).
SVSFlagsAsync
Specifies that the Speak call should be asynchronous. That is, it will return immediately after the speak request is queued.
SVSFPurgeBeforeSpeak
Purges all pending speak requests prior to this speak call.
SVSFIsFilename
The string passed to the Speak method is a file name rather than text. As a result, the string itself is not spoken but rather the file the path that points to is spoken.
SVSFIsXML
The input text will be parsed for XML markup.
SVSFIsNotXML
The input text will not be parsed for XML markup.
SVSFPersistXML
Global state changes in the XML markup will persist across speak calls.
SVSFNLPSpeakPunc
Punctuation characters should be expanded into words (e.g. "This is it." would become "This is it period").
SVSFParseSapi
Force XML parsing as MS SAPI.
SVSFParseSsml
Force XML parsing as W3C SSML.
SVSFParseAutoDetect
The TTS XML format is auto-detected. This is the default if none of these TTS XML format values are present in the bit-field.
SVSFNLPMask
Flags handled by SAPI (as opposed to the text-to-speech engine) are set in this mask.
SVSFParseMask
SVSFParseSapi|SVSFParseSsml
SVSFVoiceMask
This is an existing SAPI 5.1 mask that has every flag bit set. In 5.3, it has been extended to contain SVSFParseMask.
SVSFUnusedFlags
This mask has every unused bit set.


SpeechWordPronounceable (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechWordPronounceable Enum

The SpeechWordPronounceable enumeration lists the possible return values from the IsPronounceable method of the ISpeechRecoGrammar interface.

Definition

Enum SpeechWordPronounceable
    SWPUnknownWordUnpronounceable = 0
    SWPUnknownWordPronounceable = 1
    SWPKnownWordPronounceable = 2
End Enum

Elements

SWPUnknownWordUnpronounceable
The word is not pronounceable by the SR engine, and is not located in the lexicon and/or the engine's dictionary.
SWPUnknownWordPronounceable
The word is pronounceable by the SR engine, but is not located in the lexicon and/or the engine's dictionary.
SWPKnownWordPronounceable
The word is pronounceable by the SR engine, and is located in the lexicon and/or the engine's dictionary.


SpeechWordType (Microsoft Speech Platform)

 Microsoft Speech Platform

SpeechWordType Enum

The SpeechWordType enumeration lists the change state of a word/pronunciation combination in a lexicon.

The ISpeechLexiconWord.Type property returns a SpeechWordType value.

Definition

Enum SpeechWordType
    SWTAdded = 1
    SWTDeleted = 2
End Enum

Elements

SWTAdded
Indicates that the word has been added to the lexicon.
SWTDeleted
Indicates that the word has been deleted from the lexicon.


ISpeechAudio Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechAudio

The ISpeechAudio automation interface supports the control of real-time audio streams, such as those connected to a live microphone or telephone line.

The Format property and the Read, Write and Seek methods are inherited from the ISpeechBaseStream interface.

Automation Interface Elements

The ISpeechAudio automation interface contains the following elements:

Properties | Description
BufferInfo Property | Returns the audio buffer information as an ISpeechAudioBufferInfo object.
BufferNotifySize Property | Returns the audio stream buffer size information.
DefaultFormat Property | Returns the default audio format as an SpAudioFormat object.
EventHandle Property | Returns a Win32 event handle that applications can use to wait for status changes in the I/O stream.
Format Property | Gets and sets the cached wave format of the audio stream or device.
Status Property | Returns the audio status as an ISpeechAudioStatus object.
Volume Property | Gets and sets the volume level.
Methods | Description
Read Method | Reads data from an audio stream.
Seek Method | Returns the current read position of the audio stream in bytes.
SetState Method | Sets the audio state with a SpeechAudioState constant.
Write Method | Writes data to the audio stream.


ISpeechAudio BufferInfo Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechAudio

BufferInfo Property

The BufferInfo property returns the audio buffer information as an ISpeechAudioBufferInfo object.

Syntax

Set: | (This property is read-only)
Get: | ISpeechAudioBufferInfo = ISpeechAudio.BufferInfo

Parts

ISpeechAudio
The owning object.
ISpeechAudioBufferInfo
Set: (This property is read-only)
Get: An ISpeechAudioBufferInfo object which gets the buffer data.


ISpeechAudio BufferNotifySize Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechAudio

BufferNotifySize Property

The BufferNotifySize property gets and sets the audio stream buffer size information.

This information is used to determine when the event returned by the EventHandle method is set or reset.

Syntax

Set: | ISpeechAudio.BufferNotifySize = Long
Get: | Long = ISpeechAudio.BufferNotifySize

Parts

ISpeechAudio
The owning object.
Long
Set: A Long variable that sets the property.
Get: A Long variable that gets the property.

Remarks

For read streams, the event is set if the audio buffered is greater than or equal to the value set in pcbSize, otherwise the event information is reset.

For write streams, the event is set if the audio buffered is less than the value set in pcbSize, otherwise the event information is reset.


ISpeechAudio DefaultFormat Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechAudio

DefaultFormat Property

The DefaultFormat property returns the default audio format as an SpAudioFormat object.

Syntax

Set: | (This property is read-only)
Get: | SpAudioFormat = ISpeechAudio.DefaultFormat

Parts

ISpeechAudio
The owning object.
SpAudioFormat
Set: (This property is read-only)
Get: A SpAudioFormat that gets the audio format.


ISpeechAudio EventHandle Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechAudio

EventHandle Property

The EventHandle property returns a Win32 event handle that applications can use to wait for status changes in the I/O stream.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechAudio.EventHandle

Parts

ISpeechAudio
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the handle.

Remarks

The handle may use one of the various Win32 wait functions, such as WaitForSingleObject or WaitForMultipleObjects.

For read streams, set the event when there is data available to read and reset it whenever there is no available data. For write streams, set the event when all of the data has been written to the device, and reset it at any time when there is still data available to be played.


ISpeechBaseStream Format Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechBaseStream

Format Property

The Format property gets and sets the cached wave format of the stream as an SpAudioFormat object.

Syntax

Set: | ISpeechBaseStream.Format = SpAudioFormat
Get: | SpAudioFormat = ISpeechBaseStream.Format

Parts

ISpeechBaseStream
The owning object.
SpAudioFormat
Set: An SpAudioFormat object that sets the wave format.
Get: An SpAudioFormat object that gets the wave format.

Example

For an example of the use of the Format property, see the code example in the SpAudioFormat GetWaveFormatEx section.


ISpeechBaseStream Read Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechBaseStream

Read Method

The Read method reads data from a stream object.

The Read method reads text or audio data from the stream into a Variant variable. Data is read from the Seek pointer of the stream until the specified number of bytes has been copied, or the end of the stream has been reached. When the method has completed, it returns the actual number of bytes read and resets the Seek pointer one byte past the last byte read.

ISpeechBaseStream.Read(
     Buffer As Variant,
     NumberOfBytes As Long
) As Long

Parameters

Buffer
Specifies a Variant variable to receive the data.
NumberOfBytes
Specifies the number of bytes of data to attempt to read from the audio stream.

Return Value

A Long variable containing the actual number of bytes read from the stream object.

Example

Use of the Read method is demonstrated in a code example at the end of the ISpeechBaseStream section.


ISpeechBaseStream Seek Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechBaseStream

Seek Method

The Seek method returns the current read position of the stream in bytes.

The Seek method may also move the Seek pointer forward or backward in the stream. The parameter Position, specifies a number of bytes to move the Seek pointer forward in the stream; negative values specify moving the Seek pointer backward. The parameter Origin, specifies the point from which the forward or backward movement will begin. When the method has completed, it returns a Variant variable containing the new Seek pointer.

ISpeechBaseStream.Seek(
     Position As Variant,
     [Origin As SpeechStreamSeekPositionType = SSSPTRelativeToStart]
) As Variant

Parameters

Position
Specifies the number of bytes to move the Seek pointer forward in the stream. Negative values move the pointer backward.
Origin
[Optional] Specifies the Origin. Default value is SSSPTRelativeToStart.

Return Value

A Variant variable containing the new Seek pointer.

Remarks

The following are examples. This statement sets the Seek pointer 23,456 bytes past the start of the stream and returns a Variant containing the new Seek pointer:

    varCurPos = S.Seek(23456, SSSPTRelativeToStart)

This statement moves the Seek pointer forward 23,456 bytes and returns a Variant containing the new Seek pointer:

    varCurPos = S.Seek(23456, SSSPTRelativeToCurrentPosition)

This statement sets the Seek pointer to the end of the stream and returns a Variant containing the new Seek pointer, which in this case is equal to the size of the stream:

    varCurPos = S.Seek(0, SSSPTRelativeToEnd)

Example

Use of the Seek method is demonstrated in a code example at the end of the ISpeechBaseStream section.


ISpeechAudio SetState Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechAudio
Type: Hidden

SetState Method

The SetState method sets the audio state with a SpeechAudioState constant.

ISpeechAudio.SetState(
     State As SpeechAudioState
)

Parameters

State
Specifies a member of the SpeechAudioState enumeration.

Return Value

None.


ISpeechAudio Status Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechAudio

Status Property

The Status property returns the audio status as an ISpeechAudioStatus object.

Syntax

Set: | (This property is read-only)
Get: | ISpeechAudioStatus = ISpeechAudio.Status

Parts

ISpeechAudio
The owning object.
ISpeechAudioStatus
Set: (This property is read-only)
Get: An ISpeechAudioStatus variable that gets the audio status.


ISpeechAudio Volume Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechAudio

Volume Property

The Volume property gets and sets the volume (loudness) level.

The volume level is on a linear scale from zero to 10,000.

Syntax

Set: | ISpeechAudio.Volume = Long
Get: | Long = ISpeechAudio.Volume

Parts

ISpeechAudio
The owning object.
Long
Set: A Long variable that sets the property.
Get: A Long variable that gets the property.


ISpeechBaseStream Write Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechBaseStream

Write Method

The Write method writes data to a stream object.

The Write method writes text or audio data from a Variant variable into the stream, starting at the Seek pointer and writing until all data has been copied. When the method has completed, it returns the number of bytes written, and resets the Seek pointer one byte past the last byte written.

ISpeechBaseStream.Write(
     Buffer As Variant
) As Long

Parameters

Buffer
A Variant variable containing the data to be written.

Return Value

A Long variable indicating the number of bytes written.

Example

Use of the Write method is demonstrated in a code example at the end of the ISpeechBaseStream section.


ISpeechAudioBufferInfo Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechAudioBufferInfo

The ISpeechAudioBufferInfo automation interface defines the audio stream buffer information.

Automation Interface Elements

The ISpeechAudioBufferInfo automation interface contains the following elements:

Properties | Description
BufferSize Property | Gets and sets the size of the audio object's buffer, in milliseconds.
EventBias Property | Gets and sets the amount of time, in milliseconds, by which event notifications precede the actual occurrence of the events.
MinNotification Property | Gets and sets the minimum preferred time, in milliseconds, between the actual time an event notification occurs and the ideal time.


ISpeechAudioBufferInfo BufferSize Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechAudioBufferInfo

BufferSize Property

The BufferSize property gets and sets the size of the audio object's buffer, in milliseconds.

For readable audio objects, this is simply a preferred size because readable objects will automatically expand their buffers to accommodate data. For writable audio objects, this is the amount of audio data that will be buffered before a call to Write will block.

This value must be greater than or equal to 200 milliseconds. A reasonable default is 500ms.

Syntax

Set: | ISpeechAudioBufferInfo.BufferSize = Long
Get: | Long = ISpeechAudioBufferInfo.BufferSize

Parts

ISpeechAudioBufferInfo
The owning object.
Long
Set: A Long variable that sets the buffer size.
Get: A Long variable that gets the buffer size.


ISpeechAudioBufferInfo EventBias Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechAudioBufferInfo

EventBias Property

The EventBias property gets and sets the amount of time, in milliseconds, by which event notifications precede the actual occurrence of the events.

For example, setting a value of 100 for the event bias would cause all events to be notified 100 milliseconds prior to the audio data being played. This can be useful for applications needing time to animate mouths for TTS voices.

Syntax

Set: | ISpeechAudioBufferInfo.EventBias = Long
Get: | Long = ISpeechAudioBufferInfo.EventBias

Parts

ISpeechAudioBufferInfo
The owning object.
Long
Set: A Long variable that sets the property.
Get: A Long variable that gets the property.


ISpeechAudioBufferInfo MinNotification Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechAudioBufferInfo

MinNotification Property

The MinNotification property gets and sets the minimum preferred time, in milliseconds, between the actual time an event notification occurs and the ideal time.

More CPU resources are needed when the amount of time is shorter; however, the event notifications are more timely. This value must be greater than zero and no more than one quarter the size of the Buffersize property.

Syntax

Set: | ISpeechAudioBufferInfo.MinNotification = Long
Get: | Long = ISpeechAudioBufferInfo.MinNotification

Parts

ISpeechAudioBufferInfo
The owning object.
Long
Set: A Long variable that sets the property.
Get: A Long variable that gets the property.


ISpeechAudioStatus Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechAudioStatus

The ISpeechAudioStatus automation interface provides control over the operation of real-time audio streams.

It is intended for use when the audio input or output source is not a standard Windows multimedia device. An audio stream connected to a microphone or a telephone line would be a typical use.

Automation Interface Elements

The ISpeechAudioStatus automation interface contains the following elements:

Properties | Description
CurrentDevicePosition Property | Returns the current read or write position of the stream or device in bytes.
CurrentSeekPosition Property | Returns the current seek position in the stream or device in bytes.
FreeBufferSpace Property | Returns the size of the free space in the stream or device in bytes.
NonBlockingIO Property | Returns the amount of data which can be read from or written to the stream or device without blocking.
State Property | Returns the state of the audio stream or device.


ISpeechAudioStatus CurrentDevicePosition Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechAudioStatus

CurrentDevicePosition Property

The CurrentDevicePosition property returns the current read or write position of the stream or device in bytes.

This is the position in the stream where the device is currently reading or writing. For readable streams, this value will always be greater than or equal to the CurrentSeekPosition property. For writable streams, this value will always be less than or equal to the CurrentSeekPosition property.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechAudioStatus.CurrentDevicePosition

Parts

ISpeechAudioStatus
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant variable returning the position.


ISpeechAudioStatus CurrentSeekPosition Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechAudioStatus

CurrentSeekPosition Property

The CurrentSeekPosition property returns the current seek position in the audio stream or device in bytes.

This is the position in the stream where the next read or write will be performed.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechAudioStatus.CurrentSeekPosition

Parts

ISpeechAudioStatus
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant variable returning the position.


ISpeechAudioStatus FreeBufferSpace Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechAudioStatus

FreeBufferSpace Property

The FreeBufferSpace property returns the size of the free space in the stream or device in bytes.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechAudioStatus.FreeBufferSpace

Parts

ISpeechAudioStatus
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the size.


ISpeechAudioStatus NonBlockingIO Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechAudioStatus

NonBlockingIO Property

The NonBlockingIO property returns the amount of data which can be read from or written to the stream or device without blocking.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechAudioStatus.NonBlockingIO

Parts

ISpeechAudioStatus
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the count in bytes.


ISpeechAudioStatus State Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechAudioStatus

State Property

The State property returns the state of the audio stream or device.

Syntax

Set: | (This property is read-only)
Get: | SpeechAudioState = ISpeechAudioStatus.State

Parts

ISpeechAudioStatus
The owning object.
SpeechAudioState
Set: (This property is read-only)
Get: A SpeechAudioState object returning the state of the stream or device.


ISpeechBaseStream Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechBaseStream

The ISpeechBaseStream automation interface defines properties and methods for manipulating data streams.

ISpeechBaseStream objects normally contain audio data, but may also be used for text data.

The Read, Write and Seek methods maintain a pointer referred to as the Seek pointer. The Read and Write methods begin reading or writing at the Seek pointer, and reset the Seek pointer one byte past the last byte read or written. The Seek method returns the current pointer, and can also move the Seek pointer forward or backward in the stream, starting from the Seek pointer, or relative to the beginning or the end of the stream.

Use of the Read, Write and Seek methods are demonstrated in a code example at the end of the ISpeechBaseStream section.

The ISpeechBaseStream is not an object in its own right, but is implemented by other objects, such as SpFileStream and SpMemoryStream. SAPI does not call ISpeechBaseStream methods, but uses the underlying COM interfaces. For this reason, a custom object cannot be created using the ISpeechBaseStream interface.

Automation Interface Elements

The ISpeechBaseStream automation interface contains the following elements:

Properties | Description
Format Property | Gets and sets the cached wave format of the stream as an SpAudioFormat object.
Methods | Description
Read Method | Reads data from the audio stream.
Seek Method | Returns the current read position of the audio stream in bytes.
Write Method | Writes data to the audio stream.


ISpeechBaseStream Code Example (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechBaseStream

Example

The following Visual Basic form code demonstrates the use of the ISpeechBaseStream methods Read, Write and Seek. These ISpeechBaseStream methods are inherited by SpCustomStream, SpFileStream and SpMemoryStream. This example uses SpFileStream, but the methods work the same in all three objects.

To run this code, create a form with the following controls:

  • Two command buttons called Command1 and Command2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object and two SpFileStream objects. The Command1_Click procedure speaks the words "one," "point," "five," and "SAPI" into the first file stream, using the Seek method to find the ending byte position of each word. It then reads the audio data for each word separately, and writes a new stream with the order of the words reversed. The Command2_Click procedure plays back the two files created by Command1.

Option Explicit

Const FILENAME1 = "c:\First.wav"
Const FILENAME2 = "c:\Second.wav"

Dim V As SpeechLib.SpVoice
Dim S1 As SpeechLib.SpFileStream
Dim S2 As SpeechLib.SpFileStream

Private Sub Command1_Click()

    Dim varT(3) As Variant      'text to be spoken
    Dim varP(3) As Variant      'positions in output stream
    Dim varD(3) As Variant      'audio data chunks
    Dim varStart As Variant
    Dim ii As Integer

    On Error GoTo EH

    varT(0) = "one": varT(1) = "point": varT(2) = "five": varT(3) = "SAPI"

    'Create WAV file of "one point five SAPI"
    'Speak the words into a single filestream object,
    'and remember the end-of-stream position of each word.

    S1.Open FILENAME1, SSFMCreateForWrite
    Set V.AudioOutputStream = S1
    For ii = 0 To UBound(varT)
        V.Speak varT(ii)
        varP(ii) = S1.Seek(0, SSSPTRelativeToCurrentPosition)
    Next ii
    S1.Close

    'Read the words from the first file into the variant array;
    'Write them back into the second file in reverse order.

    S1.Open FILENAME1, SSFMOpenForRead
    S2.Open FILENAME2, SSFMCreateForWrite

    varStart = 0
    For ii = 0 To UBound(varT)
        S1.Read varD(ii), varP(ii) - varStart
        varStart = varP(ii)
    Next ii

    For ii = UBound(varT) To 0 Step -1
        S2.Write varD(ii)
    Next ii

    S2.Close
    S1.Close

    'After using AudioOutputStream, reset voice AudioOutput property
    Set V.AudioOutput = V.GetAudioOutputs("").Item(0)

    Command1.Enabled = False
    Command2.Enabled = True

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH

    S1.Open FILENAME1, SSFMOpenForRead
    S2.Open FILENAME2, SSFMOpenForRead

    'Use first male voice to announce the results
    Set V.Voice = V.GetVoices("gender=male").Item(0)

    V.Speak "This is the first sound file", SVSFlagsAsync
    V.SpeakStream S1, SVSFlagsAsync

    V.Speak "This is the second sound file", SVSFlagsAsync
    V.SpeakStream S2, SVSFlagsAsync

    Do
        DoEvents
    Loop Until V.WaitUntilDone(1)

    S1.Close
    S2.Close

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Set V = New SpeechLib.SpVoice
    Set S1 = New SpFileStream       'Create stream1
    Set S2 = New SpFileStream       'Create stream2
    Command2.Enabled = False

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechDataKey Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechDataKey

The ISpeechDataKey automation interface provides read and write access to the speech configuration database.

The Speech configuration database contains folders which represent the resources on a computer which are used by SAPI 5.1 and later SR and TTS. These folders are organized into resource categories, such as voices, lexicons, and audio input devices. The SpObjectTokenCategory object provides access to a category of resources, and the SpObjectToken object provides access to a single resource.

An ISpeechDataKey object is typically created by the DataKey property of an SpObjectToken or the GetDataKey method of an SpObjectTokenCategory object. Such an ISpeechDataKey object provides read and write access to the database folder represented by its parent token or token category object. Further ISpeechDataKey objects can be created by CreateKey and OpenKey calls on existing ISpeechDataKey objects. ISpeechDataKey methods can create, delete and enumerate subfolders and values in the database folder represented by an ISpeechDataKey object.

Automation Interface Elements

The ISpeechDataKey automation interface contains the following elements:

Methods | Description
CreateKey Method | Creates the specified subkey within the data key.
DeleteKey Method | Deletes the specified subkey from the data key.
DeleteValue Method | Deletes the specified value from the data key.
EnumKeys Method | Returns the name of one subkey of the data key, specified by its index.
EnumValues Method | Returns the name of one value of the data key, specified by its index.
GetBinaryValue Method | Gets the specified binary value from the data key.
GetLongValue Method | Gets the specified Long value from the data key.
GetStringValue Method | Gets the specified String value from the data key.
OpenKey Method | Opens the specified subkey of the data key as another data key object.
SetBinaryValue Method | Sets the specified binary value in the data key.
SetLongValue Method | Sets the specified Long value in the data key.
SetStringValue Method | Sets the specified String value in the data key.


ISpeechDataKey CreateKey Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

CreateKey Method

The CreateKey method creates the specified subkey within the data key.

ISpeechDataKey.CreateKey(
     SubKeyName As String
) As ISpeechDataKey

Parameters

SubKeyName
The name of the subkey.

Return Value

An ISpeechDataKey object representing the new subkey.

For an example of the use of the CreateKey method, see the code example in the code example at the end of this section.


ISpeechDataKey DeleteKey Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

DeleteKey Method

The DeleteKey method deletes the specified subkey from the data key.

ISpeechDataKey.DeleteKey(
     SubKeyName As String
)

Parameters

SubKeyName
The name of the subkey.

Return Value

None.

For an example of the use of the DeleteKey method, see the code example in the code example at the end of this section.


ISpeechDataKey DeleteValue Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

DeleteValue Method

The DeleteValue method deletes the specified value from the data key.

ISpeechDataKey.DeleteValue(
     ValueName As String
)

Parameters

ValueName
The name of the value.

Return Value

None.

Example

For an example of the use of the DeleteValue method, see the code example in the EnumKeys section.


ISpeechDataKey EnumKeys Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

EnumKeys Method

The EnumKeys method returns the name of one subkey of the data key, specified by its index.

The starting index is zero. A count of subkeys or an enumeration of subkey names can be performed by calling this method repetitively, starting with an index of zero, and increasing the index until all items are enumerated. This is indicated by an SPERR_NO_MORE_ITEMS error.

ISpeechDataKey.EnumKeys(
     Index As Long
) As String

Parameters

Index
The index of the subkey to be returned.

Return Value

A String variable containing the name of the subkey.

Example

The following Visual Basic form code demonstrates several ISpeechDataKey methods, including OpenKey, EnumKeys, SetStringValue, and DeleteValue. It also demonstrates the creation and deletion of custom object token attributes, and the selection of tokens by these custom attributes. A custom attribute called "SenseOfHumor" is created for each voice token. This attribute name is intentionally unrelated to any actual characteristics of a voice or a voice token; it is intended to be obviously meaningless and easily distinguishable from installed voice attributes. To run this code, create a form with the following controls:

  • A list box called List1
  • Two command buttons called Command1 and Command2

Copy the code below and paste it into the Declarations section of the form.

The Form_Load procedure creates an SpObjectTokenCategory object and sets it to the category of voices in the speech configuration database.

The Command1 procedure sets one data key object to the category of voices, and another data key object to the Tokens subfolder. It then enumerates the voice tokens contained in Tokens and writes a value called SenseOfHumor in the Attributes subfolder of each voice token. The values written are "0" and "1" alternately, so that every second voice has a non-zero SenseOfHumor attribute value. Finally, the procedure calls a subroutine which uses the SenseOfHumor attribute in a GetVoices call.

The Command2 procedure enumerates the voice token "Attributes" subfolders and removes all "SenseOfHumor" attributes. It then calls the subroutine which uses "SenseOfHumor" attributes in a GetVoices call after these attributes have been removed.

Option Explicit

Dim C As SpeechLib.SpObjectTokenCategory    'one object token category
Dim T As SpeechLib.SpObjectToken            'one object token
Dim V As SpeechLib.SpVoice                  'Voice used for enumeration

Dim Kc As SpeechLib.ISpeechDataKey          'DataKey of the category
Dim Kf As SpeechLib.ISpeechDataKey          'DataKey of its tokens folder
Dim Kt As SpeechLib.ISpeechDataKey          'DataKey of one token

Const SPERR_NO_MORE_ITEMS = &H80045039

Private Sub Command1_Click()
    Dim nn As Long
    Dim strKey As String, strValue As String

    Set Kc = C.GetDataKey                   'Get DataKey of voice category
    Set Kf = Kc.OpenKey("Tokens")           'Get DataKey of its "Tokens" subfolder
    nn = 0

    On Error Resume Next
    Do
        strKey = Kf.EnumKeys(nn)
        If Err.Number = SPERR_NO_MORE_ITEMS Then Exit Do

        'Write an attribute for each voice:
        'Attribute "SenseOfHumor" will be true for alternating voices
        Set Kt = Kf.OpenKey(strKey)         'Kt = the DataKey of the voice token
        Set Kt = Kt.OpenKey("Attributes")   'Kt = the DataKey of voice\Attributes

        If nn Mod 2 Then strValue = "1" Else strValue = "0"
        Call Kt.SetStringValue("SenseOfHumor", strValue)
        nn = nn + 1
    Loop
    Err.Clear
    On Error GoTo 0

    Call TestAttributes     'Select voices using this attribute

End Sub

Private Sub Command2_Click()
    Dim nn As Long
    Dim strKey As String

    Set Kc = C.GetDataKey                   'Get DataKey of voice category
    Set Kf = Kc.OpenKey("Tokens")           'Get DataKey of its "Tokens" subfolder

    On Error Resume Next
    Do
        strKey = Kf.EnumKeys(nn)
        If Err.Number = SPERR_NO_MORE_ITEMS Then Exit Do
        Set Kt = Kf.OpenKey(strKey)         'Kt = the DataKey of the voice token
        Set Kt = Kt.OpenKey("Attributes")   'Kt = the DataKey of voice\Attributes
        Call Kt.DeleteValue("SenseOfHumor")
        nn = nn + 1

    Loop
    Err.Clear
    On Error GoTo 0

    Call TestAttributes     'Select voices using this attribute

End Sub

Private Sub Form_Load()
    On Error GoTo EH

    'Create new token object, and set its ID to voice tokens

    Set C = New SpObjectTokenCategory
    C.SetId SpeechCategoryVoices

    Set V = New SpVoice

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub TestAttributes()
    On Error GoTo EH

    List1.Clear
    List1.AddItem "Voices with a sense of humor"

    For Each T In V.GetVoices("senseofhumor=1")
        List1.AddItem "   " & T.GetDescription
    Next

    List1.AddItem ""
    List1.AddItem "Voices with no sense of humor"

    'When the "SenseOfHumor" attribute is not present,
    'the selection "SenseOfHumor!=1" shows all voices,
    'bau the selection "SenseOfHumor=0" would show no voices.

    For Each T In V.GetVoices("senseofhumor!=1")
        List1.AddItem "   " & T.GetDescription
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechDataKey EnumValues Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

EnumValues Method

The EnumValues method returns the name of one value of the data key, specified by its index.

The starting index is zero. A count of values or an enumeration of value names can be performed by calling this method repetitively, starting with an index of zero, and increasing the index until all items are enumerated.

ISpeechDataKey.EnumValues(
     Index As Long
) As String

Parameters

Index
The index of the value to be returned.

Return Value

A String variable containing the name of the value.

For an example of the use of the EnumValues method, see the code example in the code example at the end of this section.


ISpeechDataKey GetBinaryValue Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

GetBinaryValue Method

The GetBinaryValue method gets the specified binary value from the data key.

ISpeechDataKey.GetBinaryValue(
     ValueName As String
) As Variant

Parameters

ValueName
The name of the Value.

Return Value

A Variant variable.

For an example of the use of the GetBinaryValue method, see the code example in the code example at the end of this section.


ISpeechDataKey GetLongValue Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

GetLongValue Method

The GetLongValue method gets the specified Long value from the data key.

ISpeechDataKey.GetLongValue(
     ValueName As String
) As Long

Parameters

ValueName
The name of the Value.

Return Value

A Long variable.

For an example of the use of the GetLongValue method, see the code example in the code example at the end of this section.


ISpeechDataKey GetStringValue Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

GetStringValue Method

The GetStringValue method gets the specified String value from the data key.

ISpeechDataKey.GetStringValue(
     ValueName As String
) As String

Parameters

ValueName
The name of the Value.

Return Value

A String variable.

For an example of the use of the GetStringValue method, see the code example in the code example at the end of this section.


ISpeechDataKey OpenKey Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

OpenKey Method

The OpenKey method opens the specified subkey of the data key as another data key object.

ISpeechDataKey.OpenKey(
     SubKeyName As String
) As ISpeechDataKey

Parameters

SubKeyName
Name of the subkey.

Return Value

An ISpeechDataKey variable representing the subkey.

Example

For an example of the use of the OpenKey method, see the code example in the EnumKeys section.


ISpeechDataKey SetBinaryValue Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

SetBinaryValue Method

The SetBinaryValue method sets the specified binary value in the data key.

ISpeechDataKey.SetBinaryValue(
     ValueName As String,
     Value As Variant
)

Parameters

ValueName
The name of the value.
Value
The binary data value.

Return Value

None.

For an example of the use of the SetBinaryValue method, see the code example in the code example at the end of this section.


ISpeechDataKey SetLongValue Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

SetLongValue Method

The SetLongValue method sets the specified Long value in the data key.

ISpeechDataKey.SetLongValue(
     ValueName As String,
     Value As Long
)

Parameters

ValueName
The name of the value.
Value
The Long data value.

Return Value

None.

For an example of the use of the SetLongValue method, see the code example in the code example at the end of this section.


ISpeechDataKey SetStringValue Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

SetStringValue Method

The SetStringValue method sets the specified String value in the data key.

ISpeechDataKey.SetStringValue(
     ValueName As String,
     Value As String
)

Parameters

ValueName
The name of the value.
Value
The String data value.

Return Value

None.

Example

For an example of the use of the SetStringValue method, see the code example in the EnumKeys section.


ISpeechDataKey Code Example (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechDataKey

Code Example

The following Visual Basic form code demonstrates the methods of the ISpeechDataKey interface. To run this code, create a form containing the following controls:

  • Three command buttons, called Command1, Command2, and Command3

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object and gets its object token.

The Command1 procedure creates a data key, called K1, from the voice's token. This key provides data access to the token's folder in the Speech configuration database. The procedure then uses that datakey's CreateKey method to create a subfolder called "ISpeechDataKey" within its folder; the new datakey K2, which provides access to the new subfolder, is returned by the CreateKey method. Next, the procedure uses datakey K2 to create a subfolder called "Test1" within the "ISpeechDataKey" folder. The CreateKey method returns datakey K3, which accesses the folder. The procedure then creates a default value, a string value, a long value and a binary value within the "Test1" folder. Finally, the procedure creates a subfolder called "Test2" within the "ISpeechDataKey" folder, and writes the same four values into it.

The Command2 procedure opens the "ISpeechDataKey" subfolder, and enumerates the subfolders "Test1" and "Test2" and enumerates the values with each subfolder.

The Command3 procedure enumerates and deletes the values within the "Test1" and "Test2" subfolders, deletes these folders, and finally deletes the "ISpeechDataKey" folder.

Option Explicit

Dim V As SpeechLib.SpVoice
Dim T As SpeechLib.SpObjectToken

Dim K1 As SpeechLib.ISpeechDataKey
Dim K2 As SpeechLib.ISpeechDataKey
Dim K3 As SpeechLib.ISpeechDataKey

Const SPERR_NO_MORE_ITEMS = &H80045039

Private Sub Command1_Click()
    On Error GoTo EH

    'Create subkey voice\ISpeechDataKey
    Set K1 = T.DataKey
    Set K2 = K1.CreateKey("ISpeechDataKey")

    'Create subkey voice\ISpeechDataKey\Test1
    Set K3 = K2.CreateKey("Test1")

    Call K3.SetStringValue("", "The default value")
    Call K3.SetStringValue("Description", "A test string value")
    Call K3.SetLongValue("Long_10K", 10000)
    Call K3.SetBinaryValue("Binary_100K", 100000)

    'Create subkey voice\ISpeechDataKey\Test2
    Set K3 = K2.CreateKey("Test2")

    Call K3.SetStringValue("", "The default value")
    Call K3.SetStringValue("Description", "A test string value")
    Call K3.SetLongValue("Long_10K", 10000)
    Call K3.SetBinaryValue("Binary_100K", 100000)

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    Dim nn As Long, mm As Long
    Dim strKey As String

    Set K1 = T.DataKey
    Debug.Print "Key " & T.GetDescription

    Set K2 = K1.OpenKey("ISpeechDataKey")
    Debug.Print "   Key ISpeechDataKey"

    'Enumerate keys within "ISpeechDataKey"
    nn = 0
    On Error Resume Next
    Do
        strKey = K2.EnumKeys(nn)
        If Err.Number = SPERR_NO_MORE_ITEMS Then Exit Do
        Debug.Print "      Key """ & strKey & """"
        nn = nn + 1

        'Enumerate values within each subkey
        Set K3 = K2.OpenKey(strKey)
        Call EnumerateValues(K3)

    Loop
    Err.Clear
    On Error GoTo 0

End Sub

Private Sub Command3_Click()
    Dim strKey As String, strValue As String

    Set K1 = T.DataKey
    Set K2 = K1.OpenKey("ISpeechDataKey")

    'Enumerate and delete keys loop
    On Error Resume Next
    Do
        strKey = K2.EnumKeys(0)
        If Err.Number = SPERR_NO_MORE_ITEMS Then Exit Do

        'Enumerate and delete values loop
        Set K3 = K2.OpenKey(strKey)
        Do
            strValue = K3.EnumValues(0)
            If Err.Number = 0 Then
                Call K3.DeleteValue(strValue)
            End If
        Loop Until Err.Number = SPERR_NO_MORE_ITEMS
        Err.Clear

        Call K2.DeleteKey(strKey)
    Loop

    Call K1.DeleteKey("ISpeechDataKey")

End Sub

Private Sub Form_Load()
    On Error GoTo EH

    'T is object token for first available voice
    Set V = New SpVoice
    Set T = V.GetVoices().Item(0)

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub EnumerateValues(DK As ISpeechDataKey)
    Dim nn As Long, strValue As String
    Dim varVariant As Variant
    Dim lngLong As Long
    Dim strString As String

    nn = 0
    On Error Resume Next
    Do
        strValue = DK.EnumValues(nn)
        If Err.Number = SPERR_NO_MORE_ITEMS Then Exit Do

        If Left(strValue, 6) = "Binary" Then
            'Binary
            varVariant = DK.GetBinaryValue(strValue)
            strString = Format(varVariant)
        ElseIf Left(strValue, 4) = "Long" Then
            'Long
            lngLong = DK.GetLongValue(strValue)
            strString = Format(lngLong)
        Else
            'String
            strString = DK.GetStringValue(strValue)
        End If

        Debug.Print "         Val """ & strValue & """ = """ & strString & """"
        nn = nn + 1

    Loop
    Err.Clear

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechGrammarRule Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechGrammarRule

The ISpeechGrammarRule automation interface defines the properties and methods of a speech grammar rule.

Automation Interface Elements

The ISpeechGrammarRule automation interface contains the following elements:

Properties | Description
Attributes Property | Returns information about the attributes of a speech grammar rule.
Id Property | Specifies the ID of the speech grammar rule.
InitialState Property | Specifies the initial state of the speech grammar rule.
Name Property | Specifies the name of the speech grammar rule.
Methods | Description
AddResource Method | Adds a string to a speech rule.
AddState Method | Adds a state to a speech rule.
Clear Method | Clears a rule, leaving only its initial state.


ISpeechGrammarRule AddResource Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRule

AddResource Method

The AddResource method adds one or more string name/value pair associated with a rule.

This method is used with an interpreter rule.

ISpeechGrammarRule.AddResource(
     ResourceName As String,
     ResourceValue As String
)

Parameters

ResourceName
Specifies the ResourceName.
ResourceValue
Specifies the ResourceValue.

Return Value

None.


ISpeechGrammarRule AddState Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRule

AddState Method

The AddState method adds a state to a speech rule.

This method can be used with the ISpeechGrammarRuleState methods AddRuleTransition, AddSpecialTransition, or AddWordTransition to modify speech rules programmatically.

ISpeechGrammarRule.AddState() As ISpeechGrammarRuleState

Parameters

None.

Return Value

An ISpeechGrammarRuleState object.


ISpeechGrammarRule Attributes property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRule

Attributes Property

The Attributes property returns information about the attributes of each grammar rule.

This property consists of one or more members of the SpeechRuleAttributes enumeration.

Syntax

Set: | (This property is read-only)
Get: | SpeechRuleAttributes = ISpeechGrammarRule.Attributes

Parts

ISpeechGrammarRule
The owning object.
SpeechRuleAttributes
Set: (This property is read-only)
Get: One or more SpeechRuleAttributes flags representing the attributes of the rule.


ISpeechGrammarRule Clear Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRule

Clear Method

The Clear method clears a rule, leaving only its initial state.

ISpeechGrammarRule.Clear()

Parameters

None.

Return Value

None.


ISpeechGrammarRule Id Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRule

Id Property

The Id property specifies the ID of the speech grammar rule.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechGrammarRule.Id

Parts

ISpeechGrammarRule
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the ID of the rule.


ISpeechGrammarRule InitialState Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRule

InitialState Property

The InitialState property specifies the initial state of the speech grammar rule.

Syntax

Set: | (This property is read-only)
Get: | ISpeechGrammarRuleState = ISpeechGrammarRule.InitialState

Parts

ISpeechGrammarRule
The owning object.
ISpeechGrammarRuleState
Set: (This property is read-only)
Get: An ISpeechGrammarRuleState variable that gets the initial rule state.


ISpeechGrammarRule Name Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRule

Name Property

The Name property specifies the name of the speech grammar rule.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechGrammarRule.Name

Parts

ISpeechGrammarRule
The owning object.
String
Set: (This property is read-only)
Get: A String variable that gets the name of the rule.


ISpeechGrammarRules Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechGrammarRules

The ISpeechGrammarRules automation interface represents a collection of ISpeechGrammarRule objects.

Automation Interface Elements

The ISpeechGrammarRules automation interface contains the following elements:

Properties | Description
Count Property | Returns the count of objects in the collection.
Dynamic Property | Determines whether the grammar rules contained in the collection were created as dynamic.
Methods | Description
Add Method | Creates a new grammar rule in an ISpeechGrammarRules collection.
Commit Method | Compiles the rules in the rule collection.
CommitAndSave Method | Compiles the rules in the rule collection and saves the result.
FindRule Method | Returns a grammar rule, specified by Name or by ID.
Item Method | Returns a member of the collection specified by its index.


ISpeechGrammarRules Add Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRules

Add Method

The Add method creates a new ISpeechGrammarRule object in an ISpeechGrammarRules collection.

RuleName, or RuleId, or both must be specified to identify the rule. If RuleName is specified (not an empty string such as ""), it must be unique within the grammar. If RuleId is specified (a value other than zero), it must be unique within the grammar.

ISpeechGrammarRules.Add(
     RuleName As String,
     Attributes As SpeechRuleAttributes,
     [RuleId As Long = 0]
) As ISpeechGrammarRule

Parameters

RuleName
Specifies the RuleName of the new rule.
Attributes
Specifies the Attributes of the new rule.
RuleId
Specifies the RuleId of the new rule. Default value is zero.

Return Value

The Add method returns the newly-created ISpeechGrammarRule object.


ISpeechGrammarRules Commit Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRules

Commit Method

The Commit method compiles the rules in the rule collection.

ISpeechGrammarRules.Commit()

Parameters

None.

Return Value

None.


ISpeechGrammarRules CommitAndSave Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRules

CommitAndSave Method

The CommitAndSave method compiles the rules in the rule collection and saves the result.

ISpeechGrammarRules.CommitAndSave(
     ErrorText As String
) As Variant

Parameters

ErrorText
The text of any errors that may result from compiling and saving the grammar upon calling the method.

Return Value

The CommitAndSave method returns a Variant variable.


ISpeechGrammarRules Count Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRules

Count Property

The Count property returns the number of ISpeechGrammarRule objects in the ISpeechGrammarRules object.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechGrammarRules.Count

Parts

ISpeechGrammarRules
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the count.

Remarks

The ISpeechGrammarRules object is a collection of ISpeechGrammarRule objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Count property is one of these common properties.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechGrammarRules Dynamic Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRules

Dynamic Property

The Dynamic property determines whether the grammar rules contained in the collection were created as dynamic.

Syntax

Set: | (This property is read-only)
Get: | Boolean = ISpeechGrammarRules.Dynamic

Parts

ISpeechGrammarRules
The owning object.
Boolean
Set: (This property is read-only)
Get: A Boolean variable returning the value of the property.


ISpeechGrammarRules FindRule Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRules

FindRule Method

The FindRule method returns a grammar rule, specified by Name or by ID.

ISpeechGrammarRules.FindRule(
     RuleNameOrId As Variant
) As ISpeechGrammarRule

Parameters

RuleNameOrId
Specifies the RuleNameOrId.

Return Value

The FindRule method returns an ISpeechGrammarRule variable.


ISpeechGrammarRules Item Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRules

Item Method

The Item method returns a member of the ISpeechGrammarRules collection by its index.

ISpeechGrammarRules.Item(
     Index As Long
) As ISpeechGrammarRule

Parameters

Index
Specifies the Index of the rule.

Return Value

The Item method returns an ISpeechGrammarRule object as specified by the Index parameter.

Remarks

The ISpeechGrammarRules object is a collection of ISpeechGrammarRule objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Item method is one of these common methods.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechGrammarRuleState Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechGrammarRuleState

The ISpeechGrammarRuleState automation interface presents the properties and methods of a speech grammar rule state.

Automation Interface Elements

The ISpeechGrammarRuleState automation interface contains the following elements:

Properties | Description
Rule Property | Specifies the rule to which the rule state belongs.
Transitions Property | Specifies the set of transitions out of the rule state.
Methods | Description
AddRuleTransition Method | Adds a rule reference transition from the current rule state to another rule state in the same rule.
AddSpecialTransition Method | Adds a special transition from the current rule state to another rule state in the same rule
AddWordTransition Method | Adds a word transition from this rule state to another rule state in the same rule


ISpeechGrammarRuleState AddRuleTransition Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRuleState

AddRuleTransition Method

The AddRuleTransition method adds a rule reference transition from the current rule state to another rule state in the same rule.

When the word sequence accepted by the referenced rule is spoken, the rule can go from the current state to the DestinationState. A rule accepts a word sequence when the rule can go from the initial state to the end state using the word sequence.

ISpeechGrammarRuleState.AddRuleTransition(
     DestinationState As ISpeechGrammarRuleState,
     Rule As ISpeechGrammarRule,
     [PropertyName As String = ""],
     [PropertyId As Long = 0],
     [PropertyValue As Variant = 0],
     [Weight As Single = 1.0]
)

Parameters

DestinationState
Specifies the DestinationState, or the state where the transition ends. DestinationState of Nothing means the end state of the rule.
Rule
Specifies the Rule.
PropertyName
[Optional] Specifies the PropertyName.
PropertyId
[Optional] Specifies the PropertyId.
PropertyValue
[Optional] Specifies the PropertyValue.
Weight
[Optional] Specifies the Weight.

Return Value

None.


ISpeechGrammarRuleState AddSpecialTransition Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRuleState

AddSpecialTransition Method

The AddSpecialTransition method adds a special transition from the current rule state to another rule state in the same rule.

When the word sequence accepted by the special transition is spoken, the rule can go from the current state to the DestinationState. A rule accepts a word sequence when the rule can go from the initial state to the end state using the word sequence.

Special transitions may not be supported by all speech engines. There are three types of special transitions:

  • Wildcard: A wildcard tag is used to accept words not critical to a rule's intent and allows any word or words to be spoken for that position.
  • Dictation: A dictation tag allows any word or words to be spoken for that position and each word is returned by the SR engine in the phrase element list. Unlike the wildcard, the word or words are considered important to the rule. See Grammar Format Tags: Special Characters for more information about the wildcard and dictation tags.
  • Textbuffer: A Textbuffer accepts the word sequence and can be set later using ISpeechRecoGrammar.SetWordSequenceData and ISpeechRecoGrammar.SetTextSelection.

ISpeechGrammarRuleState.AddSpecialTransition(
     DestinationState As ISpeechGrammarRuleState,
     Type As SpeechSpecialTransitionType,
     [PropertyName As String = ""],
     [PropertyId As Long = 0],
     [PropertyValue As Variant = 0],
     [Weight As Single = 1.0]
)

Parameters

DestinationState
Specifies the DestinationState, or the state where the transition ends. DestinationState of Nothing means the end state of the rule.
Type
Specifies the Type.
PropertyName
[Optional] Specifies the PropertyName.
PropertyId
[Optional] Specifies the PropertyId.
PropertyValue
[Optional] Specifies the PropertyValue.
Weight
[Optional] Specifies the Weight.

Return Value

None.


ISpeechGrammarRuleState AddWordTransition Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRuleState

AddWordTransition Method

The AddWordTransition method adds a word transition from this rule state to another rule state in the same rule.

When the word sequence specified by the word transition is spoken, the rule can go from this state to the DestinationState. A rule accepts a word sequence when the rule can go from the initial state to the end state using the word sequence.

ISpeechGrammarRuleState.AddWordTransition(
     DestinationState As ISpeechGrammarRuleState,
     Words As String,
     [Separators As String = " "],
     [Type As SpeechGrammarWordType = SGLexical],
     [PropertyName As String = ""],
     [PropertyId As Long = 0],
     [PropertyValue As Variant = 0],
     [Weight As Single = 1.0]
)

Parameters

DestinationState
Specifies the DestinationState, or the state where the transition ends. DestinationState of Nothing means the end state of the rule.
Words
Specifies the Words.
Separators
[Optional] Specifies the Separators.
PropertyName
[Optional] Specifies the PropertyName.
PropertyId
[Optional] Specifies the PropertyId.
PropertyValue
[Optional] Specifies the PropertyValue.
Weight
[Optional] Specifies the Weight.

Return Value

None.


ISpeechGrammarRuleState Rule Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRuleState

Rule Property

The Rule property specifies the rule to which the rule state belongs.

Syntax

Set: | (This property is read-only)
Get: | ISpeechGrammarRule = ISpeechGrammarRuleState.Rule

Parts

ISpeechGrammarRuleState
The owning object.
ISpeechGrammarRule
Set: (This property is read-only)
Get: An ISpeechGrammarRule variable that gets the property.


ISpeechGrammarRuleState Transitions Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRuleState

Transitions Property

The Transitions property specifies the set of transitions out of the rule state.

Syntax

Set: | (This property is read-only)
Get: | ISpeechGrammarRuleStateTransitions = ISpeechGrammarRuleState.Transitions

Parts

ISpeechGrammarRuleState
The owning object.
ISpeechGrammarRuleStateTransitions
Set: (This property is read-only)
Get: An ISpeechGrammarRuleStateTransitions object that gets the property.


ISpeechGrammarRuleStateTransition Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechGrammarRuleStateTransition

The ISpeechGrammarRuleStateTransition automation interface returns data about a transition from one rule state to another, or from a rule state to the end of a rule.

Automation Interface Elements

The ISpeechGrammarRuleStateTransition automation interface contains the following elements:

Properties | Description
NextState Property | Specifies the rule state to which the transition leads.
PropertyId Property | Specifies the Id of a property contained in a semantic tag.
PropertyName Property | Specifies the name of a property contained in a semantic tag.
PropertyValue Property | Returns the value of a property contained in a semantic tag.
Rule Property | Specifies the speech rule to which the transition leads.
Text Property | Returns the recognition text associated with a transition.
Type Property | Specifies the type of the transition.
Weight Property | Assigns the transition a weight relative to its sibling transitions.


ISpeechGrammarRuleStateTransition NextState Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRuleStateTransition

NextState Property

The NextState property specifies the rule state to which the transition leads.

Syntax

Set: | (This property is read-only)
Get: | ISpeechGrammarRuleState = ISpeechGrammarRuleStateTransition.NextState

Parts

ISpeechGrammarRuleStateTransition
The owning object.
ISpeechGrammarRuleState
Set: (This property is read-only)
Get: An ISpeechGrammarRuleState variable that gets the property.


ISpeechGrammarRuleStateTransition PropertyId Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRuleStateTransition

PropertyId Property

The PropertyId property specifies the ID of a property contained in a semantic tag.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechGrammarRuleStateTransition.PropertyId

Parts

ISpeechGrammarRuleStateTransition
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the property.

Remarks

Semantic tags provide a way for grammar designers to put semantic information about a transition into the grammar. The PropertyId, PropertyName and PropertyValue properties provide access to that information at run time.


ISpeechGrammarRuleStateTransition PropertyName Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRuleStateTransition

PropertyName Property

The PropertyName property specifies the name of a property contained in a semantic tag.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechGrammarRuleStateTransition.PropertyName

Parts

ISpeechGrammarRuleStateTransition
The owning object.
String
Set: (This property is read-only)
Get: A String variable that gets the property.

Remarks

Semantic tags provide a way for grammar designers to put semantic information about a transition into the grammar. The PropertyId, PropertyName and PropertyValue properties provide access to that information at run time.


ISpeechGrammarRuleStateTransition PropertyValue Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRuleStateTransition

PropertyValue Property

The PropertyValue property returns the value of a property contained in a semantic tag.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechGrammarRuleStateTransition.PropertyValue

Parts

ISpeechGrammarRuleStateTransition
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant variable returning the value of the semantic tag property.

Remarks

Semantic tags provide a way for grammar designers to put semantic information about a transition into the grammar. The PropertyId, PropertyName and PropertyValue properties provide access to that information at run time.


ISpeechGrammarRuleStateTransition Rule Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRuleStateTransition

Rule Property

The Rule property specifies the speech rule to which the transition leads.

Syntax

Set: | (This property is read-only)
Get: | ISpeechGrammarRule = ISpeechGrammarRuleStateTransition.Rule

Parts

ISpeechGrammarRuleStateTransition
The owning object.
ISpeechGrammarRule
Set: (This property is read-only)
Get: An ISpeechGrammarRule variable that gets the property.


ISpeechGrammarRuleStateTransition Text Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRuleStateTransition

Text Property

The Text property returns the recognition text associated with a transition. This is text which is added to the recognition results when the transition is processed.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechGrammarRuleStateTransition.Text

Parts

ISpeechGrammarRuleStateTransition
The owning object.
String
Set: (This property is read-only)
Get: A String variable that gets the property.


ISpeechGrammarRuleStateTransition Type Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRuleStateTransition

Type Property

The Type property specifies the type of the transition. The SpeechGrammarRuleStateTransitionType enumeration contains the possible transition type values.

Syntax

Set: | (This property is read-only)
Get: | SpeechGrammarRuleStateTransitionType = ISpeechGrammarRuleStateTransition.Type

Parts

ISpeechGrammarRuleStateTransition
The owning object.
SpeechGrammarRuleStateTransitionType
Set: (This property is read-only)
Get: A SpeechGrammarRuleStateTransitionType constant returning the transition type.


ISpeechGrammarRuleStateTransition Weight Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRuleStateTransition

Weight Property

The Weight property assigns the transition a weight relative to its sibling transitions.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechGrammarRuleStateTransition.Weight

Parts

ISpeechGrammarRuleStateTransition
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant variable that gets the property.

Remarks

Recognition proceeds by means of transitions from one rule state to another. Each rule state has a collection of transitions, which represent the possible recognition paths to subsequent rule states.

In the absence of weighting, each transition is considered equally probable. For example, in a rule state with five transitions, each has a 20 percent probability of being followed. The Weight property enables grammar designers to specify a transition as more probable, or less probable, than its sibling transitions.

The weight property for a transition is a fractional number with a range of zero to one, and the sum of the weights of a rule state's transition should be one.


ISpeechGrammarRuleStateTransitions Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechGrammarRuleStateTransitions

The ISpeechGrammarRuleStateTransitions automation interface represents a collection of ISpeechGrammarRuleStateTransition objects.

Automation Interface Elements

The ISpeechGrammarRuleStateTransitions automation interface contains the following elements:

Properties | Description
Count Property | Returns the number of objects in the collection.
Methods | Description
Item Method | Returns a member of the collection specified by its index.


ISpeechGrammarRuleStateTransitions Count Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechGrammarRuleStateTransitions

Count Property

The Count property returns the number of ISpeechGrammarRuleStateTransition objects in the ISpeechGrammarRuleStateTransitions object.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechGrammarRuleStateTransitions.Count

Parts

ISpeechGrammarRuleStateTransitions
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the Count property.

Remarks

The ISpeechGrammarRuleStateTransitions object is a collection of ISpeechGrammarRuleStateTransition objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all objects in the collection. The Count property is one of these common properties.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechGrammarRuleStateTransitions Item Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechGrammarRuleStateTransitions

Item Method

The Item method returns a member of the ISpeechGrammarRuleStateTransitions collection by its index.

ISpeechGrammarRuleStateTransitions.Item(
     Index As Long
) As ISpeechGrammarRuleStateTransition

Parameters

Index
Specifies the Index of the member to be returned.

Return Value

The Item method returns an ISpeechGrammarRuleStateTransition variable.

Remarks

The ISpeechGrammarRuleStateTransitions object is a collection of ISpeechGrammarRuleStateTransition objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Item method is one of these common methods.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechLexiconPronunciation Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechLexiconPronunciation

The ISpeechLexiconPronunciation automation interface provides access to the pronunciations of a speech lexicon word.

Automation Interface Elements

The ISpeechLexiconPronunciation automation interface contains the following elements:

Properties | Description
LangId Property | Returns the language id of the pronunciation.
PartOfSpeech Property | Returns a word's part of speech.
PhoneIds Property | Returns the pronunciation of a word as a Variant array of numeric phone ids.
Symbolic Property | Returns the pronunciation of a word as a string of phone symbols.
Type Property | Returns the type of the pronunciation.


ISpeechLexiconPronunciation LangId Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechLexiconPronunciation

LangId Property

The LangId property returns the language ID of the pronunciation.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechLexiconPronunciation.LangId

Parts

ISpeechLexiconPronunciation
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the LangId.


ISpeechLexiconPronunciation PartOfSpeech Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechLexiconPronunciation

PartOfSpeech Property

The PartOfSpeech property returns a word's part of speech.

Syntax

Set: | (This property is read-only)
Get: | SpeechPartOfSpeech = ISpeechLexiconPronunciation.PartOfSpeech

Parts

ISpeechLexiconPronunciation
The owning object.
SpeechPartOfSpeech
Set: (This property is read-only)
Get: A SpeechPartOfSpeech object returning the value of the property.


ISpeechLexiconPronunciation PhoneIds Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechLexiconPronunciation

PhoneIds Property

The PhoneIds property returns the pronunciation of a word as a Variant array of numeric phone ids.

Pronunciations represented in PhoneIds can be converted to phones with the IdToPhone method of theSpPhoneConverter object.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechLexiconPronunciation.PhoneIds

Parts

ISpeechLexiconPronunciation
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant variable returning the value of the property.

Example

The following code example creates a lexicon, adds a pronunciation to it, retrieves the pronunciation object, and formats the values of the PhoneIds as a string. The resulting string is " 46 12 33".

Option Explicit

Private Sub Form_Load()

    On Error GoTo EH

    ' Declare identifiers:
    Dim MyLex As SpeechLib.SpLexicon
    Dim MyLexPronunciation As SpeechLib.ISpeechLexiconPronunciation
    Dim MyLexPronunciations As SpeechLib.ISpeechLexiconPronunciations
    Dim ID As Integer
    Dim PhoneIDs As Variant     'A Variant array of numeric values
    Dim TmpStr As String        'Display the PhoneId values

    Set MyLex = New SpeechLib.SpLexicon
    MyLex.AddPronunciation "one", 1033, SPSNoun, "w ah n"

    ' Get first item in pronunciations collection:
    Set MyLexPronunciations = MyLex.GetPronunciations("one", 1033)
    Set MyLexPronunciation = MyLexPronunciations.Item(0)

    PhoneIDs = MyLexPronunciation.PhoneIDs

    For ID = LBound(PhoneIDs) To UBound(PhoneIDs)
        TmpStr = TmpStr & Str(PhoneIDs(ID))
    Next ID

    MsgBox TmpStr, vbInformation

    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechLexiconPronunciation Symbolic Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechLexiconPronunciation

Symbolic Property

The Symbolic property returns the pronunciation of a word as a string of phone symbols.

Pronunciations represented in phones can be converted to PhoneIds with the PhoneToId method of the SpPhoneConverter object.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechLexiconPronunciation.Symbolic

Parts

ISpeechLexiconPronunciation
The owning object.
String
Set: (This property is read-only)
Get: A String variable returning the value of the property.


ISpeechLexiconPronunciation Type Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: ISpeechLexiconPronunciation

Type Property

The Type property returns the type of the pronunciation.

Syntax

Set: | (This property is read-only)
Get: | SpeechLexiconType = ISpeechLexiconPronunciation.Type

Parts

ISpeechLexiconPronunciation
The owning object.
SpeechLexiconType
Set: (This property is read-only)
Get: A SpeechLexiconType constant returning the type.


ISpeechLexiconPronunciations Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechLexiconPronunciations

The ISpeechLexiconPronunciations automation interface represents a collection of ISpeechLexiconPronunciation objects.

Automation Interface Elements

The ISpeechLexiconPronunciations automation interface contains the following elements:

Properties | Description
Count Property | Returns the number of objects in the collection.
Methods | Description
Item Method | Returns a member of the collection by its index.


ISpeechLexiconPronunciations Count Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: ISpeechLexiconPronunciations

Count Property

The Count property returns the number of objects in the collection.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechLexiconPronunciations.Count

Parts

ISpeechLexiconPronunciations
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the Count property.

Remarks

The ISpeechLexiconPronunciations object is a collection of ISpeechLexiconPronunciation objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all objects in the collection. The Count property is one of these common properties.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechLexiconPronunciations Item Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechLexiconPronunciations

Item Method

The Item method returns a member of the ISpeechLexiconPronunciations collection by its index.

ISpeechLexiconPronunciations.Item(
     Index As Long
) As ISpeechLexiconPronunciation

Parameters

Index
Specifies the Index.

Return Value

The Item method returns an ISpeechLexiconPronunciation object.

Remarks

The ISpeechLexiconPronunciations object is a collection of ISpeechLexiconPronunciation objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Item method is one of these common methods.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechLexiconWord Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechLexiconWord

The ISpeechLexiconWord automation interface provides access to a lexicon word.

Automation Interface Elements

The ISpeechLexiconWord automation interface contains the following elements:

Properties | Description
LangId Property | Returns the language Id of a lexicon word.
Pronunciations Property | Returns the pronunciations of a lexicon word.
Type Property | Returns the type of a lexicon word.
Word Property | Returns the text of a lexicon word.


ISpeechLexiconWord LangId Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: ISpeechLexiconWord

LangId Property

The LangId property returns the language ID of a lexicon word.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechLexiconWord.LangId

Parts

ISpeechLexiconWord
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the LangId.


ISpeechLexiconWord Pronunciations Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: ISpeechLexiconWord

Pronunciations Property

The Pronunciations property returns the pronunciations of a lexicon word.

The pronunciations are returned as a collection of ISpeechLexiconPronunciation objects.

Syntax

Set: | (This property is read-only)
Get: | ISpeechLexiconPronunciations = ISpeechLexiconWord.Pronunciations

Parts

ISpeechLexiconWord
The owning object.
ISpeechLexiconPronunciations
Set: (This property is read-only)
Get: An ISpeechLexiconPronunciations object returning the pronunciations of the lexicon word.


ISpeechLexiconWord Type Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: ISpeechLexiconWord

Type Property

The Type property returns the type of a lexicon word.

Syntax

Set: | (This property is read-only)
Get: | SpeechWordType = ISpeechLexiconWord.Type

Parts

ISpeechLexiconWord
The owning object.
SpeechWordType
Set: (This property is read-only)
Get: A SpeechWordType constant returning the word type.


ISpeechLexiconWord Word Property (Microsoft Speech Platform)

 > Microsoft Speech Platform

Object: ISpeechLexiconWord

Word Property

The Word property returns the text of a lexicon word.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechLexiconWord.Word

Parts

ISpeechLexiconWord
The owning object.
String
Set: (This property is read-only)
Get: A String variable returning the word.


ISpeechLexiconWords Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechLexiconWords

The ISpeechLexiconWords automation interface represents a collection of ISpeechLexiconWord objects.

Automation Interface Elements

The ISpeechLexiconWords automation interface contains the following elements:

Properties | Description
Count Property | Returns the number of objects in the collection.
Methods | Description
Item Method | Returns a member of the collection by its index.


ISpeechLexiconWords Count Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: ISpeechLexiconWords

Count Property

The Count property returns the number of ISpeechLexiconWord objects in the ISpeechLexiconWords collection.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechLexiconWords.Count

Parts

ISpeechLexiconWords
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the Count property.

Remarks

The ISpeechLexiconWords object is a collection of ISpeechLexiconWord objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Count property is one of these common properties.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechLexiconWords Item Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechLexiconWords

Item Method

The Item method returns a member of the ISpeechLexiconWords collection by its index.

ISpeechLexiconWords.Item(
     Index As Long
) As ISpeechLexiconWord

Parameters

Index
Specifies the Index.

Return Value

The Item method returns an ISpeechLexiconWord object.

Remarks

The ISpeechLexiconWords object is a collection of ISpeechLexiconWord objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Item method is one of these common methods.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechObjectTokens Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechObjectTokens

The ISpeechObjectTokens automation interface represents a collection of SpObjectToken objects.

Automation Interface Elements

The ISpeechObjectTokens automation interface contains the following elements:

Properties | Description
Count Property | Returns the number of objects in the collection.
Methods | Description
Item Method | Returns a member of the collection by its index.


ISpeechObjectTokens Count Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechObjectTokens

Count Property

The Count property returns the number of SpObjectToken objects in the ISpeechObjectTokens object.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechObjectTokens.Count

Parts

ISpeechObjectTokens
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the Count property.

Remarks

The ISpeechObjectTokens object is a collection of SpObjectToken objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Count property is one of these common properties.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechObjectTokens Item Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechObjectTokens

Item Method

The Item method returns a member of the ISpeechObjectTokens collection by its index.

ISpeechObjectTokens.Item(
     Index As Long
) As SpObjectToken

Parameters

Index
Specifies the Index.

Return Value

The Item method returns an SpObjectToken variable.

Remarks

The ISpeechObjectTokens object is a collection of SpObjectToken objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Item method is one of these common methods.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechPhraseAlternate Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechPhraseAlternate

The ISpeechPhraseAlternate automation interface enables applications to retrieve alternate phrase information from a speech recognition (SR) engine, and to update the SR engine's language model to reflect committed alternate changes.

There are two types of speech recognition in SAPI: Command and control (C&C) recognition, which is guided by one or more grammars; and dictation recognition, in which the SR engine uses statistical calculations to determine the most likely recognitions of a requested phrase. It should be noted that the two types are not mutually exclusive, and that applications do not request one type of recognition as opposed to the other. Applications simply request recognition; they can determine after the fact which type of recognition produced a particular recognition result.

Dictation recognition is inherently less accurate than C&C recognition, which is guided by grammars. Because of this, there is a practical need for returning alternate recognition results, and for the user to select an alternate as the correct recognition of the phrase.

The ISpeechRecoResult.Alternates method returns a specific number of recognitions in an ISpeechPhraseAlternates object. It should be noted that the default recognition result is the first ISpeechPhraseAlternate object in the collection.

Use of the ISpeechPhraseAlternate object is demonstrated in a code example at the end of this section.

Automation Interface Elements

The ISpeechPhraseAlternate automation interface contains the following elements:

Properties | Description
NumberOfElementsInResult Property | Returns the count of phrase elements in the alternate's parent ISpeechRecoResult object.
PhraseInfo Property | Returns the ISpeechPhraseInfo object of the alternate's parent ISpeechRecoResult object.
RecoResult Property | Returns the alternate's parent ISpeechRecoResult object.
StartElementInResult Property | Specifies the starting phrase element of the alternate's parent ISpeechRecoResult object.
Methods | Description
Commit Method | Specifies that the alternate recognition should replace the recognition selected by the SR engine.


ISpeechPhraseAlternate Commit Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseAlternate

Commit Method

The Commit method specifies that the alternate recognition should replace the recognition selected by the speech recognition (SR) engine.

ISpeechPhraseAlternate.Commit()

Parameters

None.

Return Value

None.

Example

Use of the Commit method is demonstrated in a code example at the end of this section.


ISpeechPhraseAlternate NumberOfElementsInResult Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseAlternate

NumberOfElementsInResult Property

The NumberOfElementsInResult property returns the count of phrase elements in the alternate's parent ISpeechRecoResult object.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseAlternate.NumberOfElementsInResult

Parts

ISpeechPhraseAlternate
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the value of the property.

Example

Use of the ISpeechPhraseAlternate object is demonstrated in a code example at the end of this section.


ISpeechPhraseAlternate PhraseInfo Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseAlternate

PhraseInfo Property

The PhraseInfo property returns the ISpeechPhraseInfo object of the alternate's parent ISpeechRecoResult object.

Syntax

Set: | (This property is read-only)
Get: | ISpeechPhraseInfo = ISpeechPhraseAlternate.PhraseInfo

Parts

ISpeechPhraseAlternate
The owning object.
ISpeechPhraseInfo
Set: (This property is read-only)
Get: An ISpeechPhraseInfo that gets the value of the property.

Example

Use of the ISpeechPhraseAlternate object is demonstrated in a code example at the end of this section.


ISpeechPhraseAlternate RecoResult Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseAlternate

RecoResult Property

The RecoResult property returns the alternate's parent ISpeechRecoResult object.

Syntax

Set: | (This property is read-only)
Get: | ISpeechRecoResult = ISpeechPhraseAlternate.RecoResult

Parts

ISpeechPhraseAlternate
The owning object.
ISpeechRecoResult
Set: (This property is read-only)
Get: The alternate's parent ISpeechRecoResult object.

Example

Use of the ISpeechPhraseAlternate object is demonstrated in a code example at the end of this section.


ISpeechPhraseAlternate StartElementInResult Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseAlternate

StartElementInResult Property

The StartElementInResult property specifies the starting phrase element of the alternate's parent ISpeechRecoResult object.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseAlternate.StartElementInResult

Parts

ISpeechPhraseAlternate
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the starting element.

Example

Use of the ISpeechPhraseAlternate object is demonstrated in a code example at the end of this section.


ISpeechPhraseAlternate Code Example (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseAlternate

ISpeechPhraseAlternate Code Example

The following Visual Basic form code displays use of the ISpeechPhraseAlternate object. It demonstrates recognition and the EmulateRecognition method.

To run this code, create a form with the following controls:

  • A text box called Text1
  • Two list boxes, called List1 and List2
  • Two command buttons, called Command1 and Command2

Paste this code into the Declarations section of the form and add a reference to Microsoft Speech Object Library in Visual Basic's References dialog box.

The solitaire grammar file sol.xml is located in the default directory for a standard SAPI SDK installation. If the file is not there, use the path to an existing version.

The Form_Load procedure creates a recognizer, a recognition context, and a grammar object. It loads the grammar object with sol.xml, the Solitaire grammar from the SAPI sample code, then activates the command and control (C and C) and dictation components of the grammar, and places a Solitaire command in the text box. Text matching the rules of the Solitaire grammar will produce better recognition results, but in order to demonstrate recognition alternates, it is necessary to enter phrases that do not satisfy grammar rules.

The command button, captioned Recognition, speaks text from the text box into an audio .wav file and then performs speech recognition of that file. The command button captioned EmulateRecognition simply calls the EmulateRecognition method.

When alternates are available, the code displays three alternates in the top list box, and shows the phrase elements of one alternate in the lower list box. Click any alternate to display its phrase elements in the lower list box. Double click any alternate to perform the Commit method on that alternate. In the illustration below, the first alternate is incorrect; the second alternate is highlighted, and its phrase elements are displayed in the lower list box.

The data displayed in the lower list box is the same data displayed in the ISpeechPhraseElement code example. Please see that page for full details.

Option Explicit

Const WAVEFILENAME = "C:\ISpeechPhraseAlternate.wav"

Private blnAlternatesExist As Boolean

Private MyRecognizer As SpeechLib.SpInprocRecognizer
Private MyGrammar As SpeechLib.ISpeechRecoGrammar
Private MyFileStream As SpeechLib.SpFileStream
Private MyVoice As SpeechLib.SpVoice

Private PhraseInfo As SpeechLib.ISpeechPhraseInfo
Private PhraseAlts1 As SpeechLib.ISpeechPhraseAlternate
Private PhraseAlts2 As SpeechLib.ISpeechPhraseAlternates
Private PhraseElem As SpeechLib.ISpeechPhraseElement
Private PhraseElems As SpeechLib.ISpeechPhraseElements

Private WithEvents MyRecoContext As SpeechLib.SpInProcRecoContext

Private Sub Command1_Click()
    On Error GoTo EH

    List1.Clear
    List2.Clear
    Screen.MousePointer = vbHourglass

    ' Create ISpeechPhraseAlternate.wav file from text in text box.
    Set MyFileStream = MakeWAVFileFromText(Text1.Text, WAVEFILENAME)

    'Set the file as recognizer's input stream
    MyFileStream.Open WAVEFILENAME
    Set MyRecognizer.AudioInputStream = MyFileStream

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH

    List1.Clear
    List2.Clear
    Screen.MousePointer = vbHourglass
    MyRecoContext.Recognizer.EmulateRecognition Text1.Text

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    ' Create Recognizer, RecoContext, Grammar, and Voice
    Set MyRecognizer = New SpInprocRecognizer
    Set MyRecoContext = MyRecognizer.CreateRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar(16)
    Set MyVoice = New SpVoice

    ' Load Grammar with solitaire XML, set active
    MyGrammar.CmdLoadFromFile "C:\sol.xml", SLOStatic
    MyGrammar.CmdSetRuleIdState 0, SGDSActive           'Set MyRecoContext & MyRecoContext active
    MyGrammar.DictationSetState SGDSActive              'Set Dictation active

    Text1.Text = "let's go over minor details"
    Command1.Caption = "&Recognition"
    Command2.Caption = "&EmulateRecognition"

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Function MakeWAVFileFromText _
   (ByVal strText As String, _
    ByVal strFName As String) _
    As SpFileStream

    On Error GoTo EH

    ' Declare identifiers:
    Dim FileStream As SpFileStream
    Dim Voice As SpVoice

    ' Instantiate Voice and FileStream objects:
    Set Voice = New SpVoice
    Set FileStream = New SpFileStream

    ' Open specified .wav file, set voice output
    ' to file, and speak synchronously:
    FileStream.Open strFName, SSFMCreateForWrite, True
    Set Voice.AudioOutputStream = FileStream
    Voice.Speak strText, SVSFIsXML

    ' Close file and return reference to FileStream object:
    FileStream.Close
    Set MakeWAVFileFromText = FileStream

EH:
    If Err.Number Then ShowErrMsg
End Function

Private Function PhonesToString(ByVal arrV As Variant) As String
    Dim ii As Integer, S As String

    On Error GoTo EH

    If IsEmpty(arrV) Then
        PhonesToString = ""
    Else
        For ii = 0 To UBound(arrV)
            If Len(S) Then
                S = S & "," & arrV(ii)
            Else
                S = arrV(ii)
            End If
        Next ii
        PhonesToString = S
    End If

EH:
    If Err.Number Then ShowErrMsg
End Function

Private Sub MyRecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)
    Dim nn As Integer

    On Error GoTo EH

    Set PhraseAlts2 = Result.Alternates(3)       'May or may not be available
    If PhraseAlts2 Is Nothing Then

        'No alternates when speech matches PhraseAlts1 grammar rule
        'No alternates when using EmulateRecognition
        blnAlternatesExist = False
        List1.AddItem Result.PhraseInfo.GetText
        If Len(Result.PhraseInfo.Rule.Name) Then
            List1.AddItem "   matches rule """ & Result.PhraseInfo.Rule.Name & """"
        End If
        Set PhraseInfo = Result.PhraseInfo
    Else

        blnAlternatesExist = True
        nn = 0
        For Each PhraseAlts1 In PhraseAlts2
            List1.AddItem "alt" & Format(nn) & ": " & PhraseAlts1.PhraseInfo.GetText
            nn = nn + 1
        Next
        Set PhraseInfo = PhraseAlts2.Item(0).PhraseInfo
    End If

    List1.ListIndex = 0     'Highlight the selected alternate
    Call DisplayPhraseElements(0)
    Screen.MousePointer = vbDefault

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub MyRecoContext_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal StreamReleased As Boolean)

    On Error GoTo EH

    'Recognition uses the Filestream, EmulateReco does not
    If ActiveControl.Caption = "&Recognition" Then
        MyFileStream.Close
        DoEvents
        MyFileStream.Open WAVEFILENAME
        MyVoice.SpeakStream MyFileStream
        MyFileStream.Close
    End If
    Screen.MousePointer = vbDefault

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub DisplayPhraseElements(Index As Integer)
    Dim X As String
    Dim T As String
    Dim A1 As Long, A2 As Long
    Dim T1 As Long, T2 As Long
    Dim C1 As Single, C2 As Integer, C3 As Integer

    On Error GoTo EH

    List2.Clear

    'If no alternates, then there is only one PhraseInfo
    If blnAlternatesExist = True Then
        Set PhraseInfo = PhraseAlts2.Item(Index).PhraseInfo
    End If

    For Each PhraseElem In PhraseInfo.Elements

        'Audio data
        A1 = PhraseElem.AudioStreamOffset
        A2 = PhraseElem.AudioSizeBytes
        X = Format(A1, "000000") & " " & Format(A2, "000000") & "  "

        'Time data
        T1 = PhraseElem.AudioTimeOffset
        T2 = PhraseElem.AudioSizeTime
        X = X & Format(T1, "000000000") & " " & Format(T2, "000000000") & "  "

        'Display attributes
        X = X & Format(PhraseElem.DisplayAttributes) & " "

        'Confidences
        C1 = PhraseElem.EngineConfidence
        C2 = PhraseElem.ActualConfidence
        C3 = PhraseElem.RequiredConfidence
        T = "(" & Format(C1) & " " & Format(C2) & " " & Format(C3) & ")"
        X = X & Left(T & "         ", 14)

        'Text and pronunciation
        X = X & Left(PhraseElem.DisplayText & "              ", 14)
        X = X & PhonesToString(PhraseElem.Pronunciation)

        List2.AddItem X
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub List1_Click()
    Call DisplayPhraseElements(List1.ListIndex)
End Sub

Private Sub List1_DblClick()
    PhraseAlts2.Item(List1.ListIndex).Commit
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechPhraseAlternates Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechPhraseAlternates

The ISpeechPhraseAlternates automation interface is a collection of ISpeechPhraseAlternate objects.

Automation Interface Elements

The ISpeechPhraseAlternates automation interface contains the following elements:

Properties | Description
Count Property | Returns the number of objects in the collection.
Methods | Description
Item Method | Returns a member of the collection by its index.


ISpeechPhraseAlternates Count Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseAlternates

Count Property

The Count property returns the number of ISpeechPhraseAlternate objects in the ISpeechPhraseAlternates object.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseAlternates.Count

Parts

ISpeechPhraseAlternates
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the Count property.

Remarks

The SpeechPhraseAlternates object is a collection of ISpeechPhraseAlternate objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Count property is one of these common properties.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechPhraseAlternates Item Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechPhraseAlternates

Item Method

The Item method returns a member of the ISpeechPhraseAlternates collection by its index.

ISpeechPhraseAlternates.Item(
     Index As Long
) As ISpeechPhraseAlternate

Parameters

Index
Specifies the Index.

Return Value

The Item method returns an ISpeechPhraseAlternate variable.

Remarks

The ISpeechPhraseAlternates object is a collection of ISpeechPhraseAlternate objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Item method is one of these common methods.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechPhraseElement Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechPhraseElement

The ISpeechPhraseElement automation interface provides access to information about a word or phrase.

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.

Automation Interface Elements

The ISpeechPhraseElement automation interface contains the following elements:

Properties | Description
ActualConfidence Property | Returns the actual confidence for the phrase element.
AudioSizeBytes Property | Returns the size, in bytes, of the audio for this element.
AudioSizeTime Property | Returns the length of the element in 100-nanosecond units.
AudioStreamOffset Property | Returns the starting offset of the element in bytes relative to the start of the phrase in the original input stream.
AudioTimeOffset Property | Returns the starting offset of the element in 100-nanosecond units relative to the start of the phrase.
DisplayAttributes Property | Returns a set of SpeechDisplayAttributes constants defining information about the display of this word.
DisplayText Property | Returns the display text for the element.
EngineConfidence Property | Returns the confidence score computed by the SR engine.
LexicalForm Property | Returns the lexical form of the element.
Pronunciation Property | Returns the pronunciation of the element as phonemes.
RequiredConfidence Property | Returns the required confidence for this element.
RetainedSizeBytes Property | Returns the size, in bytes, of the element in the retained audio stream.
RetainedStreamOffset Property | Returns the starting offset of the element in bytes relative to the start of the phrase in the retained audio stream.


ISpeechPhraseElement ActualConfidence Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

ActualConfidence Property

The ActualConfidence property returns the actual confidence for the phrase element.

This value consists of a SpeechEngineConfidence constant, and it is always at least as high as the ISpeechPhraseElement.RequiredConfidence property. The confidence rating is an enumerated value of type SpeechEngineConfidence.

Syntax

Set: | (This property is read-only)
Get: | SpeechEngineConfidence = ISpeechPhraseElement.ActualConfidence

Parts

ISpeechPhraseElement
The owning object.
SpeechEngineConfidence
Set: (This property is read-only)
Get: A SpeechEngineConfidence constant that gets the value of the property.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement AudioSizeBytes Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

AudioSizeBytes Property

The AudioSizeBytes property returns the size, in bytes, of the audio for this element.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseElement.AudioSizeBytes

Parts

ISpeechPhraseElement
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the value of the property.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement AudioSizeTime Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

AudioSizeTime Property

The AudioSizeTime property returns the length of the element in 100-nanosecond units.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseElement.AudioSizeTime

Parts

ISpeechPhraseElement
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the value of the property.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement AudioStreamOffset Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

AudioStreamOffset Property

The AudioStreamOffset property returns the starting offset of the element, in bytes, relative to the start of the phrase in the original input stream.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseElement.AudioStreamOffset

Parts

ISpeechPhraseElement
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the value of the property.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement AudioTimeOffset Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

AudioTimeOffset Property

The AudioTimeOffset property returns the starting offset of the element in 100-nanosecond units relative to the start of the phrase.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseElement.AudioTimeOffset

Parts

ISpeechPhraseElement
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the value of the property.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement DisplayAttributes Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

DisplayAttributes Property

The DisplayAttributes property returns a set of SpeechDisplayAttributes constants defining information about the display of this word.

Syntax

Set: | (This property is read-only)
Get: | SpeechDisplayAttributes = ISpeechPhraseElement.DisplayAttributes

Parts

ISpeechPhraseElement
The owning object.
SpeechDisplayAttributes
Set: (This property is read-only)
Get: One or more SpeechDisplayAttributes constants that gets the value of the property.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement DisplayText Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

DisplayText Property

The DisplayText property returns the display text for the element with normalization of numbers, currency values, and ordinals (for example, displays "$2" for the spoken words "two dollars").

The LexicalForm property displays text without normalization of numbers, currency values, and ordinals.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechPhraseElement.DisplayText

Parts

ISpeechPhraseElement
The owning object.
String
Set: (This property is read-only)
Get: A String variable that gets the value of the property.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement EngineConfidence Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

EngineConfidence Property

The EngineConfidence property returns the confidence score computed by the speech recognition (SR) engine.

Syntax

Set: | (This property is read-only)
Get: | Single = ISpeechPhraseElement.EngineConfidence

Parts

ISpeechPhraseElement
The owning object.
Single
Set: (This property is read-only)
Get: A Single variable that gets the value of the property.

Remarks

The value range is engine dependent. It can be used to optimize an application's performance with a specific engine. Using this value will improve the application with a particular speech engine, but it is likely to make it worse with other engines and should be used with care. This value is more useful with speaker-independent engines because it allows a large corpus of recorded usage to correctly optimize the overall accuracy of the application.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement LexicalForm Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

LexicalForm Property

The LexicalForm property returns the lexical form of the element without normalization of numbers, currency values, and ordinals (for example, displays "two dollars" for the spoken words "two dollars").

The DisplayText property displays text with normalization of numbers, currency values, and ordinals.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechPhraseElement.LexicalForm

Parts

ISpeechPhraseElement
The owning object.
String
Set: (This property is read-only)
Get: A String variable that gets the value of the property.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement Pronunciation Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

Pronunciation Property

The Pronunciation property returns the pronunciation of the element as phonemes.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechPhraseElement.Pronunciation

Parts

ISpeechPhraseElement
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant variable that gets the value of the property.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement RequiredConfidence Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

RequiredConfidence Property

The RequiredConfidence property returns the required confidence for this element.

This value is an enumerated value of type SpeechEngineConfidence. Required confidence values are specified in grammars. Preceding a word with '-' sets its RequiredConfidence as low (SECLowConfidence); preceding a word with '+' sets its RequiredConfidence as high (SECHighConfidence)

Syntax

Set: | (This property is read-only)
Get: | SpeechEngineConfidence = ISpeechPhraseElement.RequiredConfidence

Parts

ISpeechPhraseElement
The owning object.
SpeechEngineConfidence
Set: (This property is read-only)
Get: A SpeechEngineConfidence variable that gets the value of the property.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement RetainedSizeBytes Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

RetainedSizeBytes Property

The RetainedSizeBytes property returns the size, in bytes, of the element in the retained audio stream.

If the current RecoContext is retaining audio, the value of RetainedSizeBytes will be equal to the value of AudioSizeBytes. If the current RecoContext is not retaining audio, RetainedSizeBytes will be zero.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseElement.RetainedSizeBytes

Parts

ISpeechPhraseElement
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the value of the property.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement RetainedStreamOffset Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseElement

RetainedStreamOffset Property

The RetainedStreamOffset property returns the starting offset of the element, in bytes, relative to the start of the phrase in the retained audio stream.

If the current RecoContext is retaining audio, the value of RetainedStreamOffset will be equal to the value of AudioStreamOffset. If the current RecoContext is not retaining audio, RetainedStreamOffset will be zero.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseElement.RetainedStreamOffset

Parts

ISpeechPhraseElement
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the value of the property.

Example

Use of the ISpeechPhraseElement is demonstrated in a code example at the end of this section.


ISpeechPhraseElement Code Example (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseElement

ISpeechPhraseElement Code Example

The following Visual Basic form code displays the properties of the ISpeechPhraseElement object. The ISpeechPhraseElement object is contained in the ISpeechRecoResult object returned by a RecoContext's Recognition event. This code shows two ways to create a recognition result object:

  • Perform recognition directly
  • Emulate recognition using the EmulateRecognition method

The example also demonstrates the use of the SpFileStream object in conjunction with the AudioOutputStream of the voice and the AudioInputStream of the recognizer.

To run this code, create a form with the following controls:

  • Two command buttons called Command1 and Command2
  • A list box called List1
  • A text box called Text1

Paste this code into the Declarations section of the form.

The code will set the command button captions as shown in the illustration.

The Form_Load procedure creates a recognizer, a recognition context, and a grammar object. It loads the grammar object with sol.xml, the Solitaire grammar from the SAPI sample code. It then activates the command and control (C and C) and dictation components of the grammar, and places a Solitaire command in the text box. Users can enter whatever text they like in the text box, but best recognition results will be obtained from phrases matching the rules in the C and C grammar; for example, sentences such as "Move the black ten to the jack of diamonds," or "Play the red queen."

The command button captioned Recognition speaks text from the text box into an audio file, and then performs speech recognition of that file. The command button captioned EmulateRecognition simply calls the EmulateRecognition method.

When the speech recognition (SR) engine has completed recognition, it generates a Recognition Event that returns an ISpeechRecoResult object. The Recognition procedure instantiates each ISpeechPhraseElement in the result object's Elements property (a collection of ISpeechPhraseElement objects), and displays selected phrase element properties in columns in the list box.

AudioStreamOffset and AudioSizeBytes

The first two columns show the AudioStreamOffset and AudioSizeBytes properties. These two properties indicate the boundaries of an element in the input audio stream. AudioStreamOffset points to the beginning of the element and AudioSizeBytes is the element's length. The sum of an element's AudioStreamOffset and AudioSizeBytes is the same as the AudioStreamOffset of the next element.

In an ISpeechPhraseElement object created by the EmulateRecognition method, the AudioStreamOffset and AudioSizeBytes properties are zero.

AudioTimeOffset and AudioSizeTime

The next two columns are the AudioTimeOffset and AudioSizeTime properties, which delimit the phrase elements in 100-nanosecond units of time. AudioTimeOffset indicates the beginning time of the element, and AudioSizeTime is its time length. The sum of an element's AudioTimeOffset and AudioSizeTime is approximately the same as the AudioTimeOffset of the next element.

In an ISpeechPhraseElement object created by the EmulateRecognition method, the AudioTimeOffset and AudioSizeTime properties are zero.

DisplayAttributes

The next column is the DisplayAttributes property, which defines how the text of the element is displayed relative to text from other phrase elements. The SpeechDisplayAttributes enumeration lists the possible values of this property. All elements in the example above have a DisplayAttributes property of two, which is the value of the SDA_One_Trailing_Space constant, indicating that the element should be displayed with a trailing space.

EngineConfidence, ActualConfidence, and RequiredConfidence

The three numbers in parentheses are the three property values involving confidence in the recognition of the phrase element. The first of these is the EngineConfidence property, which represents the SR engine's level of confidence in the recognition. The ActualConfidence property reduces the EngineConfidence to one of three confidence levels: low, normal or high. The RequiredConfidence property specifies the confidence level that the ActualConfidence property must equal or surpass.

In an ISpeechPhraseElement object created by the EmulateRecognition method, the EngineConfidence and RequiredConfidence properties are zero. If the emulated phrase matches C and C rules, the ActualConfidence property is one; otherwise it is zero.

DisplayText and LexicalForm

The DisplayText property is the next column in the example. It consists of the recognized text of the phrase element, with normalization of numbers, ordinals, and currency values. The LexicalForm property, not shown in this example, returns the same text, but without normalization.

Pronunciation

To the right of the DisplayText is data from the Pronunciation property. Each number represents a phoneme, and the phonemes represent the pronunciation of the phrase element.

In an ISpeechPhraseElement object created by the EmulateRecognition method, the Pronunciation property is Empty.

RetainedStreamOffset and RetainedSizeBytes

The RetainedStreamOffset and RetainedSizeBytes properties are not shown in this example. If the current recognition context is retaining audio data, then RetainedStreamOffset and RetainedSizeBytes are the same as AudioStreamOffset and AudioSizeBytes, respectively; otherwise, both properties are zero.

In an ISpeechPhraseElement object created by the EmulateRecognition method, the RetainedStreamOffset and RetainedSizeBytes properties are zero.

Option Explicit

Const WAVEFILENAME = "C:\ISpeechPhraseElement.wav"

Dim MyRecognizer As SpeechLib.SpInprocRecognizer
Dim MyGrammar As SpeechLib.ISpeechRecoGrammar
Dim MyFileStream As SpeechLib.SpFileStream
Dim PhraseElem As SpeechLib.ISpeechPhraseElement
Dim MyVoice As SpeechLib.SpVoice

Dim WithEvents MyRecoContext As SpeechLib.SpInProcRecoContext

Private Sub Command1_Click()
    On Error GoTo EH

    List1.Clear
    Set MyFileStream = MakeWAVFileFromText(Text1.Text, WAVEFILENAME)
    MyFileStream.Open WAVEFILENAME
    Set MyRecognizer.AudioInputStream = MyFileStream

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH

    List1.Clear
    MyRecoContext.Recognizer.EmulateRecognition Text1.Text

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    ' Create Recognizer, RecoContext, Grammar, and Voice
    Set MyRecognizer = New SpInprocRecognizer
    Set MyRecoContext = MyRecognizer.CreateRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar(16)
    Set MyVoice = New SpVoice
    Set MyVoice.Voice = MyVoice.GetVoices("gender=male").Item(0)

    ' Load Grammar with solitaire XML, set active
    MyGrammar.CmdLoadFromFile "C:\sol.xml", SLOStatic
    MyGrammar.CmdSetRuleIdState 0, SGDSActive               'Set MyRecoContext & MyRecoContext active
    MyGrammar.DictationSetState SGDSActive                  'Set Dictation active

    Text1.Text = "play the eight of clubs"
    Command1.Caption = "&Recognition"
    Command2.Caption = "&EmulateRecognition"

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Function PhonesToString(ByVal arrV As Variant) As String
    Dim ii As Integer, S As String

    On Error GoTo EH

    If IsEmpty(arrV) Then
        PhonesToString = ""
    Else
        For ii = 0 To UBound(arrV)
            If Len(S) Then
                S = S & "," & arrV(ii)
            Else
                S = arrV(ii)
            End If
        Next ii
        PhonesToString = S
    End If

EH:
    If Err.Number Then ShowErrMsg
End Function

Private Sub MyRecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim X As String
    Dim T As String
    Dim A1 As Long, A2 As Long
    Dim T1 As Long, T2 As Long
    Dim C1 As Single, C2 As Integer, C3 As Integer

    On Error GoTo EH

    For Each PhraseElem In Result.PhraseInfo.Elements

        'Audio data
        A1 = PhraseElem.AudioStreamOffset
        A2 = PhraseElem.AudioSizeBytes
        X = Format(A1, "000000") & " " & Format(A2, "000000") & "  "

        'Time data
        T1 = PhraseElem.AudioTimeOffset
        T2 = PhraseElem.AudioSizeTime
        X = X & Format(T1, "000000000") & " " & Format(T2, "000000000") & "  "

        'Display attributes
        X = X & Format(PhraseElem.DisplayAttributes) & " "

        'Confidences
        C1 = PhraseElem.EngineConfidence
        C2 = PhraseElem.ActualConfidence
        C3 = PhraseElem.RequiredConfidence
        T = "(" & Format(C1) & " " & Format(C2) & " " & Format(C3) & ")"
        X = X & Left(T & "         ", 14)

        'Text and pronunciation
        X = X & Left(PhraseElem.DisplayText & "              ", 14)
        X = X & PhonesToString(PhraseElem.Pronunciation)

        List1.AddItem X
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub MyRecoContext_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal StreamReleased As Boolean)

    On Error GoTo EH

    'Recognition uses the Filestream, EmulateReco does not
    If ActiveControl.Caption = "&Recognition" Then MyFileStream.Close
    List1.AddItem ""

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Function MakeWAVFileFromText _
   (ByVal strText As String, _
    ByVal strFName As String) _
    As SpFileStream

    On Error GoTo EH

    ' Declare identifiers:
    Dim FileStream As SpFileStream
    Dim Voice As SpVoice

    ' Instantiate Voice and FileStream objects:
    Set Voice = New SpVoice
    Set FileStream = New SpFileStream

    ' Open specified .wav file, set voice output
    ' to file, and speak synchronously:
    FileStream.Open strFName, SSFMCreateForWrite, True
    Set Voice.AudioOutputStream = FileStream
    Voice.Speak strText, SVSFIsXML

    ' Close file and return reference to FileStream object:
    FileStream.Close
    Set MakeWAVFileFromText = FileStream

EH:
    If Err.Number Then ShowErrMsg
End Function

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechPhraseElements Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechPhraseElements

The ISpeechPhraseElements automation interface represents a collection of ISpeechPhraseElement objects.

Automation Interface Elements

The ISpeechPhraseElements automation interface contains the following elements:

Properties | Description
Count Property | Returns the number of objects in the collection.
Methods | Description
Item Method | Returns a member of the collection by its index.


ISpeechPhraseElements Count Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: ISpeechPhraseElements

Count Property

The Count property returns the number of ISpeechPhraseElement objects in the ISpeechPhraseElements object.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseElements.Count

Parts

ISpeechPhraseElements
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the count.

Remarks

The ISpeechPhraseElements object is a collection of ISpeechPhraseElement objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Count property is one of these common properties.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechPhraseElements Item Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechPhraseElements

Item Method

The Item method returns a member of the ISpeechPhraseElements collection by its index.

ISpeechPhraseElements.Item(
     Index As Long
) As ISpeechPhraseElement

Parameters

Index
Specifies the Index.

Return Value

The Item method returns an ISpeechPhraseElement variable.

Remarks

The ISpeechPhraseElements object is a collection of ISpeechPhraseElement objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Item method is one of these common methods.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechPhraseInfo Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechPhraseInfo

The ISpeechPhraseInfo automation interface contains properties detailing phrase elements. This includes information about the audio streams, start and stop times for the audio, and elements contained in the phrase.

Automation Interface Elements

The ISpeechPhraseInfo automation interface contains the following elements:

Properties | Description
AudioSizeBytes Property | Returns the size of audio data in bytes for this phrase.
AudioSizeTime Property | Returns the length of phrase's audio in 100-nanosecond units.
AudioStreamPosition Property | Returns the start time in the audio stream for the phrase.
Elements Property | Returns information about the elements of the phrase.
EngineId Property | Returns a string containing the GUID of the engine recognizing this phrase.
EnginePrivateData Property | Returns the private data of the engine.
GrammarId Property | Returns the ID of the grammar that contains the top-level rule used to recognize the phrase.
LanguageId Property | Returns the language ID for the phrase elements.
Properties Property | Returns the root property for the result.
Replacements Property | Returns possible text replacements.
RetainedSizeBytes Property | Returns the size in bytes of the retained audio data for the audio format specified.
Rule Property | Retrieves information about the top-level rule that was used to recognize the phrase.
StartTime Property | Returns the start time for start of phrase audio in absolute time.
Methods | Description
GetDisplayAttributes Method | Returns the display attribute for the text.
GetText Method | Returns the text from a recognition as a single string.
SaveToMemory Method | Saves the entire recognition result to memory.


ISpeechPhraseInfo AudioSizeBytes Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

AudioSizeBytes Property

The AudioSizeBytes property returns the size of audio data in bytes for this phrase.

AudioSizeBytes is directly tied to the input audio format. AudioSizeBytes increases as the quality of the format increases (and in doing so, requires more bytes). However, it is possible that the application needs the retained audio in a format different from the input audio stream (perhaps for lower-quality persistence, for example). If an application scales the audio, RetainedAudioSizeBytes will change, but not AudioSizeBytes.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseInfo.AudioSizeBytes

Parts

ISpeechPhraseInfo
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable containing the size of audio data.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo AudioSizeTime Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

AudioSizeTime Property

The AudioSizeTime property returns the phrase audio length in 100-nanosecond units.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseInfo.AudioSizeTime

Parts

ISpeechPhraseInfo
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable containing the phrase audio length.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo AudioStreamPosition Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

AudioStreamPosition Property

The AudioStreamPosition property returns the start time in the audio stream for the phrase.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechPhraseInfo.AudioStreamPosition

Parts

ISpeechPhraseInfo
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant variable that gets the property.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo Elements Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

Elements Property

The Elements property returns information about the elements of the phrase.

Syntax

Set: | (This property is read-only)
Get: | ISpeechPhraseElements = ISpeechPhraseInfo.Elements

Parts

ISpeechPhraseInfo
The owning object.
ISpeechPhraseElements
Set: (This property is read-only)
Get: An ISpeechPhraseElements variable containing the phrase elements.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo EngineId Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

EngineId Property

The EngineId property returns a string containing the GUID of the engine recognizing this phrase.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechPhraseInfo.EngineId

Parts

ISpeechPhraseInfo
The owning object.
String
Set: (This property is read-only)
Get: A String variable that gets the property.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo EnginePrivateData Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

EnginePrivateData Property

The EnginePrivateData property returns the private data of the engine.

Private engine data represents a proprietary engine that returns non-standard information with the recognition. The format of the data is defined by the manufacturer. Not every recognition will contain private data. If there is no private data, the return value will be empty or NULL.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechPhraseInfo.EnginePrivateData

Parts

ISpeechPhraseInfo
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant variable containing the private data returned by the engine.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo GetDisplayAttributes Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechPhraseInfo

GetDisplayAttributes Method

The GetDisplayAttributes method returns the display attribute for the text.

The display attribute is the padding of white spaces before or after each word as determined by the engine. The speech recognition engine determines this value for the language used. Western scripts commonly use spaces between words, although eastern languages may not. Default is SDA_One_Trailing_Space.

ISpeechPhraseInfo.GetDisplayAttributes(
     [StartElement As Long = 0],
     [Elements As Long = -1],
     [UseReplacements As Boolean = True]
) As SpeechDisplayAttributes

Parameters

StartElement
[Optional] Specifies the word position from which to start. If omitted, the first word is used.
Elements
[Optional] Specifies the number of words retrieve to determine spacing. Default value is -1 indicating all words are retrieved.
UseReplacements
[Optional] Indicates if replacement text should be used. An example of a text replacement is speaking the sentence "write new check for twenty dollars." The retrieved replacement text is "write new check for $20." Default value is True.

Return Value

The GetDisplayAttributes method returns a SpeechDisplayAttributes variable.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo GetText Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechPhraseInfo

GetText Method

The GetText method returns the text from a recognition as a single string.

ISpeechPhraseInfo.GetText(
     [StartElement As Long = 0],
     [Elements As Long = -1],
     [UseReplacements As Boolean = True]
) As String

Parameters

StartElement
[Optional] Specifies the word position from which to start. If omitted, the first word is used.
Elements
[Optional] Specifies the number of words to retrieve. Default value is -1 indicating all words are retrieved.
UseReplacements
[Optional] Indicates if replacement text should be used. An example of a text replacement is speaking the sentence "write new check for twenty dollars." The retrieved replacement text is "write new check for $20." Default value is True.

Return Value

The GetText method returns a String containing the words in the phrase.

Remarks

GetText may be used only after a recognition attempt, whether successful (SRERecognition), or unsuccessful (SREFalseRecognition).

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo GrammarId Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

GrammarId Property

The GrammarId property returns the ID of the grammar that contains the top-level rule used to recognize the phrase.

The grammar ID is set with ISpeechRecoContext.CreateGrammar.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechPhraseInfo.GrammarId

Parts

ISpeechPhraseInfo
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant variable that gets the property.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo LanguageId Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

LanguageId Property

The LanguageId property returns the language ID for the phrase elements.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseInfo.LanguageId

Parts

ISpeechPhraseInfo
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the property.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo Properties Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

Properties Property

The Properties property returns the root property for the result.

Syntax

Set: | (This property is read-only)
Get: | ISpeechPhraseProperties = ISpeechPhraseInfo.Properties

Parts

ISpeechPhraseInfo
The owning object.
ISpeechPhraseProperties
Set: (This property is read-only)
Get: An ISpeechPhraseProperties interface for the properties.

Remarks

If the recognition result does not have an associated property, the Property will have a value of Nothing.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo Replacements Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

Replacements Property

The Replacements property returns possible text replacements.

Syntax

Set: | (This property is read-only)
Get: | ISpeechPhraseReplacements = ISpeechPhraseInfo.Replacements

Parts

ISpeechPhraseInfo
The owning object.
ISpeechPhraseReplacements
Set: (This property is read-only)
Get: An ISpeechPhraseReplacements interface for the replacements.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo RetainedSizeBytes Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

RetainedSizeBytes Property

The RetainedSizeBytes property returns the size in bytes of the retained audio data for the audio format specified.

It is possible that the application needs the retained audio in a format different from the input audio stream; therefore, RetainedAudioSizeBytes and AudioSizeBytes could be different as well. In this case, the scaled (or converted) retained audio will be RetainedAudioSizeBytes in length and AudioSizeBytes will be the size of the original stream length. AudioSizeBytes changes only if the quality of the original format of the stream changes, and in doing so, requiring more or fewer bytes.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseInfo.RetainedSizeBytes

Parts

ISpeechPhraseInfo
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the property.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo Rule Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

Rule Property

The Rule property retrieves information about the top-level rule that was used to recognize the phrase.

Syntax

Set: | (This property is read-only)
Get: | ISpeechPhraseRule = ISpeechPhraseInfo.Rule

Parts

ISpeechPhraseInfo
The owning object.
ISpeechPhraseRule
Set: (This property is read-only)
Get: An ISpeechPhraseRule variable that gets the property.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo SaveToMemory Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechPhraseInfo

SaveToMemory Method

The SaveToMemory method saves the phrase information from a recognition result to memory.

The phrase may be recalled at a later time. To retrieve the phrase information from memory use SpPhraseInfoBuilder.RestorePhraseFromMemory.

ISpeechPhraseInfo.SaveToMemory() As Variant

Parameters

None

Return Value

The SaveToMemory method returns a Variant containing a pointer to the saved phrase.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseInfo StartTime Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

StartTime Property

The StartTime property returns the start time for the start of phrase audio in absolute time.

The time is expressed in Universal Coordinated Time.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechPhraseInfo.StartTime

Parts

ISpeechPhraseInfo
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant variable that gets the property.

Example

Use of the ISpeechPhraseInfo object is demonstrated in a code example at the end of this section.


ISpeechPhraseProperties Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechPhraseProperties

The ISpeechPhraseProperties automation interface represents a collection of ISpeechPhraseProperty objects.

Automation Interface Elements

The ISpeechPhraseProperties automation interface contains the following elements:

Properties | Description
Count Property | Returns the number of objects in the collection.
Methods | Description
Item Method | Returns a member of the collection by its index.


ISpeechPhraseProperties Count Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseProperties

Count Property

The Count property returns the number of ISpeechPhraseProperty objects in the ISpeechPhraseProperties object.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseProperties.Count

Parts

ISpeechPhraseProperties
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the Count property.

Remarks

The ISpeechPhraseProperties object is a collection of ISpeechPhraseProperty objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Count property is one of these common properties.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechPhraseProperties Item Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseProperties

Item Method

The Item method returns a member of the ISpeechPhraseProperties collection by its index.

ISpeechPhraseProperties.Item(
     Index As Long
) As ISpeechPhraseProperty

Parameters

Index
Specifies the Index.

Return Value

The Item method returns an ISpeechPhraseProperty variable.

Remarks

The ISpeechPhraseProperties object is a collection of ISpeechPhraseProperty objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Item method is one of these common methods.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechPhraseProperty Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechPhraseProperty

The ISpeechPhraseProperty automation interface stores the information for a semantic property.

Automation Interface Elements

The ISpeechPhraseProperty automation interface contains the following elements:

Properties | Description
Children Property | Returns a collection of the property's child objects.
Confidence Property | Returns the confidence value for this semantic property computed by SAPI or the speech recognition engine.
EngineConfidence Property | Returns the confidence value for this semantic property computed by the speech recognition (SR) engine.
FirstElement Property | Returns the offset of the first spoken element spanned by this property.
Id Property | Returns the ID of the semantic property.
Name Property | Returns the name of the semantic property.
NumberOfElements Property | Returns the number of spoken elements spanned by this property.
Parent Property | Specifies the parent of the semantic property.
Value Property | Returns the value of the semantic property.


ISpeechPhraseProperty Children Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseProperty

Children Property

The Children property returns a collection of the property's child objects.

A child is a rule within a rule. That is, within a command and control grammar, rules are explicitly defined with the Rule tag. To allow greater flexibility, it is possible to allow another rule to be used within one by declaring it with the RuleRef tag. In this case, the second rule referenced by the RuleRef tag could be a child. Child rules are defined with the RULE tag, and referenced with the RULEREF tag. Properties can be added to rulerefs and phrases within the rule with the PROPNAME attribute If a child rule is present, the original rule containing the child is the parent. In this way, a rule can contain several levels of children and child rules can have several levels of parents.

An example of this is sol.xml for the card game solitaire. A user may play a card such as "move the red five on the black seven." Examine sol.xml; the rule is set up so that both the color of the card as well as the rank are referenced within the MoveCard rule. In this case, a successful recognition would have two top parent nodes: From and To. In turn, each parent node would have two children: color and rank. This way, an application could sort through the rules and know exactly which card moves (the From node) and which card receives it (the To node). The rule name would still be MoveCard.

In contrast, the more simple command "play the red ace," has only two nodes (color and rank). Neither node is considered to be either parent or child since the rule PlayCard has no PROPNAME tag. The nodes are peers of each other.

Syntax

Set: | (This property is read-only)
Get: | ISpeechPhraseProperties = ISpeechPhraseProperty.Children

Parts

ISpeechPhraseProperty
The owning object.
ISpeechPhraseProperties
Set: (This property is read-only)
Get: An ISpeechPhraseProperties object returning the value of the property.

Example

The following code demonstrates the Children property from a command and control recognition.

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a command and control grammar. The grammar file sol.xml is the solitaire grammar provided with the SDK. The path listed is for a standard SDK install and may be changed as needed.

The display indicates that the rules match. If any are child rules, then the child name is also displayed. For instance, if "move the red five on the black six," has been recognized, the application displays the recognized text in Label1. Label2 displays the rule name and any associated children under it. If the rule has no children, Label2 displays "No Children."`

Option Explicit
Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    On Error GoTo EH

    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.CmdLoadFromFile "C:\Program Files\Microsoft Speech SDK 5.4\Samples\Common\sol.xml", SLODynamic
    myGrammar.CmdSetRuleIdState 0, SGDSActive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RC_FalseRecognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Beep
    Label1.Caption = "(no recognition)"
    Label2.Caption = ""

End Sub

Private Sub RC_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim i, j, theFirstElement, theNumberOfElements As Long
    Dim theString As String

    On Error GoTo EH

    Label1.Caption = Result.PhraseInfo.GetText & vbCrLf

    Label2.Caption = "Rule Properties Found : " & Result.PhraseInfo.Properties.Count & vbCrLf
    For i = 0 To Result.PhraseInfo.Properties.Count - 1

        'Property name used
        Label2.Caption = Label2.Caption & _
            "Rule " & i & ": " & Result.PhraseInfo.Properties.Item(i).Name & vbCrLf

        If Not Result.PhraseInfo.Properties.Item(i).Children Is Nothing Then
            Label2.Caption = Label2.Caption & _
                "   Children = " & Result.PhraseInfo.Properties.Item(i).Children.Count & vbCrLf

            For j = 0 To Result.PhraseInfo.Properties.Item(i).Children.Count - 1
                Label2.Caption = Label2.Caption & _
                    "      Rule = " & Result.PhraseInfo.Properties.Item(i).Children.Item(j).Name & vbCrLf
            Next
        Else
            Label2.Caption = Label2.Caption & "   No Children" & vbCrLf
        End If

    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechPhraseProperty Confidence Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseProperty

Confidence Property

The Confidence property returns the confidence value for this semantic property computed by SAPI or the speech recognition engine.

It is an enumerated value of type SpeechEngineConfidence.

Syntax

Set: | (This property is read-only)
Get: | SpeechEngineConfidence = ISpeechPhraseProperty.Confidence

Parts

ISpeechPhraseProperty
The owning object.
SpeechEngineConfidence
Set: (This property is read-only)
Get: A SpeechEngineConfidence variable that gets the property.

Remarks

It is possible to have different confidences for each rule name. This would be the result of pronunciation, background noise, or accent.

Example

The following code demonstrates getting the Confidence property from a command and control recognition. One label displays the recognized text and the other label displays the rule name activated as well as the confidence associated with that recognition.

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a command and control grammar. The grammar file sol.xml is the solitaire grammar with the SDK. The path listed is for a standard SDK install and may be changed as needed.

If "play the red five" has been recognized, the application displays the recognized text in Label1. Label2 displays the rule name and the confidence for that recognition. In this case, the rules would be "color" and "rank" along with their confidence values.

Option Explicit
Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    On Error GoTo EH

    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.CmdLoadFromFile "C:\Program Files\Microsoft Speech SDK 5.4\Samples\Common\sol.xml", SLODynamic
    myGrammar.CmdSetRuleIdState 0, SGDSActive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RC_FalseRecognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Beep
    Label1.Caption = "(no recognition)"
    Label2.Caption = ""

End Sub

Private Sub RC_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim i As Long

    On Error GoTo EH

    Label1.Caption = Result.PhraseInfo.GetText & vbCrLf

    Label2.Caption = "Rule Properties Found : " & Result.PhraseInfo.Properties.Count & vbCrLf
    For i = 0 To Result.PhraseInfo.Properties.Count - 1
        Label2.Caption = Label2.Caption & Result.PhraseInfo.Properties.Item(i).Name
        Label2.Caption = Label2.Caption & " Confidence : " & Result.PhraseInfo.Properties.Item(i).Confidence & vbCrLf
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechPhraseProperty EngineConfidence Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseProperty

EngineConfidence Property

The EngineConfidence property returns the confidence value for this semantic property computed by the speech recognition (SR) engine.

The value range is specific to each SR engine and not standard across multiple SR engines.

Syntax

Set: | (This property is read-only)
Get: | Single = ISpeechPhraseProperty.EngineConfidence

Parts

ISpeechPhraseProperty
The owning object.
Single
Set: (This property is read-only)
Get: A Single variable that gets the property.

Example

The following code demonstrates retrieving the Engine Confidence property from a command and control recognition. One label displays the recognized text and the other label displays the rule name activated along with the engine confidence associated with that recognition.

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a command and control grammar. The grammar file sol.xml is the solitaire grammar provided with the SDK. The path listed is for a standard SDK install and may be changed as needed.

If "play the red five" has been recognized, the application displays the recognized text in Label1. Label2 displays the rule name and the confidence for that recognition. In this case, the rules would be "color" and "rank" along with their Engine confidence values.

Option Explicit
Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    On Error GoTo EH

    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.CmdLoadFromFile "C:\Program Files\Microsoft Speech SDK 5.4\Samples\Common\sol.xml", SLODynamic
    myGrammar.CmdSetRuleIdState 0, SGDSActive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RC_FalseRecognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Beep
    Label1.Caption = "(no recognition)"
    Label2.Caption = ""

End Sub

Private Sub RC_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim i As Long

    On Error GoTo EH

    Label1.Caption = Result.PhraseInfo.GetText & vbCrLf

    Label2.Caption = "Rule Properties Found : " & Result.PhraseInfo.Properties.Count & vbCrLf
    For i = 0 To Result.PhraseInfo.Properties.Count - 1
        Label2.Caption = Label2.Caption & Result.PhraseInfo.Properties.Item(i).Name
        Label2.Caption = Label2.Caption & " Engine Confidence : " & Result.PhraseInfo.Properties.Item(i).EngineConfidence & vbCrLf
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechPhraseProperty FirstElement Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseProperty

FirstElement Property

The FirstElement property returns the offset of the first spoken element spanned by this property.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseProperty.FirstElement

Parts

ISpeechPhraseProperty
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the property.

Example

The following code demonstrates retrieving the Name property from a command and control recognition.

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar. The grammar file sol.xml is the solitaire grammar provided with the SDK. The path listed is for a standard SDK install and may be changed as needed.

If "play the red five" has been recognized, the application will display the recognized text in label1. Label2 displays the names of the two properties used from the grammar along with the actual word or phrase which activated the rule. In this case, the rules would be "color=red" and "rank=five." The number of elements in the phrase matching the property is displayed in parenthesis. It is possible for more than one word to activate a rule for a property. In the case of sol.xml, only single words are used. However, if the file were changed, for example, so that the ColorRed definition becomes "red card" instead of just "red", then the expression "play the red card five" would display two elements for the property.

Option Explicit
Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
On Error GoTo EH

    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.CmdLoadFromFile "C:\Program Files\Microsoft Speech SDK 5.4\Samples\Common\sol.xml", SLODynamic
    myGrammar.CmdSetRuleIdState 0, SGDSActive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RC_FalseRecognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Beep
    Label1.Caption = "(no recognition)"
    Label2.Caption = ""

End Sub

Private Sub RC_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim i, j, theFirstElement, theNumberOfElements As Long
    Dim theString As String

    On Error GoTo EH

    Label1.Caption = Result.PhraseInfo.GetText & vbCrLf

    Label2.Caption = "Rule Properties Found : " & Result.PhraseInfo.Properties.Count & vbCrLf
    For i = 0 To Result.PhraseInfo.Properties.Count - 1
        Label2.Caption = Label2.Caption & _
            "Rules Name: " & Result.PhraseInfo.Properties.Item(i).Name

        theFirstElement = Result.PhraseInfo.Properties.Item(i).FirstElement
        theNumberOfElements = Result.PhraseInfo.Properties.Item(i).NumberOfElements

        theString = ""
        For j = 0 To theNumberOfElements - 1
            theString = theString & Result.PhraseInfo.Elements(theFirstElement + j).DisplayText
            theString = theString & " "
        Next

        Label2.Caption = Label2.Caption & _
            " = " & theString & " (" & theNumberOfElements & ")" & vbCrLf
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechPhraseProperty Id Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseProperty

Id Property

The Id property returns the ID of the semantic property.

The ID is the numeric identifier associated with the ISpeechPhraseProperty.Name property. This property must be explicitly marked with the PROPID label.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseProperty.Id

Parts

ISpeechPhraseProperty
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the property.

Remarks

Either Name or Id (if available) may be used to identify the rule invoked. Some languages, such as Visual Basic, can use strings in a Select Case statement. Therefore, the rule Name may be used directly in the Select Case statement. Other languages, such as C/C++ can only use numeric values in switch statements. In this case, the Id is more appropriate.

Example

See the example for ISpeechPhraseProperty.Name for more information.


ISpeechPhraseProperty Name Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseProperty

Name Property

The Name property returns the name of the semantic property.

The Name is the name of the semantic property from the command and control grammar. This property must be explicitly marked with the PROPNAME label. This is often associated with an ISpeechPhraseProperty.ID which is a numeric identifier and is assigned by the PROPID label.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechPhraseProperty.Name

Parts

ISpeechPhraseProperty
The owning object.
String
Set: (This property is read-only)
Get: A String variable that gets the property.

Remarks

Either Name or Id (if available) may be used to identify the rule invoked. Some languages, such as Visual Basic, can use strings in a Select Case statement. Therefore, the rule Name may be used directly in the Select Case statement. Other languages, such as C/C++ can only use numeric values in switch statements. In this case, the Id is more appropriate.

Example

The following code demonstrates getting the Name and Id property from a command and control recognition.

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a command and control grammar. The grammar file sol.xml is the solitaire grammar provided with the SDK. The path listed is for a standard SDK install and may be changed as needed.

If "play the red five" has been recognized, the application displays the recognized text in Label1. Label2 displays the additional information about the grammar properties. In this case, the rules would be "color" and "rank" along with their numeric values.

Option Explicit
Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    On Error GoTo EH
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.CmdLoadFromFile "C:\Program Files\Microsoft Speech SDK 5.4\Samples\Common\sol.xml", SLODynamic
    myGrammar.CmdSetRuleIdState 0, SGDSActive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RC_FalseRecognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Beep
    Label1.Caption = "(no recognition)"
    Label2.Caption = ""

End Sub

Private Sub RC_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim i, j, theFirstElement, theNumberOfElements As Long
    Dim theString As String

    On Error GoTo EH

    Label1.Caption = Result.PhraseInfo.GetText & vbCrLf

    Label2.Caption = "Rule Properties Found : " & Result.PhraseInfo.Properties.Count & vbCrLf
    For i = 0 To Result.PhraseInfo.Properties.Count - 1

        'Property name used
        Label2.Caption = Label2.Caption & _
            "Property Name: " & Result.PhraseInfo.Properties.Item(i).Name

         'Property Id used
        Label2.Caption = Label2.Caption & _
            " (" & Result.PhraseInfo.Properties.Item(i).Id & ")"

        theFirstElement = Result.PhraseInfo.Properties.Item(i).FirstElement
        theNumberOfElements = Result.PhraseInfo.Properties.Item(i).NumberOfElements

        theString = ""
        For j = 0 To theNumberOfElements - 1
            theString = theString & Result.PhraseInfo.Elements(theFirstElement + j).DisplayText
            theString = theString & " "
        Next

        Label2.Caption = Label2.Caption & _
            " = " & theString & " (" & theNumberOfElements & ")" & vbCrLf
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechPhraseProperty NumberOfElements Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseProperty

NumberOfElements Property

The NumberOfElements property returns the number of spoken elements spanned by this property.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseProperty.NumberOfElements

Parts

ISpeechPhraseProperty
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the property.

Example

See the example for ISpeechPhraseProperty.FirstElement for a complete example.


ISpeechPhraseProperty Parent Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseProperty

Parent Property

The Parent property specifies the parent of the semantic property.

A parent is a rule containing a child. A child is a rule within a rule. That is, within a command and control grammar, rules are explicitly defined with the Rule tag. To allow greater flexibility, it is possible to allow another rule to be used within one by declaring it with the RuleRef tag. In this case, the second rule being referenced by the RuleRef tag could be a child. Child rules are defined with the RULE tag, and referenced with the RULEREF tag. In this way, a rule can contain several levels of children and children rules can have several levels of parents.

An example of this is sol.xml for the card game solitaire. A user may play a card such as "move the red five on the black seven." Examine sol.xml; the rule is set up so that both the color of the card as well as the rank are referenced within the MoveCard rule. In this case, a successful recognition would have two top parent nodes: From and To. In turn, each parent node would have two children: color and rank. This way, an application could sort through the rules and know exactly which card moves (the From node) and which card receives it (the To node). The rule name would still be MoveCard.

In contrast, the more simple command "play the red ace," has only two nodes (color and rank). Neither node is considered a parent nor child since since the rule PlayCard does not have PROPNAME tag. Both nodes are peers of each other.

Syntax

Set: | (This property is read-only)
Get: | ISpeechPhraseProperty = ISpeechPhraseProperty.Parent

Parts

ISpeechPhraseProperty
The owning object.
ISpeechPhraseProperty
Set: (This property is read-only)
Get: An ISpeechPhraseProperty variable that gets the property.

Example

See ISpeechPhraseProperty.Children for a complete code sample.


ISpeechPhraseProperty Value Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseProperty

Value Property

The Value property returns the value of the semantic property.

The Value property is the value of a semantic property set in either the VAL or VALSTR attributes in the grammar. Each terminal node can have a value associated with it assigned by the VAL (for numeric values) or VALSTR (for string) attributes. This value may be used for processing the rule.

For instance, in the sol.xml grammar for the card game solitaire used in the example below, the actual rank of the card (e.g., ace, five, king) is the terminal node since no other word or phrase is needed to complete the rule for rank. Each word as an associated value to assist with processing the rule. In the case of card rank, ace is assigned 1, two is assigned 2, and so on, through the king which is assigned a value of 13. Additionally, a common alternate for king is included as emperor which also has a value of 13.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechPhraseProperty.Value

Parts

ISpeechPhraseProperty
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant variable that gets the property.

Example

The following code demonstrates retrieving the value property from a command and control recognition. The application displays the recognized text and also makes a subjective statement about the worth of the card played based on rank. A low card (which includes the ace in this solitaire game), displays "You played a low card," for instance.

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The grammar file sol.xml is the solitaire grammar provided with the SDK. The path listed is for a standard SDK install and may be changed as needed.

Option Explicit
Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    On Error GoTo EH
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.CmdLoadFromFile "C:\Program Files\Microsoft Speech SDK 5.4\Samples\Common\sol.xml", SLODynamic
    myGrammar.CmdSetRuleIdState 0, SGDSActive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RC_FalseRecognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Beep
    Label1.Caption = "(no recognition)"
    Label2.Caption = ""

End Sub

Private Sub RC_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim i As Long

    On Error GoTo EH

    Label1.Caption = Result.PhraseInfo.GetText & vbCrLf

    Label2.Caption = "Rule Properties Found : " & Result.PhraseInfo.Properties.Count & vbCrLf
    For i = 0 To Result.PhraseInfo.Properties.Count - 1

        If Result.PhraseInfo.Properties.Item(i).Name = "rank" Then

            Select Case Result.PhraseInfo.Properties.Item(i).Value
            Case Is < 5
                Label2.Caption = "You played a low card"
            Case Is < 9
                Label2.Caption = "You played a mediocre card"
            Case Else
                Label2.Caption = "You played a good card"
            End Select

        End If

    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechPhraseReplacement Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechPhraseReplacement

The ISpeechPhraseReplacement automation interface specifies a replacement, or text normalization, of one or more spoken words in a recognition result.

For example, the spoken words "twenty three" might be replaced by the replacement text "23."

Recognition results are returned in an ISpeechRecoResult, which contains an ISpeechPhraseInfo object. The ISpeechPhraseInfo has two properties which are closely related. Its Elements property is a collection of ISpeechPhraseElement objects; its Replacements property is a collection of ISpeechPhraseReplacement objects. An ISpeechPhraseReplacement object is related to and dependent on the phrase elements in the recognition result which contains it.

Use of the ISpeechPhraseReplacement is demonstrated in a code example at the end of this section.

Automation Interface Elements

The ISpeechPhraseReplacement automation interface contains the following elements:

Properties | Description
DisplayAttributes Property | Returns a set of SpeechDisplayAttributes constants specifying information about the display of this word.
FirstElement Property | Returns the offset of the first spoken element to be replaced.
NumberOfElements Property | Returns the number of spoken elements to replaced.
Text Property | Returns the text of the replacement.


ISpeechPhraseReplacement DisplayAttributes Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseReplacement

DisplayAttributes Property

The DisplayAttributes property returns a set of SpeechDisplayAttributes constants specifying information about the display of this word.

Syntax

Set: | (This property is read-only)
Get: | SpeechDisplayAttributes = ISpeechPhraseReplacement.DisplayAttributes

Parts

ISpeechPhraseReplacement
The owning object.
SpeechDisplayAttributes
Set: (This property is read-only)
Get: One or more SpeechDisplayAttributes constants representing the value of the property.

Example

Use of the DisplayAttributes property is demonstrated in a code example at the end of this section.


ISpeechPhraseReplacement FirstElement Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseReplacement

FirstElement Property

The FirstElement property returns the index of the first phrase element to be replaced.

The phrase elements replaced are contained in the same recognition result that contains the phrase replacement.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseReplacement.FirstElement

Parts

ISpeechPhraseReplacement
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the property.

Example

Use of the FirstElement property is demonstrated in a code example at the end of this section.


ISpeechPhraseReplacement NumberOfElements Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseReplacement

NumberOfElements Property

The NumberOfElements property returns the number of elements to replaced.

The phrase elements replaced are contained in the same recognition result that contains the phrase replacement.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseReplacement.NumberOfElements

Parts

ISpeechPhraseReplacement
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the property.

Example

Use of the NumberOfElements property is demonstrated in a code example at the end of this section.


ISpeechPhraseReplacement Text Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseReplacement

Text Property

The Text property returns the text of the replacement.

The phrase elements replaced are contained in the same recognition result that contains the phrase replacement. The Text property is the replacement for the number of phrase elements in the NumberOfElements property, beginning with the element specified in the FirstElement property.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechPhraseReplacement.Text

Parts

ISpeechPhraseReplacement
The owning object.
String
Set: (This property is read-only)
Get: A String variable representing the value of the property.

Example

Use of the Text property is demonstrated in a code example at the end of this section.


ISpeechPhraseReplacement Code Example (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseReplacement

Example

The following Visual Basic form code demonstrates the ISpeechPhraseReplacement interface and its relation to the ISpeechPhraseElement interface. To run this code, create a form with the following controls:

  • A text box called Text1
  • A list box called List1
  • Two command buttons called Command1 and Command2

Paste this code into the Declarations section of the form.

This example is based on the ISpeechPhraseElement code example. Individual phrase elements from the recognition result are listed in the list box. The DisplayAttributes and DisplayText properties of each phrase element are shown. The DisplayAttributes and Text properties of the phrase replacements are displayed next to the elements which can be replaced by them.

Option Explicit

Const WAVEFILENAME = "C:\ISpeechPhraseReplacement.wav"

Dim MyRecognizer As SpeechLib.SpInprocRecognizer
Dim MyGrammar As SpeechLib.ISpeechRecoGrammar
Dim MyFileStream As SpeechLib.SpFileStream
Dim PhraseElem As SpeechLib.ISpeechPhraseElement

Dim PhraseRepl As SpeechLib.ISpeechPhraseReplacement
Dim PhraseRepls As SpeechLib.ISpeechPhraseReplacements

Dim Voice1 As SpeechLib.SpVoice
Dim Voice2 As SpeechLib.SpVoice     'Plays the wave file back

Dim WithEvents MyRecoContext As SpeechLib.SpInProcRecoContext

Private Sub Command1_Click()
    On Error GoTo EH

    List1.Clear

    ' Create ISpeechPhraseReplacement.wav file from text in text box.
    Set MyFileStream = MakeWAVFileFromText(Text1.Text, WAVEFILENAME)

    'Set the file as recognizer's input stream
    MyFileStream.Open WAVEFILENAME
    Set MyRecognizer.AudioInputStream = MyFileStream

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH

    List1.Clear
    MyRecoContext.Recognizer.EmulateRecognition Text1.Text

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()

    ' Create Recognizer, RecoContext, Grammar, and Voice
    Set MyRecognizer = New SpInprocRecognizer
    Set MyRecoContext = MyRecognizer.CreateRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar(16)
    Set Voice1 = New SpVoice
    Set Voice1.Voice = Voice1.GetVoices("gender=male").Item(0)
    Set Voice2 = New SpVoice

    On Error GoTo EH

    ' Load Grammar with solitaire XML, set active
    MyGrammar.CmdLoadFromFile "c:\sol.xml", SLOStatic
    MyGrammar.CmdSetRuleIdState 0, SGDSActive               'Set C & C active
    MyGrammar.DictationSetState SGDSActive                  'Set Dictation active

    Text1.Text = "I spent twenty-eight dollars on route sixty-six"
    Command1.Caption = "&Recognition"
    Command2.Caption = "&EmulateRecognition"

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub SpeakToFile(ByVal strText As String, ByVal strFName As String)
    On Error GoTo EH

    Set MyFileStream = New SpFileStream                    'Create stream
    MyFileStream.Open strFName, SSFMCreateForWrite, True   'Open as the filename
    Set Voice1.AudioOutputStream = MyFileStream                 'Set voice output to file
    Voice1.Speak strText, SVSFIsXML                  'Speak synchronously
    MyFileStream.Close                                     'Close file

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub MyRecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim ECount As Integer   'Count of elements
    Dim ii As Integer
    Dim nn As Integer
    Dim R1 As Integer, R2 As Integer

    On Error GoTo EH

    'Arrays with an entry for every PhraseElem
    Dim arrElements() As String
    Dim arrReplaces() As String
    ECount = Result.PhraseInfo.Elements.Count - 1
    ReDim arrElements(ECount)
    ReDim arrReplaces(ECount)

    'Load PhraseElements into an array
    nn = 0
    For Each PhraseElem In Result.PhraseInfo.Elements
        arrElements(nn) = PhraseElem.DisplayAttributes & " " & PhraseElem.DisplayText
        nn = nn + 1
    Next

    'Load PhraseReplacements (if any) in an array
    Set PhraseRepls = Result.PhraseInfo.Replacements
    If Not PhraseRepls Is Nothing Then
        For Each PhraseRepl In PhraseRepls

            'Get the first and last elements
            'replaced by this Replacement
            R1 = PhraseRepl.FirstElement
            R2 = R1 + PhraseRepl.NumberOfElements - 1

            For ii = 0 To ECount
                'Is element within the range of this replacement?
                If (ii >= R1) And (ii <= R2) Then
                    arrReplaces(ii) = PhraseRepl.DisplayAttributes & " " & PhraseRepl.Text
                End If
            Next ii
        Next
    End If

    Dim X As String
    For ii = 0 To ECount

        'Get PhraseElem and pad with blanks
        X = arrElements(ii) & String(15, " ")
        X = Left(X, 15)

        'Put element index in front
        X = "Element" & Format(ii, "00") & ": " & X

        'Put Replacement elements at the end
        X = X & arrReplaces(ii)

        List1.AddItem X
    Next ii

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub MyRecoContext_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal StreamReleased As Boolean)

    On Error GoTo EH

    'Recognition uses the Filestream, EmulateReco does not
    If ActiveControl.Caption = "&Recognition" Then
        MyFileStream.Close
        DoEvents
        MyFileStream.Open WAVEFILENAME
        Voice2.SpeakStream MyFileStream
        MyFileStream.Close
    End If
    List1.AddItem ""

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Function MakeWAVFileFromText _
   (ByVal strText As String, _
    ByVal strFName As String) _
    As SpFileStream

    On Error GoTo EH

    ' Declare identifiers:
    Dim FileStream As SpFileStream
    Dim Voice As SpVoice

    ' Instantiate Voice and FileStream objects:
    Set Voice = New SpVoice
    Set FileStream = New SpFileStream

    ' Open specified .wav file, set voice output
    ' to file, and speak synchronously:
    FileStream.Open strFName, SSFMCreateForWrite, True
    Set Voice.AudioOutputStream = FileStream
    Voice.Speak strText, SVSFIsXML

    ' Close file and return reference to FileStream object:
    FileStream.Close
    Set MakeWAVFileFromText = FileStream

EH:
    If Err.Number Then ShowErrMsg
End Function

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechPhraseReplacements Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechPhraseReplacements

The ISpeechPhraseReplacements automation interface represents a collection of ISpeechPhraseReplacement objects.

Automation Interface Elements

The ISpeechPhraseReplacements automation interface contains the following elements:

Properties | Description
Count Property | Returns the number of objects in the collection.
Methods | Description
Item Method | Returns a member of the collection by its index.


ISpeechPhraseReplacements Count Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseReplacements

Count Property

The Count property returns the number of ISpeechPhraseReplacement objects in the ISpeechPhraseReplacements object.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseReplacements.Count

Parts

ISpeechPhraseReplacements
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the Count property.

Remarks

The ISpeechPhraseReplacements object is a collection of ISpeechPhraseReplacement objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Count property is one of these common properties.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechPhraseReplacements Item Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseReplacements

Item Method

The Item method returns a member of the ISpeechPhraseReplacement collection by its index.

ISpeechPhraseReplacements.Item(
     Index As Long
) As ISpeechPhraseReplacement

Parameters

Index
Specifies the Index.

Return Value

The Item method returns an ISpeechPhraseReplacement variable.

Remarks

The ISpeechPhraseReplacements object is a collection of ISpeechPhraseReplacement objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Item method is one of these common methods.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechPhraseRule Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechPhraseRule

The ISpeechPhraseRule automation interface represents the part of a recognition result that returns information about the grammar rule that produced the recognition.

An ISpeechPhraseRule object variable is returned by the Rule property of the ISpeechPhraseInfo object variable within a recognition result.

For an example of the use of the ISpeechPhraseRule interface, see the code example at the end of this section.

Automation Interface Elements

The ISpeechPhraseRule automation interface contains the following elements:

Properties | Description
Children Property | Returns an ISpeechPhraseRules collection of the rule's child rules.
Confidence Property | Returns the confidence for the rule computed by SAPI.
EngineConfidence Property | Returns the confidence score for the rule computed by the SR engine.
FirstElement Property | Returns the audio stream offset of the first phrase element in the recognition result matched by the rule.
Id Property | Returns the ID of the phrase rule.
Name Property | Returns the name of the phrase rule.
NumberOfElements Property | Returns the number of phrase elements spanned by this rule.
Parent Property | Returns the rule's parent rule.


ISpeechPhraseRule Children Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseRule

Children Property

The Children property returns an ISpeechPhraseRules collection of the rule's child rules.

If the rule has no children, its Children property will be Nothing.

Syntax

Set: | (This property is read-only)
Get: | ISpeechPhraseRules = ISpeechPhraseRule.Children

Parts

ISpeechPhraseRule
The owning object.
ISpeechPhraseRules
Set: (This property is read-only)
Get: An ISpeechPhraseRules object that gets the collection of child rules.

Example

For an example of the use of the Children property, see the code example at the end of this section.


ISpeechPhraseRule Confidence Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseRule

Confidence Property

The Confidence property returns the confidence for this rule computed by SAPI.

It is an enumerated value of type SpeechEngineConfidence.

Syntax

Set: | (This property is read-only)
Get: | SpeechEngineConfidence = ISpeechPhraseRule.Confidence

Parts

ISpeechPhraseRule
The owning object.
SpeechEngineConfidence
Set: (This property is read-only)
Get: A SpeechEngineConfidence variable that gets the Confidence property.

Example

For an example of the use of the Confidence property, see the code example at the end of this section.


ISpeechPhraseRule EngineConfidence Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseRule

EngineConfidence Property

The EngineConfidence property returns the confidence score for the rule computed by the speech recognition (SR) engine.

The value is engine dependent and not standardized across multiple SR engines.

Syntax

Set: | (This property is read-only)
Get: | Single = ISpeechPhraseRule.EngineConfidence

Parts

ISpeechPhraseRule
The owning object.
Single
Set: (This property is read-only)
Get: A Single variable that gets the EngineConfidence.

Example

For an example of the use of the EngineConfidence property, see the code example at the end of this section.


ISpeechPhraseRule FirstElement Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseRule

FirstElement Property

The FirstElement property returns the audio stream offset of the first phrase element in the recognition result matched by the rule.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseRule.FirstElement

Parts

ISpeechPhraseRule
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the audio stream offset of the first element.

Example

For an example of the use of the FirstElement property, see the code example at the end of this section.


ISpeechPhraseRule Id Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseRule

Id Property

The Id property returns the ID of the phrase rule.

In the Speech Text Grammar Format, this data is specified in the ID attribute of the RULE element.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseRule.Id

Parts

ISpeechPhraseRule
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the ID of the rule.

Example

For an example of the use of the Id property, see the code example at the end of this section.


ISpeechPhraseRule Name Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseRule

Name Property

The Name property returns the name of the phrase rule.

In the Speech Text Grammar Format, this data is specified in the NAME attribute of the RULE element.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechPhraseRule.Name()

Parts

ISpeechPhraseRule
The owning object.
String
Set: (This property is read-only)
Get: A String variable that gets the name of the rule.

Example

For an example of the use of the Name property, see the code example at the end of this section.


ISpeechPhraseRule NumberOfElements Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseRule

NumberOfElements Property

The NumberOfElements property returns the number of phrase elements spanned by this rule.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseRule.NumberOfElements

Parts

ISpeechPhraseRule
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the number of elements.

Example

For an example of the use of the NumberOfElements property, see the code example at the end of this section.


ISpeechPhraseRule Parent Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseRule

Parent Property

The Parent property returns the rule's parent rule.

If the rule is a top-level rule, it has no parent, and its Parent property is Nothing.

Syntax

Set: | (This property is read-only)
Get: | ISpeechPhraseRule = ISpeechPhraseRule.Parent

Parts

ISpeechPhraseRule
The owning object.
ISpeechPhraseRule
Set: (This property is read-only)
Get: An ISpeechPhraseRule object that gets the parent rule.

Example

For an example of the use of the Parent property, see the code example at the end of this section.


ISpeechPhraseRule Code Example (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechPhraseRule Code Example

The following Visual Basic form code demonstrates the use of the ISpeechPhraseRule interface. To run this code, create a form with the following controls:

  • A text box called Text1
  • A list box called List1
  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a recognizer, a recognition context and a grammar object. It loads the grammar object with the Solitaire grammar sol.xml and activates it.

The Command1 procedure speaks the text in the text box into a file for recognition. The recognition context's Recognition event displays selected information from the recognition result. It displays the phrase elements first, and then the properties of the ISpeechPhraseRule object.

Note that both the Parent and Children properties may have a value of Nothing. Attempting to reference them in this state will cause a run-time error.

Option Explicit

Const WAVEFILENAME = "C:\ISpeechPhraseRule.wav"

Dim MyRecognizer As SpeechLib.SpInprocRecognizer
Dim MyGrammar As SpeechLib.ISpeechRecoGrammar
Dim MyFileStream As SpeechLib.SpFileStream
Dim PhraseElem As SpeechLib.ISpeechPhraseElement
Dim Voice1 As SpeechLib.SpVoice
Dim Voice2 As SpeechLib.SpVoice     'Plays the wave file back

Dim WithEvents MyRecoContext As SpeechLib.SpInProcRecoContext

Private Sub Command1_Click()
    On Error GoTo EH

    List1.Clear

    ' Create ISpeechPhraseReplacement.wav file from text in text box.
    Set MyFileStream = MakeWAVFileFromText(Text1.Text, WAVEFILENAME)

    'Set the file as recognizer's input stream
    MyFileStream.Open WAVEFILENAME
    Set MyRecognizer.AudioInputStream = MyFileStream

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()

    ' Create Recognizer, RecoContext, Grammar, and Voice
    Set MyRecognizer = New SpInprocRecognizer
    Set MyRecoContext = MyRecognizer.CreateRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar(16)
    Set Voice1 = New SpVoice
    Set Voice1.Voice = Voice1.GetVoices("gender=male").Item(0)
    Set Voice2 = New SpVoice

    On Error GoTo EH

    ' Load Grammar with solitaire XML, set active
    MyGrammar.CmdLoadFromFile "C:\sol.xml", SLODynamic
    MyGrammar.CmdSetRuleIdState 0, SGDSActive               'Set MyRecoContext & MyRecoContext active
    MyGrammar.DictationSetState SGDSActive                  'Set Dictation active

    Text1.Text = "play the eight of clubs"

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub SpeakToFile(ByVal strText As String, ByVal strFName As String)

    On Error GoTo EH

    Set MyFileStream = New SpFileStream                    'Create stream
    MyFileStream.Open strFName, SSFMCreateForWrite, True   'Open as the filename
    Set Voice1.AudioOutputStream = MyFileStream                 'Set voice output to file
    Voice1.Speak strText, SVSFIsXML                  'Speak synchronously
    MyFileStream.Close                                     'Close file

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub MyRecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim X As String
    Dim ii As Integer
    Dim PR As ISpeechPhraseRule
    Dim PRs As ISpeechPhraseRules

    On Error GoTo EH

    ii = 0
    For Each PhraseElem In Result.PhraseInfo.Elements
        X = "element" & Str(ii) & ": " & PhraseElem.DisplayText
        List1.AddItem X
        ii = ii + 1
    Next

    'This is the rule that recognition was based on
    Set PR = Result.PhraseInfo.Rule

    List1.AddItem ""
    List1.AddItem "Id:               " & PR.Id
    List1.AddItem "Rule:             " & PR.Name
    List1.AddItem "NumberOfElements: " & PR.NumberOfElements
    List1.AddItem "FirstElement:     " & PR.FirstElement
    List1.AddItem "EngineConfidence: " & PR.EngineConfidence
    List1.AddItem "Confidence:       " & PR.Confidence
    List1.AddItem ""

    If PR.Parent Is Nothing Then
        List1.AddItem "Parent:           none"
    Else
        List1.AddItem "Parent:           " & PR.Parent.Name
    End If

    If PR.Children Is Nothing Then
        List1.AddItem "Children:         none"
    Else
        'This routine replaces the original PR object
        Set PRs = PR.Children
        ii = 0
        For Each PR In PRs
            List1.AddItem "Child" & Str(ii) & ":          " & PR.Name
            ii = ii + 1
        Next
    End If

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub MyRecoContext_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal StreamReleased As Boolean)

    On Error GoTo EH

    MyFileStream.Close
    DoEvents
    MyFileStream.Open WAVEFILENAME
    Voice2.SpeakStream MyFileStream
    MyFileStream.Close

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Function MakeWAVFileFromText _
   (ByVal strText As String, _
    ByVal strFName As String) _
    As SpFileStream

    On Error GoTo EH

    ' Declare identifiers:
    Dim FileStream As SpFileStream
    Dim Voice As SpVoice

    ' Instantiate Voice and FileStream objects:
    Set Voice = New SpVoice
    Set FileStream = New SpFileStream

    ' Open specified .wav file, set voice output
    ' to file, and speak synchronously:
    FileStream.Open strFName, SSFMCreateForWrite, True
    Set Voice.AudioOutputStream = FileStream
    Voice.Speak strText, SVSFIsXML

    ' Close file and return reference to FileStream object:
    FileStream.Close
    Set MakeWAVFileFromText = FileStream

EH:
    If Err.Number Then ShowErrMsg
End Function

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechPhraseRules Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechPhraseRules

The ISpeechPhraseRules automation interface represents a collection of ISpeechPhraseRule objects.

Automation Interface Elements

The ISpeechPhraseRules automation interface contains the following elements:

Properties | Description
Count Property | Returns the number of objects in the collection.
Methods | Description
Item Method | Returns a member of the collection by its index.


ISpeechPhraseRules Count Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechPhraseRules

Count Property

The Count property returns the number of ISpeechPhraseRule objects in the ISpeechPhraseRules object.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechPhraseRules.Count

Parts

ISpeechPhraseRules
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that gets the Count property.

Remarks

The ISpeechPhraseRules object is a collection of ISpeechPhraseRule objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Count property is one of these common properties.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechPhraseRules Item Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseRules

Item Method

The Item method returns a member of the ISpeechPhraseRules collection by its index.

ISpeechPhraseRules.Item(
     Index As Long
) As ISpeechPhraseRule

Parameters

Index
Specifies the Index.

Return Value

The Item method returns an ISpeechPhraseRule variable.

Remarks

The ISpeechPhraseRules object is a collection of ISpeechPhraseRule objects. As a collection, it provides access to any or all of its members through certain methods and properties common to all collection objects. The Item method is one of these common methods.

Example

See the SpObjectToken Example for a complete example and additional details.


ISpeechRecognizerStatus Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechRecognizerStatus

The ISpeechRecognizerStatus automation interface returns the status of the speech recognition (SR) engine represented by the recognizer object.

This method provides information for static elements about the SR engine such as the languages it supports. It also provides information for dynamic elements such as the engine's current stream position, and whether the stream is actively being sent to the engine.

These dynamic elements are equivalent to parameters returned by recognition context events. It may be advantageous for some applications to retrieve these elements by calling Status occasionally, rather than by receiving events constantly.

Automation Interface Elements

The ISpeechRecognizerStatus automation interface contains the following elements:

Properties | Description
AudioStatus Property | Returns the status of the recognizer's audio output.
ClsidEngine Property | Returns the unique identifier associated with the current engine.
CurrentStreamNumber Property | Returns the number of the current recognition stream.
CurrentStreamPosition Property | Returns the recognizer's position in the recognition stream, in bytes.
NumberOfActiveRules Property | Returns the current engine's number of active rules.
SupportedLanguages Property | Returns an array containing the languages the active engine supports.


ISpeechRecognizerStatus AudioStatus Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechRecognizerStatus

AudioStatus Property

The AudioStatus property returns the status of the speech recognition (SR) engine's audio output.

Syntax

Set: | (This property is read-only)
Get: | ISpeechAudioStatus = ISpeechRecognizerStatus.AudioStatus

Parts

ISpeechRecognizerStatus
The owning object.
ISpeechAudioStatus
Set: (This property is read-only)
Get: An ISpeechAudioStatus variable which gets the property.

Example

For an example of the use of the AudioStatus property, see the code example in the Recognizer Status property section.


ISpeechRecognizerStatus ClsidEngine Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechRecognizerStatus

ClsidEngine Property

The ClsidEngine property returns the unique identifier associated with the current engine.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechRecognizerStatus.ClsidEngine

Parts

ISpeechRecognizerStatus
The owning object.
String
Set: (This property is read-only)
Get: A String variable which gets the property.

Example

For an example of the use of the ClsidEngine property, see the code example in the Recognizer Status property section.


ISpeechRecognizerStatus CurrentStreamNumber Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechRecognizerStatus

CurrentStreamNumber Property

The CurrentStreamNumber property returns the number of the current recognition stream.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechRecognizerStatus.CurrentStreamNumber

Parts

ISpeechRecognizerStatus
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable which gets the property.

Example

For an example of the use of the CurrentStreamNumber property, see the code example in the Recognizer Status property section.


ISpeechRecognizerStatus CurrentStreamPosition Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechRecognizerStatus

CurrentStreamPosition Property

The CurrentStreamPosition property returns the recognizer's position in the recognition stream, in bytes.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechRecognizerStatus.CurrentStreamPosition

Parts

ISpeechRecognizerStatus
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant variable which gets the property.

Example

For an example of the use of the CurrentStreamPosition property, see the code example in the Recognizer Status property section.


ISpeechRecognizerStatus NumberOfActiveRules Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechRecognizerStatus

NumberOfActiveRules Property

The NumberOfActiveRules property returns the current engine's number of active rules.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechRecognizerStatus.NumberOfActiveRules

Parts

ISpeechRecognizerStatus
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable which gets the property.

Example

For an example of the use of the NumberOfActiveRules property, see the code example in the Recognizer Status property section.


ISpeechRecognizerStatus SupportedLanguages Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechRecognizerStatus

SupportedLanguages Property

The SupportedLanguages property returns an array containing the languages that the active engine supports.

The array contains the language ID in decimal format.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechRecognizerStatus.SupportedLanguages

Parts

ISpeechRecognizerStatus
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant data type as an array with each element containing a language ID of a supported language.

Example

For an example of the use of the SupportedLanguages property, see the code example in the Recognizer Status property section.


ISpeechRecoGrammar Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechRecoGrammar

The ISpeechRecoGrammar automation interface enables applications to manage the words and phrases for the SR engine.

A single SpRecognizer object can be associated with multiple SpRecoContext objects. Similarly, a single SpRecoContext object can be associated with multiple ISpRecoGrammar objects. This allows designers to create applications containing several grammars, each of which is specialized for a different type of recognition. Each ISpRecoGrammar object can contain both a context-free grammar (CFG) and a dictation grammar simultaneously.

Automation Interfaces

The ISpeechRecoGrammar automation interface contains the following elements:

Properties | Description
Id Property | Returns the Id assigned to the grammar when it was created.
RecoContext Property | Returns the RecoContext object that created this grammar.
Rules Property | Returns the collection of grammar rules in the RecoGrammar.
State Property | Gets and sets the operational status of the speech grammar.
Methods | Description
CmdLoadFromFile Method | Loads a command and control grammar from the specified file.
CmdLoadFromMemory Method | Loads a compiled speech grammar from memory.
CmdLoadFromObject Method | Loads a speech grammar from a COM object.
CmdLoadFromProprietaryGrammar Method | Loads a proprietary speech grammar.
CmdLoadFromResource Method | Loads a command and control grammar from a Win32 resource.
CmdSetRuleIdState Method | Activates or deactivates a rule by its rule ID.
CmdSetRuleState Method | Activates or deactivates a rule by its rule name.
DictationLoad Method | Loads a dictation topic into the grammar.
DictationSetState Method | Sets the dictation topic state.
DictationUnload Method | Unloads the active dictation topic from the grammar.
IsPronounceable Method | Determines if a word has a pronunciation.
Reset Method | Clears all grammar rules and resets the grammar's language to NewLanguage.
SetTextSelection Method | Sets the range of text selection information in a word sequence data buffer.
SetWordSequenceData Method | Defines a word sequence data buffer for use by the SR engine.


ISpeechRecoGrammar CmdLoadFromFile method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

CmdLoadFromFile Method

The CmdLoadFromFile method loads a command and control grammar from the specified file.

The grammar may be compiled or uncompiled, and it can be loaded for static or dynamic use, as specified in the LoadOption parameter.

ISpeechRecoGrammar.CmdLoadFromFile(
     FileName As String,
     [LoadOption As SpeechLoadOption = SLOStatic]
)

Parameters

FileName
Specifies the file name. SAPI 5 supports loading of compiled static grammars through a URL.
LoadOption
[Optional] Specifies whether the grammar is to be loaded for static or dynamic use. The default is static.

Return Value

None.

Example

The following Visual Basic form code demonstrates the use of the CmdLoadFromFile and the CmdLoadFromMemory methods. To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates two grammar objects and uses the CmdLoadFromFile method to load the Solitaire rules into the first grammar. The Command1_Click procedure calls a subroutine called GrammarToMemory, which creates a temporary grammar in a Variant variable, and returns this grammar to the caller. The Command1 procedure then reloads the first grammar with the temporary grammar.

Option Explicit

Dim C As SpeechLib.SpSharedRecoContext
Dim G1 As SpeechLib.ISpeechRecoGrammar
Dim G2 As SpeechLib.ISpeechRecoGrammar

Private Sub Command1_Click()
    Dim GT As Variant               'Temp grammar in Variant variable

    On Error GoTo EH

    GT = GrammarToMemory(G1)         'GT is temp version of grammar G
    Call G2.CmdLoadFromMemory(GT, SLOStatic)

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Set C = New SpSharedRecoContext
    Set G1 = C.CreateGrammar
    Set G2 = C.CreateGrammar

    Call G1.CmdLoadFromFile("c:\sol.xml", SLODynamic)

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Function GrammarToMemory(objGRM As SpeechLib.ISpeechRecoGrammar) As Variant
    On Error GoTo EH

    'Make changes to a standard grammar, and save it as temp grammar.
    'Add rules to grammar, delete rules from grammar, or other changes here.

    'Return the variant from ISpeechGrammarRules.CommitAndSave
    GrammarToMemory = objGRM.Rules.CommitAndSave("")

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar CmdLoadFromMemory Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

CmdLoadFromMemory Method

The CmdLoadFromMemory method loads a compiled speech grammar from memory.

ISpeechRecoGrammar.CmdLoadFromMemory(
     GrammarData As Variant,
     [LoadOption As SpeechLoadOption = SLOStatic]
)

Parameters

GrammarData
Specifies the GrammarData.
LoadOption
[Optional] Specifies whether the grammar is to be loaded for static or dynamic use. The default is static.

Return Value

None.

Example

The following Visual Basic form code demonstrates use of the CmdLoadFromMemory method. To run this code, create a form and paste this code into the Declarations section.

The Form_Load procedure creates a recognition context and a CFG grammar object. It adds a simple rule to the grammar, and saves the grammar data to a Variant variable with the CommitAndSave method. It then uses the CmdLoadFromMemory method to load the second grammar object with the grammar data in the Variant variable. Finally, it activates the rule in the second grammar.

If the computer has a microphone, run this code and speak the phrase, "Hello, world" into the microphone. The recognition context's Recognition and FalseRecognition event procedures display messages indicating successful or unsuccessful recognition.

Option Explicit

Dim WithEvents recoCtx As SpSharedRecoContext
Dim grammar As ISpeechRecoGrammar
Dim grammar2 As ISpeechRecoGrammar
Dim gRules As ISpeechGrammarRules
Dim gRule As ISpeechGrammarRule
Dim state As ISpeechGrammarRuleState

Dim buffer As String    ' Any error information when committing and saving the grammar
Dim gData As Variant    ' The contents of the grammar held in memory

' Typically there is no reason to do something like this.
' This is just the simplest possible example to demonstrate the use of
' ISpeechRecoGrammar.CmdLoadFromMemory.

Private Sub Form_Load()
    On Error GoTo EH

    Set recoCtx = New SpSharedRecoContext
    Set grammar = recoCtx.CreateGrammar
    Set gRules = grammar.Rules

    ' Grammar has one rule, one state, and one transition
    Set gRule = gRules.Add("greeting", SRATopLevel, 1)
    Set state = gRule.InitialState
    state.AddWordTransition Nothing, "hello world", " "

    ' Save the grammar to memory (contents saved in gData)
    gData = grammar.Rules.CommitAndSave(buffer)

    Set grammar2 = recoCtx.CreateGrammar                'Second grammar
    grammar2.CmdLoadFromMemory gData, SLOStatic         'Load from memory
    grammar2.CmdSetRuleState "greeting", SGDSActive     'Set rule active

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub recoCtx_FalseRecognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    ' Gets here only when the phrase "hello world" is falsely recognized
    MsgBox "(not recognized!)"

End Sub

Private Sub recoCtx_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    On Error GoTo EH

    ' Gets here only when the phrase "hello world" is recognized
    MsgBox Result.PhraseInfo.GetText

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar CmdLoadFromObject Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

CmdLoadFromObject Method

The CmdLoadFromObject method loads a speech grammar from a component object model (COM) object.

The COM object must be created from a Windows dynamic link library (DLL).

ISpeechRecoGrammar.CmdLoadFromObject(
     ClassId As String,
     GrammarName As String,
     [LoadOption As SpeechLoadOption = SLOStatic]
)

Parameters

ClassId
Specifies The reference class ID of the object containing the command.
GrammarName
Specifies the GrammarName.
LoadOption
[Optional] Specifies whether the grammar is to be loaded for static or dynamic use. The default is static.

Return Value

None.


ISpeechRecoGrammar CmdLoadFromProprietaryGrammar Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

CmdLoadFromProprietaryGrammar Method

The CmdLoadFromProprietaryGrammar method loads a proprietary speech grammar.

ISpeechRecoGrammar.CmdLoadFromProprietaryGrammar(
     ProprietaryGuid As String,
     ProprietaryString As String,
     ProprietaryData As Variant,
     [LoadOption As SpeechLoadOption = SLOStatic]
)

Parameters

ProprietaryGuid
Specifies the GUID of the grammar, which is used by the application and the speech recognition engine to identify it for verifying support.
ProprietaryString
A command string used to send information about the grammar.
ProprietaryData
Additional information for the process.
LoadOption
[Optional] Specifies whether the grammar is to be loaded for static or dynamic use. The default is static. In the case of CmdLoadFromProprietaryGrammar, static loading must be used.

Return Value

None.

Remarks

Using this method will unload the currently loaded context-free grammar or proprietary grammar.


ISpeechRecoGrammar CmdLoadFromResource Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

CmdLoadFromResource Method

The CmdLoadFromResource method loads a command and control grammar from a Win32 resource.

ISpeechRecoGrammar.CmdLoadFromResource(
     hModule As Long,
     ResourceName As Variant,
     ResourceType As Variant,
     LanguageId As Long,
     [LoadOption As SpeechLoadOption = SLOStatic]
)

Parameters

hModule
Specifies the hModule.
ResourceName
Specifies the ResourceName.
ResourceType
Specifies the ResourceType.
LanguageId
Specifies the LanguageId.
LoadOption
[Optional] Specifies whether the grammar is to be loaded for static or dynamic use. The default is static.

Return Value

None.

Remarks

The grammar resource must be a compiled SAPI 5 binary version of a context-free grammar (CFG).

Using this method will unload the currently loaded CFG or proprietary grammar.

Example

The following Visual Basic form code demonstrates the use of the CmdLoadFromResource method. Before attempting to run this code, you must:

  • Create a SpeechDocs.dll file, and
  • Make sure your microphone is connected and functional.

The Form_Load procedure creates a grammar object and loads it with the compiled Solitaire grammar contained in the DLL. There are no controls on this form; simply speak into your microphone. Phrases like "Move the red ten" or "Play the queen of hearts" will be recognized.

Option Explicit

Dim WithEvents MyRecoContext As SpSharedRecoContext
Dim MyGrammar As ISpeechRecoGrammar
Dim RsrcHandle As Long

' Change this constant to match the path
' of the SpeechDocs DLL on your machine!
Const Lib As String = "C:\SpeechDocs.dll"
Const RsrcType As String = "CFGGRAMMAR"
Const RsrcName  As Long = 101
Const LangID As Long = &H409

Private Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" _
    (ByVal lpLibFileName As String) As Long

Private Sub Form_Load()
    On Error GoTo EH

    Set MyRecoContext = New SpSharedRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar

    ' Obtain a handle to the executable holding the grammar as a resource
    RsrcHandle = LoadLibrary(Lib)

    ' Load the grammar from the resource
    MyGrammar.CmdLoadFromResource RsrcHandle, RsrcName, RsrcType, LangID, SLOStatic

    ' Set all DefaultToActive rules active
    ' NOTE: The solitaire grammar happens to have DefaultToActive rules
    ' which is why we can activate them this way.
    MyGrammar.CmdSetRuleState "", SGDSActive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub MyRecoContext_FalseRecognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal result As SpeechLib.ISpeechRecoResult)

    MsgBox "(not recognized!)"

End Sub

Private Sub MyRecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal result As SpeechLib.ISpeechRecoResult)

    On Error GoTo EH
    MsgBox result.PhraseInfo.GetText

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar CmdSetRuleIdState method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

CmdSetRuleIdState Method

The CmdSetRuleIdState method activates or deactivates a rule by its rule ID.

ISpeechRecoGrammar.CmdSetRuleIdState(
     RuleId As Long,
     State As SpeechRuleState
)

Parameters

RuleId
The Id of the rule to be changed. If Id is zero, all TopLevel and Active rules in the grammar will be changed.
State
The rule state to which the rule or rules will be changed.

Return Value

None.

Example

The following Visual Basic form code demonstrates the use of the Rules method, the CmdSetRuleState method and the CmdSetRuleIdState method. To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form1_Load procedure creates a grammar and loads it with the solitaire grammar sol.xml, and uses the Rules method to create a collection of the rules contained in the grammar. The Command1_Click procedure creates an ISpeechGrammarRule object for the first rule contained in the grammar, and deactivates this rule using the CmdSetRuleState method and the rule's Name property. The procedure then creates an ISpeechGrammarRule object for the second rule, and deactivates that rule using the CmdSetRuleIdState method and the rule's ID property.

Another example of the use of CmdSetRuleIdState can be found in the code example for the CmdLoadFromMemory method.

Option Explicit

Dim MyRecoContext As SpeechLib.SpSharedRecoContext
Dim MyGrammar As SpeechLib.ISpeechRecoGrammar
Dim Rules As SpeechLib.ISpeechGrammarRules

Dim Rule As SpeechLib.ISpeechGrammarRule

Private Sub Command1_Click()
    On Error GoTo EH

    'Get first rule in rules collection and set it inactive
    'Use CmdSetRuleState method and the rule NAME.

    Set Rule = Rules.Item(0)
    MyGrammar.CmdSetRuleState Rule.Name, SGDSInactive

    'Get next rule in rules collection and set it inactive, too
    'Use CmdSetRuleIdState method and the rule ID.

    Set Rule = Rules.Item(1)
    MyGrammar.CmdSetRuleIdState Rule.Id, SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Set MyRecoContext = New SpSharedRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar

    'Load Solitaire grammar dynamically so it can be changed.
    Call MyGrammar.CmdLoadFromFile("c:\sol.xml", SLODynamic)

    Set Rules = MyGrammar.Rules     'Get the collection of rules

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar CmdSetRuleState method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

CmdSetRuleState Method

The CmdSetRuleState method activates or deactivates a rule by its name.

ISpeechRecoGrammar.CmdSetRuleState(
     Name As String,
     State As SpeechRuleState
)

Parameters

Name
The name of the rule to be changed. If Name is an empty string (""), all TopLevel and Active rules in the grammar will be changed.
State
The rule state to which the rule or rules will be changed.

Return Value

None.

Example

The following Visual Basic form code demonstrates the use of the Rules method, the CmdSetRuleState method and the CmdSetRuleIdState method. To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form1_Load procedure creates a grammar and loads it with the solitaire grammar sol.xml, and uses the Rules method to create a collection of the rules contained in the grammar. The Command1_Click procedure creates an ISpeechGrammarRule object for the first rule contained in the grammar, and inactivates this rule using the CmdSetRuleState method and the rule's Name property. The procedure then creates an ISpeechGrammarRule object for the second rule, and inactivates that rule using the CmdSetRuleIdState method and the rule's ID property.

Option Explicit

Dim MyRecoContext As SpeechLib.SpSharedRecoContext
Dim MyGrammar As SpeechLib.ISpeechRecoGrammar
Dim Rules As SpeechLib.ISpeechGrammarRules

Dim Rule As SpeechLib.ISpeechGrammarRule

Private Sub Command1_Click()
    On Error GoTo EH

    'Get first rule in rules collection and set it inactive
    'Use CmdSetRuleState method and the rule NAME.

    Set Rule = Rules.Item(0)
    MyGrammar.CmdSetRuleState Rule.Name, SGDSInactive

    'Get next rule in rules collection and set it inactive, too
    'Use CmdSetRuleIdState method and the rule ID.

    Set Rule = Rules.Item(1)
    MyGrammar.CmdSetRuleIdState Rule.Id, SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Set MyRecoContext = New SpSharedRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar

    'Load Solitaire grammar dynamically so it can be changed.
    Call MyGrammar.CmdLoadFromFile("c:\sol.xml", SLODynamic)

    Set Rules = MyGrammar.Rules     'Get the collection of rules

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar DictationLoad method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

DictationLoad Method

The DictationLoad method loads a dictation topic into the grammar.

ISpeechRecoGrammar.DictationLoad(
     [TopicName As String = ""],
     [LoadOption As SpeechLoadOption = SLOStatic]
)

Parameters

TopicName
[Optional] Specifies a dictation topic. The default value is the empty string.
LoadOption
[Optional] Specifies whether the grammar is to be loaded for static or dynamic use. The default is static.

Return Value

None.

Remarks

SAPI currently defines one specialized dictation topic: SPTOPIC_SPELLING. SR engines are not required to support specialized dictation topics (including spelling). When using another manufacturer's SR engine, consult its documentation for details.

Example

The following Visual Basic form code demonstrates the use of the DictationLoad, DictationSetState, and DictationUnload methods. It creates a grammar, configures the grammar to perform both dictation and command and control (C and C) recognition, and toggles between the two types of recognition.

To run this code, create a form with a command button called Command1 and paste this code into the Declarations section of the form. The Form_Load procedure creates a grammar object, associates it with the system dictation lexicon and the Solitaire C and C grammar, and begins recognition in dictation mode. The Command1_Click procedure toggles the recognition mode between dictation and C and C. The Form_Unload procedure unloads the dictation grammar and inactivates the C and C grammar.

Option Explicit

Dim MyRecoContext As SpeechLib.SpSharedRecoContext
Dim MyGrammar As SpeechLib.ISpeechRecoGrammar

Private Sub Command1_Click()
    On Error GoTo EH

    If Command1.Caption = "&Dictation" Then
        MyGrammar.CmdSetRuleIdState 0, SGDSInactive     'C&C off
        MyGrammar.DictationSetState SGDSActive          'Dictation on
        Command1.Caption = "&C and C"
    Else
        MyGrammar.DictationSetState SGDSInactive        'Dictation off
        MyGrammar.CmdSetRuleIdState 0, SGDSInactive     'C&C on
        Command1.Caption = "&Dictation"
    End If

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    'Create a RecoContext and its Grammar
    Set MyRecoContext = New SpSharedRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar

    'Get dictation grammar and set it inactive
    MyGrammar.DictationLoad "", SLOStatic
    MyGrammar.DictationSetState SGDSInactive

    'Get Command & Control grammar, and set it inactive
    MyGrammar.CmdLoadFromFile "C:\SOL.XML", SLOStatic
    MyGrammar.CmdSetRuleIdState 0, SGDSInactive

    'Set dictation active and set up Command1.Caption
    MyGrammar.DictationSetState SGDSActive
    Command1.Caption = "&C and C"

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Unload(Cancel As Integer)
    On Error GoTo EH

    MyGrammar.DictationUnload
    MyGrammar.CmdSetRuleIdState 0, SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifier:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar DictationSetState method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

DictationSetState Method

The DictationSetState method sets the dictation topic state.

ISpeechRecoGrammar.DictationSetState(
     State As SpeechRuleState
)

Parameters

State
A SpeechRuleState constant that specifies the dictation topic state.

Return Value

None.

Example

The following Visual Basic form code demonstrates the use of the DictationLoad, DictationSetState, and DictationUnload methods. It creates a grammar, configures the grammar to perform both dictation and command and control (C and C) recognition, and toggles between the two types of recognition.

To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a grammar object, associates it with the system dictation lexicon and the Solitaire C and C grammar, and begins recognition in dictation mode. The Command1_Click procedure toggles the recognition mode between dictation and C and C. The Form_Unload procedure unloads the dictation grammar and deactivates the C and C grammar.

Option Explicit

Dim MyRecoContext As SpeechLib.SpSharedRecoContext
Dim MyGrammar As SpeechLib.ISpeechRecoGrammar

Private Sub Command1_Click()
    On Error GoTo EH

    If Command1.Caption = "&Dictation" Then
        MyGrammar.CmdSetRuleIdState 0, SGDSInactive     'C&C off
        MyGrammar.DictationSetState SGDSActive          'Dictation on
        Command1.Caption = "&C and C"
    Else
        MyGrammar.DictationSetState SGDSInactive        'Dictation off
        MyGrammar.CmdSetRuleIdState 0, SGDSInactive     'C&C on
        Command1.Caption = "&Dictation"
    End If

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    'Create a RecoContext and its Grammar
    Set MyRecoContext = New SpSharedRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar

    'Get dictation grammar and set it inactive
    MyGrammar.DictationLoad "", SLOStatic
    MyGrammar.DictationSetState SGDSInactive

    'Get Command & Control grammar, and set it inactive
    MyGrammar.CmdLoadFromFile "C:\SOL.XML", SLOStatic
    MyGrammar.CmdSetRuleIdState 0, SGDSInactive

    'Set dictation active and set up Command1.Caption
    MyGrammar.DictationSetState SGDSActive
    Command1.Caption = "&C and C"

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Unload(Cancel As Integer)
    On Error GoTo EH

    MyGrammar.DictationUnload
    MyGrammar.CmdSetRuleIdState 0, SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifier:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar DictationUnload method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

DictationUnload Method

The DictationUnload method unloads the active dictation topic from the grammar.

ISpeechRecoGrammar.DictationUnload()

Parameters

None.

Return Value

None.

Example

The following Visual Basic form code demonstrates the use of the DictationLoad, DictationSetState, and DictationUnload methods. It creates a grammar, configures the grammar to perform both dictation and command and control (C and C) recognition, and toggles between the two types of recognition.

To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a grammar object, associates it with the system dictation lexicon and the Solitaire C and C grammar, and begins recognition in dictation mode. The Command1_Click procedure toggles the recognition mode between dictation and C and C. The Form_Unload procedure unloads the dictation grammar and deactivates the C and C grammar.

Option Explicit

Dim MyRecoContext As SpeechLib.SpSharedRecoContext
Dim MyGrammar As SpeechLib.ISpeechRecoGrammar

Private Sub Command1_Click()
    On Error GoTo EH

    If Command1.Caption = "&Dictation" Then
        MyGrammar.CmdSetRuleIdState 0, SGDSInactive     'C&C off
        MyGrammar.DictationSetState SGDSActive          'Dictation on
        Command1.Caption = "&C and C"
    Else
        MyGrammar.DictationSetState SGDSInactive        'Dictation off
        MyGrammar.CmdSetRuleIdState 0, SGDSInactive     'C&C on
        Command1.Caption = "&Dictation"
    End If

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    'Create a RecoContext and its Grammar
    Set MyRecoContext = New SpSharedRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar

    'Get dictation grammar and set it inactive
    MyGrammar.DictationLoad "", SLOStatic
    MyGrammar.DictationSetState SGDSInactive

    'Get Command & Control grammar, and set it inactive
    MyGrammar.CmdLoadFromFile "C:\SOL.XML", SLOStatic
    MyGrammar.CmdSetRuleIdState 0, SGDSInactive

    'Set dictation active and set up Command1.Caption
    MyGrammar.DictationSetState SGDSActive
    Command1.Caption = "&C and C"

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Unload(Cancel As Integer)
    On Error GoTo EH

    MyGrammar.DictationUnload
    MyGrammar.CmdSetRuleIdState 0, SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifier:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar Id property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

Id Property

The Id property returns the ID assigned to the grammar when it was created.

Syntax

Set: | Not available.
Get: | Variant = ISpeechRecoGrammar.Id

Parts

ISpeechRecoGrammar
The owning object.
Variant
Set: (This property is read-only).
Get: A Variant variable that gets the property value.

Example

The following Visual Basic form code demonstrates the use of the ID and RecoContext properties. To run this code, create a form with the following controls:

  • Two command buttons called Command1 and Command2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a recognition context with two ISpeechRecoGrammar objects. The ISpeechRecoGrammar objects are created with ID properties of 6 and 7. The Command1 and Command2 procedures each send one of the grammar objects to the GrammarSub procedure as parameters. The GrammarSub procedure displays the ID of the grammar object parameter, and uses the parameter's RecoContext property to pause and resume the recognition context that owns the grammar.

There is no special significance to the Id property values of 6 or 7; these values are arbitrary. Additionally, the Pause and Resume methods in the GrammarSub procedure are intended simply to show how the grammar's RecoContext property provides access to the methods and properties of the recognition context which owns the grammar.

Option Explicit

Dim RecoContext As SpeechLib.SpSharedRecoContext
Dim objGR1 As SpeechLib.ISpeechRecoGrammar
Dim objGR2 As SpeechLib.ISpeechRecoGrammar

Private Sub Command1_Click()
    Call GrammarSub(objGR1)
End Sub

Private Sub Command2_Click()
    Call GrammarSub(objGR2)
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Set RecoContext = New SpSharedRecoContext
    Set objGR1 = RecoContext.CreateGrammar(6)       'Create grammar with ID = 6
    Set objGR2 = RecoContext.CreateGrammar("7")     'Create grammar with ID = 7

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub GrammarSub(G As SpeechLib.ISpeechRecoGrammar)
    On Error GoTo EH

    G.RecoContext.Pause     'Pause the RecoContext that owns grammar
    MsgBox G.Id             'Display the Id
    G.RecoContext.Resume    'Resume the RecoContext

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifier:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar IsPronounceable method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

IsPronounceable Method

The IsPronounceable method determines if a word has a pronunciation.

Additionally, the SpeechWordPronounceable constant returned by this method indicates whether the word exists in the grammar object's lexicon. Words are likely to be pronounceable even if they are not found in the lexicon.

ISpeechRecoGrammar.IsPronounceable(
     Word As String
) As SpeechWordPronounceable

Parameters

Word
Specifies the Word.

Return Value

A SpeechWordPronounceable constant.

Example

The following Visual Basic form code demonstrates the use of the IsPronounceable method.

To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a grammar and loads the general dictation topic. The Command1_Click procedure passes the word or words in Text1 to the IsPronounceable method and displays the resulting SpeechWordPronounceable constant.

Most correctly spelled words will be known and pronounceable; most incorrectly spelled words will be unknown and pronounceable. The example begins with a word which is pronounceable, even though it is misspelled.

Option Explicit

Dim MyRecoContext As SpeechLib.SpSharedRecoContext
Dim MyGrammar As SpeechLib.ISpeechRecoGrammar

Private Sub Command1_Click()
    On Error GoTo EH

    Dim strTemp As String

    Select Case MyGrammar.IsPronounceable(Text1.Text)
        Case SWPKnownWordPronounceable
            strTemp = "KnownWordPronounceable"
        Case SWPUnknownWordPronounceable
            strTemp = "UnknownWordPronounceable"
        Case SWPUnknownWordUnpronounceable
            strTemp = "UnknownWordUnpronounceable"
    End Select

    MsgBox "The word """ & Text1.Text & """ is " & strTemp

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Set MyRecoContext = New SpSharedRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar

    MyGrammar.DictationLoad ""

    Text1.Text = "missspeled"

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifier:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar RecoContext property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

RecoContext Property

The RecoContext property returns the RecoContext object that created the grammar.

Syntax

Set: | Not available.
Get: | ISpeechRecoContext = ISpeechRecoGrammar.RecoContext

Parts

ISpeechRecoGrammar
The owning object.
ISpeechRecoContext
Set: (This property is read-only).
Get: An ISpeechRecoContext object which instantiates the RecoContext object that created the grammar.

Example

The following Visual Basic form code demonstrates the use of the Id and RecoContext properties. To run this code, create a form with the following controls:

  • Two command buttons called Command1 and Command2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a recognition context with two ISpeechRecoGrammar objects. The ISpeechRecoGrammar objects are created with Id properties of 6 and 7. The Command1 and Command2 procedures each send one of the grammar objects to the GrammarSub procedure as parameters. The GrammarSub procedure displays the ID of the grammar object parameter, and uses the parameter's RecoContext property to pause and resume the recognition context that owns the grammar.

There is no special significance to the Id property values of 6 or 7; these values are arbitrary. Additionally, the Pause and Resume methods in the GrammarSub procedure are intended simply to show how the grammar's RecoContext property provides access to the methods and properties of the recognition context that created the grammar.

Option Explicit

Dim RecoContext As SpeechLib.SpSharedRecoContext
Dim objGR1 As SpeechLib.ISpeechRecoGrammar
Dim objGR2 As SpeechLib.ISpeechRecoGrammar

Private Sub Command1_Click()
    Call GrammarSub(objGR1)
End Sub

Private Sub Command2_Click()
    Call GrammarSub(objGR2)
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Set RecoContext = New SpSharedRecoContext
    Set objGR1 = RecoContext.CreateGrammar(6)       'Create grammar with ID = 6
    Set objGR2 = RecoContext.CreateGrammar("7")     'Create grammar with ID = 7

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub GrammarSub(G As SpeechLib.ISpeechRecoGrammar)
    On Error GoTo EH

    G.RecoContext.Pause     'Pause the RecoContext that owns grammar
    MsgBox G.Id             'Display the Id
    G.RecoContext.Resume    'Resume the RecoContext

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifier:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar Reset Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

Reset Method

The Reset method clears all grammar rules and resets the grammar's language to NewLanguage.

ISpeechRecoGrammar.ResetGrammar(
     [NewLanguage As Long = 0]
)

Parameters

NewLanguage
[Optional] Specifies the ID of the new language. The default value is zero.

Return Value

None.

Example

For an example of the use of the Reset method, see the CmdLoadFromMemory method.


ISpeechRecoGrammar Rules property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

Rules Property

The Rules property returns the collection of grammar rules contained in the RecoGrammar.

Syntax

Set: | Not available.
Get: | ISpeechGrammarRules = ISpeechRecoGrammar.Rules

Parts

ISpeechRecoGrammar
The owning object.
ISpeechGrammarRules
Set: (This property is read-only).
Get: An ISpeechGrammarRules variable which contains the grammar's rules.

Example

The following Visual Basic form code demonstrates the use of the Rules method, the CmdSetRuleState method and the CmdSetRuleIdState method. To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form1_Load procedure creates a grammar and loads it with the solitaire grammar sol.xml, and uses the Rules method to create a collection of the rules contained in the grammar. The Command1_Click procedure creates an ISpeechGrammarRule object for the first rule contained in the grammar, and deactivates this rule using the CmdSetRuleState method and the rule's Name property. The procedure then creates an ISpeechGrammarRule object for the second rule, and deactivates that rule using the CmdSetRuleIdState method and the rule's Id property.

Option Explicit

Dim MyRecoContext As SpeechLib.SpSharedRecoContext
Dim MyGrammar As SpeechLib.ISpeechRecoGrammar
Dim Rule As SpeechLib.ISpeechGrammarRule
Dim Rules As SpeechLib.ISpeechGrammarRules

Private Sub Command1_Click()
    On Error GoTo EH

    'Get first rule in rules collection and set it inactive
    'Use CmdSetRuleState method and the rule NAME

    Set Rule = Rules.Item(0)
    MyGrammar.CmdSetRuleState Rule.Name, SGDSInactive

    'Get next rule in rules collection and set it inactive, too
    'Use CmdSetRuleIdState method and the rule ID

    Set Rule = Rules.Item(1)
    MyGrammar.CmdSetRuleIdState Rule.Id, SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Set MyRecoContext = New SpSharedRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar

    'Load the Solitaire grammar dynamically so it can be changed.
    Call MyGrammar.CmdLoadFromFile("c:\sol.xml", SLODynamic)

    Set Rules = MyGrammar.Rules     'Get the collection of rules

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifier:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar SetTextSelection Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

SetTextSelection Method

The SetTextSelection method sets the range of text selection information in a WordSequenceData buffer.

The SetWordSequenceData method sends application-specific data to the speech recognition (SR) engine for recognition. The SetTextSelection method describes the part of that text which has been selected by the user with a mouse or keyboard.

ISpeechRecoGrammar.SetTextSelection(
     Info As SpTextSelectionInformation
)

Parameters

Info
An SpTextSelectionInformation object which specifies the text selection range.

Return Value

None.

Example

For an example of the use of the SetTextSelection method, see the SetWordSequenceData section.


ISpeechRecoGrammar SetWordSequenceData Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

SetWordSequenceData Method

The SetWordSequenceData method defines a word sequence buffer for use by the speech recognition (SR) engine.

Some recognition grammars specify every word and phrase that they are capable of recognizing. The Solitaire grammar is one of these; it contains only a small amount of data, and all its data elements were known to the grammar designer. But it would be impractical to create such a grammar for a speech-enabled order-entry system handling several hundred thousand inventory items.

In order to eliminate the need to specify every recognizable word in a grammar, yet still maintain the high quality of rule-based recognition, SAPI provides applications with a means to link the grammar to application-specific and user-specific data. An order-entry application could display the text for several inventory items on a user's monitor, and send this text to the engine for recognition. When a user spoke a part number, the engine would more easily recognize it from the few words on the user's screen than from thousands of part numbers specified in a grammar.

To accomplish this, the SR engine maintains a text buffer which is associated with the XML grammar tag <TEXTBUFFER>. When the recognition process arrives at a <TEXTBUFFER> tag, it expects that the application has placed text in this buffer, and that the user's speech represents one word or phrase out of the words and phrases in the buffer. If recognition is successful, the words or phrases selected from the buffer are recognized as if they had been specified in the grammar rule literally.

The SetWordSequenceData method sends this text to the engine's buffer. It is associated with the SetTextSelection method, which describes the range of text the user has selected with the mouse. The SetWordSequenceData method always sends selection data with the text data, because changing the text in the buffer invalidates the previous selection data. The SetTextSelection method sends selection data only.

ISpeechRecoGrammar.SetWordSequenceData(
     Text As String,
     TextLength As Long,
     Info As SpTextSelectionInformation
)

Parameters

Text
Specifies the text.
TextLength
Specifies the length of the text.
Info
An SpTextSelectionInformation object which specifies the text selection range.

Return Value

None.

Example

The following Visual Basic form code demonstrates the use of the SetWordSequenceData and SetTextSelection methods. To run this code, create a form with the following controls:

  • A text box called Text1
  • A list box called List1
  • A command button called Command1

Paste this code into the Declarations section of the form.

Because selecting data in the text box is an important visual part of this example, the HideSelection property of the text box should be set to False.

The Form_Load procedure creates a recognizer, a recognition context, and a grammar object. It fills the text box with the names of several types of animals. It writes an XML grammar file which contains a grammar rule using a text tag. The rule expects a sentence like "Send me a *," where "*" is a type of animal listed in the text box.

Double-click on an animal type in the text box to select it, and then click Command1. The Command1 procedure gets the selected animal type and builds a sentence such as, "Send me a hamster," or "Send me a chinchilla." If no animal type is selected in the text box, the sample uses the first animal listed. The procedure then speaks the sentence into a wave file and sends the file to the recognition context for recognition.

The Recognition event procedure displays some of the recognition data in the list box. It first determines if the recognition result satisfied a grammar rule; if so, it displays the name of the rule. In this case, PETS is the only rule that can be satisfied. The procedure then displays the individual phrase elements of the sentence.

Option Explicit

Const WAVEFILENAME = "C:\SetWordSequenceData.wav"
Const XMLFILENAME = "C:\texttag.xml"

Dim MyRecognizer As SpeechLib.SpInprocRecognizer
Dim MyGrammar As SpeechLib.ISpeechRecoGrammar
Dim MyFileStream As SpeechLib.SPFileStream
Dim PhraseElem As SpeechLib.ISpeechPhraseElement
Dim Voice1 As SpeechLib.SpVoice
Dim Voice2 As SpeechLib.SpVoice     'Plays the wave file back
Dim TextSelectInfo As SpeechLib.SpTextSelectionInformation

Dim WithEvents RecoContext As SpeechLib.SpInProcRecoContext

Private Sub Form_Load()
    On Error GoTo EH

    ' Create Recognizer, RecoContext, Grammar, and Voices:
    Set MyRecognizer = New SpInprocRecognizer
    Set RecoContext = MyRecognizer.CreateRecoContext
    Set MyGrammar = RecoContext.CreateGrammar()
    Set Voice1 = New SpVoice
    Set Voice1.Voice = Voice1.GetVoices("gender=male").Item(0)
    Set Voice2 = New SpVoice
    Set TextSelectInfo = New SpeechLib.SpTextSelectionInformation

    ' Write a grammar with a transition and then use it:
    Call WriteGrammar(XMLFILENAME)
    MyGrammar.CmdLoadFromFile XMLFILENAME, SLOStatic

    ' Set command-and-control grammar and dictation active:
    MyGrammar.CmdSetRuleIdState 0, SGDSActive
    MyGrammar.DictationSetState SGDSActive

    Text1.HideSelection = False
    Text1.Text = "pony dog cat mouse rabbit hamster chinchilla parrot turtle"

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub WriteGrammar(strFName)

    On Error GoTo EH

    Open strFName For Output As #1
    Print #1, "<GRAMMAR>"
    Print #1, " <RULE NAME=""PETS"" TOPLEVEL=""ACTIVE"">"
    Print #1, "   <O>please</O>"
    Print #1, "   <P>send me a</P>"
    Print #1, "   <TEXTBUFFER/>"    '<-- Calls for WordSequenceData
    Print #1, " </RULE>"
    Print #1, "</GRAMMAR>"
    Close #1

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub SetTextSelection(T As Control)
    On Error GoTo EH

    TextSelectInfo.ActiveOffset = 0                    'Start of text
    TextSelectInfo.ActiveLength = Len(T.Text)          'Length of text
    TextSelectInfo.SelectionOffset = T.SelStart + 1    'Start of selected text
    TextSelectInfo.SelectionOffset = T.SelLength       'Length of selected text
    MyGrammar.SetTextSelection TextSelectInfo        'Send text-selection data to SR engine

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub SetWordSequenceData(T As Control)
    On Error GoTo EH

    Call SetTextSelection(T)                        'Set up text-selection data
    MyGrammar.SetWordSequenceData T.Text, Len(T.Text), TextSelectInfo  'Send the text itself to engine

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()
    Dim W As String

    On Error GoTo EH

    'Get selected word for voice to speak
    If Text1.SelLength Then
        W = Mid(Text1.Text, Text1.SelStart + 1, Text1.SelLength)
    Else
        W = "pony"
    End If
    W = "send me a " & W    'Voice speaks this string

    'Send buffer text and selection data to engine
    Call SetWordSequenceData(Text1)

    List1.Clear
    Set MyFileStream = MakeWAVFileFromText(W, WAVEFILENAME)
    MyFileStream.Open WAVEFILENAME
    Set MyRecognizer.AudioInputStream = MyFileStream

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim X As String
    Dim ii As Integer

    On Error GoTo EH

    If Not Result.PhraseInfo.Rule.Name = "" Then
        List1.AddItem "   Result matches rule """ & Result.PhraseInfo.Rule.Name & """"
    End If

    ii = 0
    For Each PhraseElem In Result.PhraseInfo.Elements
        X = "element " & Format(ii, "00") & ": " & PhraseElem.DisplayText
        List1.AddItem X
        ii = ii + 1
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal StreamReleased As Boolean)

    On Error GoTo EH
    MyFileStream.Close
    DoEvents
    MyFileStream.Open WAVEFILENAME
    Voice2.SpeakStream MyFileStream
    MyFileStream.Close

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Function MakeWAVFileFromText _
   (ByVal strText As String, _
    ByVal strFName As String) _
    As SPFileStream

    On Error GoTo EH

    ' Declare identifiers:
    Dim FileStream As SPFileStream
    Dim Voice As SpVoice

    ' Instantiate Voice and FileStream objects:
    Set Voice = New SpVoice
    Set FileStream = New SPFileStream

    ' Open specified .wav file, set voice output
    ' to file, and speak synchronously:
    FileStream.Open strFName, SSFMCreateForWrite, True
    Set Voice.AudioOutputStream = FileStream
    Voice.Speak strText, SVSFIsXML

    ' Close file and return reference to FileStream object:
    FileStream.Close
    Set MakeWAVFileFromText = FileStream

EH:
    If Err.Number Then ShowErrMsg
End Function

Private Sub ShowErrMsg()

    ' Declare identifier:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoGrammar State Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoGrammar

State Property

The State property gets and sets the operational status of the speech grammar.

The status consists of a SpeechGrammarState constant; its three states can be summarized as enabled, disabled, and exclusive.

Syntax

Set: | ISpeechRecoGrammar.State = SpeechGrammarState
Get: | SpeechGrammarState = ISpeechRecoGrammar.State

Parts

ISpeechRecoGrammar
The owning object.
SpeechGrammarState
Set: A SpeechGrammarState constant that sets the property.
Get: A SpeechGrammarState constant that gets the property.

Example

The following Visual Basic form code demonstrates the use of the State property. The grammar is disabled while the CmdLoadFromFile method loads the grammar, and enabled when the load has completed.

To run this code, create a form (it need not have any controls) and paste the code into the Declarations section of the form.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Dim MyRecoContext As SpeechLib.SpSharedRecoContext
    Dim MyGrammar As SpeechLib.ISpeechRecoGrammar

    Set MyRecoContext = New SpSharedRecoContext
    Set MyGrammar = MyRecoContext.CreateGrammar()

    MyGrammar.State = SGSDisabled       'Disable grammar while loading

    MyGrammar.CmdLoadFromFile ("c:\sol.xml")

    MyGrammar.State = SGSEnabled        'Re-enable when done loading

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifier:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoResult Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechRecoResult

The ISpeechRecoResult automation interface returns information about a recognition attempt.

A recognition result is returned by a recognition context in the three following cases:

  • A successful recognition
  • An intermediate recognition (also called a hypothesis)
  • An unsuccessful recognition (or a false recognition)

A successful recognition is a word or phrase that surpasses a predetermined confidence rating. It is considered to be accurate enough to be passed back to the user as the text that was actually spoken. A hypothesis is an intermediate step toward recognition. The text has been parsed and examined and is available to the user for closer examination. Any number of hypotheses may be produced during a recognition attempt. A hypothesis may not reflect the final recognition and should not be used to predict it. A false recognition is a recognized word or phrase that does not meet or exceed a predetermined confidence rating. The false recognition will still contain a valid recognition result including text representing the speech. However, the text was not able to meet confidence criteria. Any of the following can contribute to a false recognition:

  • Background noise
  • Inexact pronunciation
  • Uncommon words
  • Unusual sequence of words

Any one of the three recognition types above is treated the same for a recognition result. A valid recognition result is returned by SAPI and its content may be examined. Information includes the phrase itself, the owning recognition context, the audio format (if the audio was retained) and other properties in this class.

Automation Interface Elements

The ISpeechRecoResult automation interface contains the following elements:

Properties | Description
AudioFormat Property | Gets or sets the audio stream format.
PhraseInfo Property | Returns an ISpeechPhraseInfo structure containing detailed information about the last recognized phrase.
RecoContext Property | Retrieves the current ISpeechRecoContext for the recognizer.
Times Property | Retrieves the time information associated with the result.
Methods | Description
Alternates Method | Returns a list of alternative words.
Audio Method | Creates an audio stream from the audio data in the result object.
DiscardResultInfo Method | Discards the requested data from a phrase object.
SaveToMemory Method | Saves the phrase portion of the recognition result to memory.
SpeakAudio Method | Plays the audio sequence containing the recognized phrase.


ISpeechRecoResult Alternates Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResult

Alternates Method

The Alternates method returns a list of alternate words.

Many recognitions, successful or not, frequently return several words or phrases that closely match the spoken sequence. The one most nearly matching the sequence with a high confidence level is returned as a successful recognition. The other words and phrases are returned as alternates that are available for examination.

ISpeechRecoResult.Alternates(
     RequestCount As Long,
     [StartElement As Long = 0],
     [Elements As Long = -1]
) As ISpeechPhraseAlternates

Parameters

RequestCount
Specifies the maximum number of alternates to retrieve, which must be greater than zero. Any number of alternates may be chosen and will be returned in descending order of confidence. That is, the first alternate returned has the highest confidence and will most likely be the word or phrase chosen by the successful recognition. The second alternate returned will be the next most likely choice, and the last alternate returned the least likely match.
StartElement
[Optional] Specifies which element to use as a starting point. If omitted, zero is used and indicates the first alternate as the starting point. Because it is zero based, the second element would be one.
Elements
[Optional] Specifies the number of elements to retrieve. Default is -1, which specifies all alternate elements are retrieved.

Return Value

The Alternates method returns an ISpeechPhraseAlternates variable.

Remarks

ISpeechRecoResult.Alternates applies only to dictation grammar. Command and control alternates are handled separately and independently. See ISpeechRecoContext.CmdMaxAlternates for command and control alternates.

Example

The following Visual Basic form code returns the 6 most likely matches for a recognition. The method call uses only one parameter, the number of alternates to return; the other parameters are assigned by default and return all the available words and phrases. Note that the first alternate returned is always the recognized word or phrase.

To run this code, paste it into the Declarations section of a form that contains no controls. In addition to the usual reference to the Microsoft Speech Object Library, this code also needs a reference to the simpleaudio 1.0 Type Library.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition:
    Set RecoContext = Recognizer.CreateRecoContext
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim phraseAlternate As ISpeechPhraseAlternates
    Dim i As Long
    Dim T As String
    Dim theString As String

    On Error GoTo EH

    Set phraseAlternate = Result.Alternates(6)
    For i = 0 To phraseAlternate.Count - 1
        theString = phraseAlternate.Item(i).PhraseInfo.GetText
        T = T & "Alternates #" + Str(i) + ": " & theString + vbNewLine
    Next i

    MsgBox T, vbInformation
    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifier:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoResult Audio Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResult

Audio Method

The Audio method creates an audio stream from the audio data in the result object.

The resulting stream can be used as input for SPVoice.SpeakStream. However, a single call to ISpeechRecoResults.SpeakAudio performs the same action of speaking the recognized result.

The audio portion of the recognition is not automatically available. By default, the recognition context does not retain audio. To retain it, call the RetainedAudio property and set it to SRAORetainAudio. While RetainedAudio can be toggled at anytime, audio for a specific phrase must be retained before recognition attempts begin. Therefore, RetainedAudio must be called before the phrase is spoken.

ISpeechRecoResult.Audio(
     [StartElement As Long = 0],
     [Elements As Long = -1]
) As ISpeechBaseStream

Parameters

StartElement
[Optional] Specifies the starting element. The default value is zero, indicating the first element is used.
Elements
[Optional] Specifies the number of elements to speak. Default value is -1, indicating all elements are to be played.

Return Value

The Audio method returns an ISpeechBaseStream stream.

Remarks

Even if there are no elements, that is, StartElement = 0 and Elements = 0, the audio will still be played. Unrecognized results not having elements will still have audio.

Example

The following Visual Basic form code calls the Audio method of a RecoResult. The stream is returned by the method and then the code passes it to SPVoice.SpeakStream for you to hear.

To run this code, paste it into the Declarations section of a form that contains no controls. In addition to the usual reference to the Microsoft Speech Object Library, this code also needs a reference to the simpleaudio 1.0 Type Library.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition and explicitly set
    ' flag to retain audio portion of recognition
    ' (default behavior is not to retain):
    Set RecoContext = Recognizer.CreateRecoContext
    RecoContext.RetainedAudio = SRAORetainAudio
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim Stream As ISpeechBaseStream

    On Error GoTo EH

    ' Retrieve stream to speak.
    Set Stream = Result.Audio

    ' Create voice and have it speak:
    Set Voice = New SpVoice
    Voice.SpeakStream Stream

    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifier:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoResult::AudioFormat Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechRecoResult

AudioFormat Property

The AudioFormat property gets or sets the audio stream format.

The controlling recognition context must retain the audio portion of the recognition. By default, a recognition context does not retain audio; that is, RecoContext.RetainedAudio is set to SRAONone. Attempts to access this retained audio stream, including references to AudioFormat, cause an SPERR_NO_AUDIO_DATA error. To retain the audio, use ISpeechRecoContext.RetainedAudio passing SRAORetainAudio as the parameter.

Syntax

Get: | SpAudioFormat = ISpeechRecoResult.AudioFormat
Set: | ISpeechRecoResult.AudioFormat = SpAudioFormat

Parts

ISpeechRecoResult
The owning object.
SpAudioFormat
An object variable representing an audio output device.
Get: The token represents the current audio output device of the voice.
Set: The token represents the audio output device assigned to the voice.
In either case, the format for SpAudioFormat.Type is of type SpeechAudioFormatType.

Example

The following Visual Basic form code reads and sets the AudioFormat property of a RecoResult.

To run this code, paste it into the Declarations section of a form that contains no controls. In addition to the usual reference to the Microsoft Speech Object Library, this code also needs a reference to the simpleaudio 1.0 Type Library.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition and explicitly set
    ' flag to retain audio portion of recognition
    ' (default behavior is not to retain):
    Set RecoContext = Recognizer.CreateRecoContext
    RecoContext.RetainedAudio = SRAORetainAudio
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim GetFormat As SpAudioFormat
    Dim SetFormat As SpAudioFormat

    On Error GoTo EH

    ' Get audio format.
    Set GetFormat = Result.AUDIOFORMAT

    ' Set audio format:
    Set SetFormat = CreateObject("SAPI.SpAudioFormat")
    SetFormat.Type = SAFT11kHz16BitMono
    Set Result.AUDIOFORMAT = SetFormat

    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoResult DiscardResultInfo Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResult

DiscardResultInfo Method

The DiscardResultInfo method discards the requested data from a phrase object.

Applications that have no use for certain types of retained data, and will be persisting or serializing the phrase or result objects, may discard unnecessary data.

For example, an application performing offline transcription may need to retain only the audio and the final result. It can remove the alternates with object.DiscardResultInfo(SPDF_ALTERNATES) to eliminate the alternate data (possibly including a large amount of private engine data). Once the result information is discarded, all attempts to access that data will be unsuccessful. For example, once retained audio has been discarded, a call to ISpeechRecoResult.Audio will fail.

ISpeechRecoResult.DiscardResultInfo(
     ValueTypes As SpeechDiscardType
)

Parameters

ValueTypes
Flags indicating elements to discard. Multiple values may be combined with logical operands.

Return Value

None.

Example

The following Visual Basic form code demonstrates discarding the audio portion of a recognition by calling the DiscardResultInfo method of a RecoResult. After discarding the retained audio, the next attempt to speak it fails and the code's exception handler catches the error and displays its description and number (SPERR_NO_AUDIO_DATA or -2147200976).

To run this code, paste it into the Declarations section of a form that contains no controls. In addition to the usual reference to the Microsoft Speech Object Library, this code also needs a reference to the simpleaudio 1.0 Type Library.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition and explicitly set
    ' flag to retain audio portion of recognition
    ' (default behavior is not to retain):
    Set RecoContext = Recognizer.CreateRecoContext
    RecoContext.RetainedAudio = SRAORetainAudio
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim GetFormat As SpAudioFormat
    Dim SetFormat As SpAudioFormat

    On Error GoTo EH

    With Result

        ' Speak back recognized text.
        .SpeakAudio

        ' Discard retained audio and note that next
        ' attempt at speaking that audio fails
        ' (exception handler catches run-time error):
        .DiscardResultInfo SDTAudio
        Result.SpeakAudio

    End With

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoResult PhraseInfo Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResult

PhraseInfo Property

The PhraseInfo property returns an ISpeechPhraseInfo structure containing detailed information about the last recognized phrase.

ISpeechPhraseInfo elements contains read-only data about timing for the phrase and audio stream, elements (words and phrases) in the recognized phrase, grammar and grammar rules information. The structure is used to examine the recognition information. It is also used by other calls such as ISpeechRecoResult.PhraseInfo.GetText to retrieve the phrase text.

Syntax

Set: | (This property is read-only)
Get: | ISpeechPhraseInfo = ISpeechRecoResult.PhraseInfo

Parts

ISpeechRecoResult
The owning object.
ISpeechPhraseInfo
Set: (This property is read-only)
Get: An ISpeechPhraseInfo variable that gets the property.

Example

The following Visual Basic form code reads the PhraseInfo property of a RecoResult and parses out selected information about stream times and element times and displays the results. Although the preferred method of retrieving the text uses ISpeechRecoResult.GetText, this code not only retrieves the text on an element by element basis, but also retrieves the stream time associated with the word.

To run this code, paste it into the Declarations section of a form that contains no controls. In addition to the usual reference to the Microsoft Speech Object Library, this code also needs a reference to the simpleaudio 1.0 Type Library.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition and explicitly set
    ' flag to retain audio portion of recognition
    ' (default behavior is not to retain):
    Set RecoContext = Recognizer.CreateRecoContext
    RecoContext.RetainedAudio = SRAORetainAudio
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Const NL = vbNewLine
    Dim i As Integer
    Dim T As String

    On Error GoTo EH

    With Result.PhraseInfo
        T = T & "LangID= " & .LanguageId & NL
        T = T & "AudioBytes= " & .AudioSizeBytes & NL
        T = T & "AudioTime= " & .AudioSizeTime & NL

        For i = 0 To .Elements.Count - 1
            T = T & "Stream offset:" & .Elements(i).AudioStreamOffset & NL
            T = T & "Text form: " & .Elements(i).DisplayText & NL
            T = T & "Lex form: " & .Elements(i).LexicalForm & NL
        Next
    End With

    MsgBox T, vbInformation
    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoResult RecoContext Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResult

RecoContext Property

The RecoContext property retrieves the current ISpeechRecoContext for the recognizer.

Applications may have multiple recognition contexts open at the same time. RecoContext provides a means to determine which context owns the recognition. For example, in situations with more than recognition context, a recognition result may call RecoContext to get the context associated with it. The returned context may be changed afterward and will not affect other contexts.

Syntax

Set: | (This property is read-only)
Get: | ISpeechRecoContext = ISpeechRecoResult.RecoContext

Parts

ISpeechRecoResult
The owning object.
SpSharedRecoContext
Set: (This property is read-only)
Get: An SpSharedRecoContext variable that gets the property.

Example

The following Visual Basic form code reads the RecoContext property of a RecoResult. If more than one recognition context exists, the one owning RecoResult is retrieved. When the event interest is changed, no other recognition contexts are affected.

To run this code, paste it into the Declarations section of a form that contains no controls. In addition to the usual reference to the Microsoft Speech Object Library, this code also needs a reference to the simpleaudio 1.0 Type Library.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition and explicitly set
    ' flag to retain audio portion of recognition
    ' (default behavior is not to retain):
    Set RecoContext = Recognizer.CreateRecoContext
    RecoContext.RetainedAudio = SRAORetainAudio
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim myContext As ISpeechRecoContext

    On Error GoTo EH

    ' Change event interest of recognition context:
    Set myContext = Result.RecoContext()
    myContext.EventInterests = SREFalseRecognition
    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoResult SaveToMemory Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResult

SaveToMemory Method

The SaveToMemory method saves the entire recognition result to memory.

The phrase may be recalled at a later time. To retrieve the recognition result from memory use SpSharedRecoContext.CreateResultFromMemory or SpInProcRecoContext.CreateResultFromMemory depending on the recognition context used.

ISpeechRecoResult.SaveToMemory() As Variant

Parameters

None

Return Value

The SaveToMemory method returns a Variant containing a pointer to saved phrase.

Example

See ISpeechRecoContext.CreateResultFromMemory.htm for a complete code sample.


ISpeechRecoResult SpeakAudio Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResult

SpeakAudio Method

The SpeakAudio method plays the audio sequence containing the recognized phrase.

The audio portion of the recognition is not automatically available. By default, the recognition context does not retain audio. Call RetainedAudio and set it to SRAORetainAudio to retain the audio. Although RetainedAudio can be toggled at anytime, audio for a specific phrase must be retained before recognition attempts begin. Therefore, RetainedAudio must be called before the phrase is spoken.

SpeakAudio combines two other methods. The first, ISpeechRecoResult.Audio, which retrieves the audio. The second call is SpVoice.SpeakStream, which plays it back.

ISpeechRecoResult.SpeakAudio(
     [StartElement As Long = 0],
     [Elements As Long = -1],
     [Flags As SpeechVoiceSpeakFlags = SVSFDefault]
) As Long

Parameters

StartElement
[Optional] Specifies the starting element. The default value is zero, indicating that the first element is used.
Elements
[Optional] Specifies the number of elements to speak. Default value is -1, indicating that all elements are to be played.
Flags
[Optional] Specifies the Flags. Default value is SVSFDefault indicating that no special speak restrictions are imposed.

Return Value

The SpeakAudio method returns a Long variable indicating the stream number.

Remarks

Even if there are no elements, that is, StartElement = 0 and Elements = 0, the audio will still be played. Unrecognized results not having elements will still have audio.

Also see ISpeechRecoContext.RetainedAudio for an additional code sample.

Example

The following Visual Basic form code plays the audio sequence containing a recognized phrase. RetainedAudio must have been set for the current recognizer.

To run this code, paste it into the Declarations section of a form that contains no controls. In addition to the usual reference to the Microsoft Speech Object Library, this code also needs a reference to the simpleaudio 1.0 Type Library.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition and explicitly set
    ' flag to retain audio portion of recognition
    ' (default behavior is not to retain):
    Set RecoContext = Recognizer.CreateRecoContext
    RecoContext.RetainedAudio = SRAORetainAudio
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim i As Integer

    On Error GoTo EH

    For i = 0 To Result.PhraseInfo.Elements.Count - 1
       StreamNumber = Result.SpeakAudio(i, 1, SVSFDefault)
    Next i

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoResult Times Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResult

Times Property

The Times property retrieves the time information associated with the result.

Syntax

Set: | (This property is read-only)
Get: | ISpeechRecoResultTimes = ISpeechRecoResult.Times

Parts

ISpeechRecoResult
The owning object.
ISpeechRecoResultTimes
Set: (This property is read-only)
Get: An ISpeechRecoResultTimes variable containing the time information for the recognition.

Example

The following Visual Basic form code reads ISpeechRecoResultTimes for the current recognition. Because that object's four properties are read-only, their values are added to a string for display in a message box. RecoResult.

To run this code, paste it into the Declarations section of a form that contains no controls. In addition to the usual reference to the Microsoft Speech Object Library, this code also needs a reference to the simpleaudio 1.0 Type Library.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition and explicitly set
    ' flag to retain audio portion of recognition
    ' (default behavior is not to retain):
    Set RecoContext = Recognizer.CreateRecoContext
    RecoContext.RetainedAudio = SRAORetainAudio
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Const NL = vbNewLine
    Dim myTimes As ISpeechRecoResultTimes
    Dim T As String

    On Error GoTo EH
    Set myTimes = Result.Times()

    With myTimes
        T = "Len: " & .Length & NL
        T = T & "Start: " & .OffsetFromStart & NL
        T = T & "Time: " & .StreamTime & NL
        T = T & "TickCount: " & .TickCount
        MsgBox T, vbInformation
        End
    End With

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoResultDispatch Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechRecoResultDispatch

New in SAPI 5.3

Supports IDispatch access to the ISpeechRecoResult and ISpeechXMLRecoResult interfaces.

The ISpeechRecoResultDispatch interface cannot be QI'd.

Automation Interface Elements

The ISpeechRecoResultDispatch automation interface contains the following elements:

Properties | Description
AudioFormat | Gets or sets the audio stream format.
PhraseInfo | Returns an ISpeechPhraseInfo interface whose properties contain or whose methods can access detailed information about the last recognized phrase.
RecoContext | Retrieves the current ISpeechRecoContext for the recognizer.
Times | Retrieves the time information associated with the result.
Methods | Description
Alternates | Returns a list of alternate words.
Audio | Creates an audio stream from the audio data in the result object.
DiscardResultInfo | Discards the requested data from a phrase object.
GetXMLErrorInfo | Is used to discover the details of an error that occurred during semantic processing.
GetXMLResult | Returns the recognition result as SSML.
SaveToMemory | Saves the entire recognition result to memory.
SpeakAudio | Plays the audio sequence containing the recognized phrase.


ISpeechRecoResultDispatch Alternates Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultDispatch

Alternates Method

The Alternates method returns a list of alternate words.

Many recognitions, successful or not, frequently return several words or phrases that closely match the spoken sequence. The one most nearly matching the sequence with a high confidence level is returned as a successful recognition. The other words and phrases are returned as alternates that are available for examination.

ISpeechRecoResultDispatch.Alternates(
    RequestCount As Long,
   [StartElement As Long = 0],
   [Elements As Long = -1]
) As ISpeechPhraseAlternates

Parameters

RequestCount
Specifies the maximum number of alternates to retrieve, which must be greater than zero. Any number of alternates may be chosen and will be returned in descending order of confidence. That is, the first alternate returned has the highest confidence and will most likely be the word or phrase chosen by the successful recognition. The second alternate returned will be the next most likely choice, and the last alternate returned the least likely match.
StartElement
[Optional] Specifies which element to use as a starting point. If omitted, zero is used and indicates the first alternate as the starting point. Because it is zero based, the second element would be one.
Elements
[Optional] Specifies the number of elements to retrieve. Default is -1 (that is, SPPR_ALL_ELEMENTS), which specifies all alternate elements are retrieved.

Return Value

The Alternates method returns a ISpeechPhraseAlternates object, which is a collection of ISpeechPhraseAlternate objects.


ISpeechRecoResultDispatch Audio Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultDispatch

Audio Method

The Audio method creates an audio stream from the audio data in the result object.

The resulting stream can be used as input for SPVoice.SpeakStream. However, a single call to ISpeechRecoResultsDispatch.SpeakAudio performs the same action of speaking the recognized result

The audio portion of the recognition is not automatically available. By default, the recognition context does not retain audio. To retain it, call the RetainedAudio property and set it to SRAORetainAudio. While RetainedAudio can be toggled at anytime, audio for a specific phrase must be retained before recognition attempts begin. Therefore, RetainedAudio must be called before the phrase is spoken.

ISpeechRecoResultDispatch.Audio(
    [StartElement As Long = 0],
    [Elements As Long = -1]
) As ISpeechBaseStream

Parameters

StartElement
[Optional] Specifies which element to use as a starting point. If omitted, zero is used and indicates the first alternate as the starting point. Because it is zero based, the second element would be one.
Elements
[Optional] Specifies the number of elements to retrieve. Default is -1 (that is, SPPR_ALL_ELEMENTS), which specifies all alternate elements are retrieved.

Return Value

The Audio method returns an ISpeechBaseStream object.

Remarks

Even if there are no elements, that is, StartElement = 0 and Elements = 0, the audio will still be played. Unrecognized results not having elements will still have audio.


ISpeechRecoResultDispatch AudioFormat Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultDispatch

AudioFormat Property

The AudioFormat property gets or sets the audio stream format.

The controlling recognition context must retain the audio portion of the recognition. By default, a recognition context does not retain audio; that is, RecoContext.RetainedAudio is set to SRAONone. Attempts to access this retained audio stream, including references to AudioFormat, cause an SPERR_NO_AUDIO_DATA error. To retain the audio, use ISpeechRecoContext.RetainedAudio passing SRAORetainAudio as the parameter.

Syntax

Get: | SpAudioFormat = ISpeechRecoResult.AudioFormat
Set: | ISpeechRecoResultDispatch.AudioFormat = SpAudioFormat

Parts

ISpeechRecoResultDispatch
The owning object.
SpAudioFormat
An object variable representing an audio output device.
Get: The token represents the current audio output device of the voice.
Set: The token represents the audio output device assigned to the voice.
In either case, the format for SpAudioFormat.Type is of type SpeechAudioFormatType.

Remarks

*TODO* Description....


ISpeechRecoResultDispatch DiscardResultInfo Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultDispatch

DiscardResultInfo Method

The DiscardResultInfo method discards the requested data from a phrase object.

Applications that have no use for certain types of retained data, and will be persisting or serializing the phrase or result objects, may discard unnecessary data.

For example, an application performing offline transcription may need to retain only the audio and the final result. It can remove the alternates with object.DiscardResultInfo(SPDF_ALTERNATES) to eliminate the alternate data (possibly including a large amount of private engine data). Once the result information is discarded, all attempts to access that data will be unsuccessful. For example, once retained audio has been discarded, a call to ISpeechRecoResultDispatch.Audio will fail.

ISpeechRecoResultDispatch.DiscardResultInfo(
    ValueTypes As SpeechDiscardType
)

Parameters

ValueTypes
Flags indicating elements to discard. Multiple values may be combined with logical operands.

Return Value

None


ISpeechRecoResultDispatch GetXMLErrorInfo Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultDispatch

GetXMLErrorInfo Method

The GetXMLErrorInfo method is used to discover the details of an error that occurred during semantic processing.

ISpeechXMLRecoResultDispatch.GetXMLErrorInfo(
    LineNumber As Long,
    ScriptLine As String,
    Source As String,
    Description As String,
    ResultCode As Long
) As Boolean

Parameters

LineNumber
The line number where the error occurred.
ScriptLine
The text of the line where the error occurred.
Source
The location of the file in which the error occurred.
Description
A description of the error.
ResultCode
The code number of the error.

Return Value

True if an error did occur during semantic processing or else false.


ISpeechRecoResultDispatch GetXMLResult Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultDispatch

GetXMLResult Method

The GetXMLResult method returns the recognition result as SSML.

ISpeechXMLRecoResultDispatch.GetXMLResult(
    Options As SPXMLRESULTOPTIONS
) As String

Parameters

Options
An element in the enumeration that specifies whether the primary result (0) or the alternate results (1) should be returned.

Return Value

A String that is the result formatted as SSML.


ISpeechRecoResultDispatch PhraseInfo Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultDispatch

PhraseInfo Property

The PhraseInfo property returns an ISpeechPhraseInfo interface whose properties contain or whose methods can access detailed information about the last recognized phrase.

ISpeechPhraseInfo members return read-only data about timing for the phrase and audio stream, elements (words and phrases) in the recognized phrase, and grammar and grammar rules information. This interface is used to examine the recognition information. It is also used by other calls such as ISpeechRecoResultDispatch.PhraseInfo.GetText to retrieve the phrase text.

Syntax

Set: | (This property is read-only)
Get: | ISpeechPhraseInfo = ISpeechRecoResultDispatch.PhraseInfo

Parts

ISpeechRecoResultDispatch
The owning object.
ISpeechPhraseInfo
Set: (This property is read-only)
Get: An ISpeechPhraseInfo variable that gets the property.


ISpeechRecoResultDispatch RecoContext Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultDispatch

RecoContext Property

The RecoContext property retrieves the current ISpeechRecoContext for the recognizer.

Applications may have multiple recognition contexts open at the same time. RecoContext provides a means to determine which context owns the recognition. For example, in situations with more than recognition context, a recognition result may call RecoContext to get the context associated with it. The returned context may be changed afterward and will not affect other contexts.

Syntax

Set: | (This property is read-only)
Get: | ISpeechRecoContext = ISpeechRecoResultDispatch.RecoContext

Parts

ISpeechRecoContextDispatch
The owning object.
SpSharedRecoContext
Set: (This property is read-only)
Get: An SpSharedRecoContext variable that gets the property.


ISpeechRecoResultDispatch SaveToMemory Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultDispatch

SaveToMemory Method

The SaveToMemory method saves the entire recognition result to memory.

ISpeechRecoResultDispatch.SaveToMemory() As Variant

Parameters

None

Return Value

The SaveToMemory method returns a Variant containing a pointer to the saved recognition result.


ISpeechRecoResultDispatch SpeakAudio Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultDispatch

SpeakAudio Method

The SpeakAudio method plays the audio sequence containing the recognized phrase.

The audio portion of the recognition is not automatically available. By default, the recognition context does not retain audio. Call RetainedAudio and set it to SRAORetainAudio to retain the audio. Although RetainedAudio can be toggled at anytime, audio for a specific phrase must be retained before recognition attempts begin. Therefore, RetainedAudio must be called before the phrase is spoken.

SpeakAudio combines two other methods. The first, ISpeechRecoResultDispatch.Audio, which retrieves the audio. The second call is SpVoice.SpeakStream, which plays it back.

ISpeechRecoResultDispatch.SpeakAudio(
    [StartElement As Long = 0],
    [Elements As Long = -1],
    [Flags As SpeechVoiceSpeakFlags = SVSFDefault]
) As Long

Parameters

StartElement
[Optional] Specifies the starting element. The default value is zero, indicating that the first element is used.
Elements
[Optional] Specifies the number of elements to speak. Default value is -1, indicating that all elements are to be played.
Flags
[Optional] Specifies the Flags. Default value is SVSFDefault indicating that no special speak restrictions are imposed.

Return Value

The SpeakAudio method returns a Long indicating the stream number.

Remarks

Even if there are no elements, that is, StartElement = 0 and Elements = 0, the audio will still be played. Unrecognized results not having elements will still have audio.


ISpeechRecoResultDispatch Times Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultDispatch

Times Property

The Times property retrieves the time information associated with the result.

Syntax

Set: | (This property is read-only)
Get: | ISpeechRecoResultTimes = ISpeechRecoResultDispatch.Times

Parts

ISpeechRecoResultDispatch
The owning object.
ISpeechRecoResultTimes
Set: (This property is read-only)
Get: An ISpeechRecoResultTimes variable containing the time information for the recognition.


ISpeechRecoResultTimes Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechRecoResultTimes

The ISpeechRecoResultTimes automation interface contains the time information for speech recognition results.

The ISpeechRecoResult.Times property returns an ISpeechRecoResultTimes object.

Automation Interface Elements

The ISpeechRecoResultTimes automation interface contains the following elements:

Properties | Description
Length Property | Returns the time length of the last recognition.
OffsetFromStart Property | Returns the time from the start of the stream to the start of the phrase.
StreamTime Property | Returns the time of the stream in Universal Coordinated Time.
TickCount Property | Returns the elapsed time from the start of the system to the start of the current result.


ISpeechRecoResultTimes Length Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultTimes

Length Property

The Length property returns the time length of the last recognition.

It is specified in 100 nanosecond units.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechRecoResultTimes.Length

Parts

ISpeechRecoResultTimes
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant type containing the length of the recognition.

Remarks

When a recognition occurs with a valid RecoResult, the times can be extracted for later use to allocate memory or to select data from the audio stream. For example, using the phrase "variety is the spice of life," the Length could be 32,200,000 nanoseconds or 3.2 seconds.

Example

Use of the ISpeechRecoResultTimes object is demonstrated in a code example at the end of this section.


ISpeechRecoResultTimes OffsetFromStart Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultTimes

OffsetFromStart Property

The OffsetFromStart property returns the time from the start of the stream to the start of the phrase.

It is specified in 100 nanosecond units.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechRecoResultTimes.OffsetFromStart

Parts

ISpeechRecoResultTimes
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant type containing time offset from the start of the stream.

Remarks

When a recognition occurs with a valid RecoResult, the times can be extracted in order to select data at a later time. For example, using the phrase "variety is the spice of life," the OffsetFromStart position could be 21120 if the user started speaking relatively quickly once the stream began.

Example

Use of the ISpeechRecoResultTimes object is demonstrated in a code example at the end of this section.


ISpeechRecoResultTimes StreamTime Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultTimes

StreamTime Property

The StreamTime property returns the time of the stream in Universal Coordinated Time.

This value is zero if a wave file input is used.

Syntax

Set: | (This property is read-only)
Get: | Variant = ISpeechRecoResultTimes.StreamTime

Parts

ISpeechRecoResultTimes
The owning object.
Variant
Set: (This property is read-only)
Get: A Variant type containing the Universal Coordinated Time time of the phrase start for the stream.

Example

Use of the ISpeechRecoResultTimes object is demonstrated in a code example at the end of this section.


ISpeechRecoResultTimes TickCount Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultTimes

TickCount Property

The TickCount property returns the elapsed time from the start of the system to the start of the current result.

It is specified in millisecond units. The TickCount returns zero if the wave file input is used.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechRecoResultTimes.TickCount

Parts

ISpeechRecoResultTimes
The owning object.
Long
Set: (This property is read-only)
Get: A Variant type containing the elapsed time

Remarks

When a recognition occurs with RecoResult, the TickCount can be extracted to determine the absolute time for the computer system. It is more accurate than retrieving the clock values.

Example

Use of the ISpeechRecoResultTimes object is demonstrated in a code example at the end of this section.


ISpeechResourceLoader Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechResourceLoader

New in SAPI 5.3

The ISpeechResourceLoader interface gives applications control over loading resources. For example, applications may want to cache remote resources, enforce custom security policies, or redirect resources to other locations.

Applications implement a resource loader by implementing either LoadResource or both GetLocalCopy and ReleaseLocalCopy. The resource loader can be provided via ISpRecoGrammar2::SetGrammarLoader.

Automation Interface Elements

The ISpeechResourceLoader automation interface contains the following elements:

Methods | Description
GetLocalCopy Method | Gets a local copy of the specified speech resource.
LoadResource Method | Loads the specified speech resource.
ReleaseLocalCopy Method | Releases the local copy of the specified speech resource.


ISpeechResourceLoader GetLocalCopy Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechResourceLoader

GetLocalCopy Method

Gets a local copy of the specified speech resource.

The local file must reside on the machine on which the Speech process is running.

Syntax

Set: | ISpeechResourceLoader.GetLocalCopy = Long
Get: | Long = ISpeechResourceLoader.GetLocalCopy

Parts

ISpeechResourceLoader
The owning object.
Long
Set: A Long variable that sets the property.
Get: A Long variable that gets the property.


ISpeechResourceLoader LoadResource Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechResourceLoader

LoadResource Method

Loads the specified speech resource.

Syntax

Set: | ISpeechResourceLoader.LoadResource = Long
Get: | Long = ISpeechResourceLoader.LoadResource

Parts

ISpeechResourceLoader
The owning object.
Long
Set: A Long variable that sets the Method.
Get: A Long variable that gets the Method.


ISpeechResourceLoader ReleaseLocalCopy Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechResourceLoader

ReleaseLocalCopy Method

Releases the local copy of the specified speech resource.

Syntax

Set: | ISpeechResourceLoader.ReleaseLocalCopy = Long
Get: | Long = ISpeechResourceLoader.ReleaseLocalCopy

Parts

ISpeechResourceLoader
The owning object.
Long
Set: A Long variable that sets the method.
Get: A Long variable that gets the method.


ISpeechVoiceStatus Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechVoiceStatus

The ISpeechVoiceStatus automation interface defines the types of information returned by the SpVoice.Status method.

Most ISpeechVoiceStatus properties consist of real-time feedback from the text-to-speech (TTS) engine. These properties are equivalent to parameters returned by voice events, and like voice events, they are used only with asynchronous speech. It may be advantageous for some applications to retrieve these elements by calling Status occasionally, rather than by receiving events constantly.

It should be noted that voice status and voice events are closely associated with the status of the audio output device. A voice speaking to a file stream produces no audio output and has no audio output status. As a result, ISpeechVoiceStatus always displays the voice as inactive.

Use of the ISpeechVoiceStatus is demonstrated in a code example at the end of this section.

Automation Interface Elements

The ISpeechVoiceStatus automation interface contains the following elements:

Properties | Description
CurrentStreamNumber Property | Retrieves the number of the text input stream being spoken by the TTS engine.
InputSentenceLength Property | Retrieves the length of the sentence currently being spoken by the TTS engine.
InputSentencePosition Property | Retrieves the position one character prior to the beginning of the sentence currently being spoken by the TTS engine.
InputWordLength Property | Retrieves the length of the word currently being spoken by the TTS engine.
InputWordPosition Property | Retrieves the position one character prior to the beginning of the word currently being spoken by the TTS engine.
LastBookmark Property | Retrieves the string value of the last bookmark encountered by the TTS engine.
LastBookmarkId Property | Retrieves the ID of the last bookmark encountered by the TTS engine.
LastHResult Property | Retrieves the HResult, or internal status code, from the last Speak or SpeakStream operation performed by the TTS engine.
LastStreamNumberQueued Property | Retrieves the number of the last audio stream spoken by the TTS engine.
PhonemeId Property | Retrieves the ID of the current phoneme being spoken by the TTS engine.
RunningState Property | Retrieves the run state of the voice, which indicates whether the voice is speaking or inactive.
VisemeId Property | Gets the ID of the current viseme being spoken by the TTS engine.


ISpeechVoiceStatus CurrentStreamNumber Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

CurrentStreamNumber Property

The CurrentStreamNumber property retrieves the number of the text input stream being spoken by the text-to-speech (TTS) engine.

The CurrentStreamNumber property of an ISpeechVoiceStatus object is valid only when its RunningState property is SRSEIsSpeaking.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechVoiceStatus.CurrentStreamNumber

Parts

ISpeechVoiceStatus
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable that returns the stream number.

Example

The following Visual Basic form code demonstrates the use of the CurrentStreamNumber and RunningState properties. To run this code, create a form with the following controls:

  • A command button called Command1
  • A list box called List1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice. The Command1_Click procedure speaks three text streams asynchronously, putting each in the list box, and then performs a loop until the voice finishes speaking. Inside this loop, the code uses the CurrentStreamNumber property to highlight each line of text in the list box while it is spoken by the TTS engine. A RunningState property of SRSEDone indicates that the voice has finished speaking.

Option Explicit

Private V As SpeechLib.SpVoice

Private Sub Command1_Click()
    Dim ii As Integer

    On Error GoTo EH
    List1.Clear

    'Place text strings in the List box, and speak them

    List1.AddItem "This is stream number one."
    V.Speak "This is stream number one.", SVSFlagsAsync

    List1.AddItem "A second stream, now."
    V.Speak "A second stream, now.", SVSFlagsAsync

    List1.AddItem "The third stream is next."
    V.Speak "The third stream is next.", SVSFlagsAsync

    'Check status periodically
    Do
        For ii = 0 To 1000
            DoEvents
        Next ii

        'Highlight the stream being spoken
        List1.ListIndex = V.Status.CurrentStreamNumber - 1

    Loop Until V.Status.RunningState = SRSEDone 'Exit when voice stops

    List1.ListIndex = -1    'Turn highlight off

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()

    On Error GoTo EH
    Set V = New SpVoice

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechVoiceStatus InputSentenceLength Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

InputSentenceLength Property

The InputSentenceLength property retrieves the length of the sentence currently being spoken by the text-to-speech (TTS) engine.

The InputSentenceLength property of an ISpeechVoiceStatus object is valid only when its RunningState property is SRSEIsSpeaking.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechVoiceStatus.InputSentenceLength

Parts

ISpeechVoiceStatus
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the sentence length.

Example

The following Visual Basic form code demonstrates the use of the InputSentenceLength and InputSentencePosition properties of an ISpeechVoiceStatus object. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1
  • Set the HideSelection property of Text1 to False

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object and places sample sentences in the text box. The Command1_Click procedure speaks the contents of the text box asynchronously and loops until the voice finishes speaking. In this loop, the code uses InputSentencePosition and InputSentenceLength properties to highlight each sentence in the text box as it is spoken by the TTS engine. A RunningState property of SRSEDone indicates that the voice has finished speaking.

Option Explicit

Dim V As SpeechLib.SpVoice

Private Sub Command1_Click()

    Dim ii As Integer
    Dim S As SpeechLib.ISpeechVoiceStatus

    On Error GoTo EH

    V.Speak Text1.Text, SVSFlagsAsync   'Speak the user-editable text

    'Check status periodically
    Do
        For ii = 0 To 5000
            DoEvents
        Next ii

        Set S = V.Status    'Get status in an ISpeechVoiceStatus object

        'Text1.HideSelection must be False for this selection to be seen!

        Text1.SelStart = S.InputSentencePosition
        Text1.SelLength = S.InputSentenceLength

    Loop Until V.Status.RunningState = SRSEDone 'Exit when voice stops

    Text1.SelLength = 0

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()

    On Error GoTo EH
    Set V = New SpVoice
    Text1.Text = "One sentence. Another sentence. Still one more sentence."

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechVoiceStatus InputSentencePosition Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

InputSentencePosition Property

The InputSentencePosition property retrieves the position one character prior to the beginning of the sentence currently being spoken by the text-to-speech (TTS) engine.

The InputSentencePosition property of an ISpeechVoiceStatus object is valid only when its RunningState property is SRSEIsSpeaking.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechVoiceStatus.InputSentencePosition

Parts

ISpeechVoiceStatus
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the character position.

Example

The following Visual Basic form code demonstrates the use of the InputSentenceLength and InputSentencePosition properties of an ISpeechVoiceStatus object. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1
  • Set the HideSelection property of Text1 to False

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object and places a few sentences in the text box. The Command1_Click procedure speaks the contents of the text box asynchronously and loops until the voice finishes speaking. In this loop, the code uses InputSentencePosition and InputSentenceLength properties to highlight each sentence in the text box as it is spoken by the TTS engine. A RunningState property of SRSEDone indicates that the voice has finished speaking.

Option Explicit

Dim V As SpeechLib.SpVoice

Private Sub Command1_Click()

    Dim ii As Integer
    Dim S As SpeechLib.ISpeechVoiceStatus

    On Error GoTo EH

    V.Speak Text1.Text, SVSFlagsAsync   'Speak the user-editable text

    'Check status periodically
    Do
        For ii = 0 To 5000
            DoEvents
        Next ii

        Set S = V.Status    'Get status in an ISpeechVoiceStatus object

        'Text1.HideSelection must be False for this selection to be seen!

        Text1.SelStart = S.InputSentencePosition
        Text1.SelLength = S.InputSentenceLength

    Loop Until V.Status.RunningState = SRSEDone 'Exit when voice stops

    Text1.SelLength = 0

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()

    On Error GoTo EH
    Set V = New SpVoice
    Text1.Text = "One sentence. Another sentence. Still one more sentence."

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechVoiceStatus InputWordLength Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

InputWordLength Property

The InputWordLength property retrieves the length of the word currently being spoken by the text-to-speech (TTS) engine.

The InputWordLength property of an ISpeechVoiceStatus object is valid only when its RunningState property is SRSEIsSpeaking.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechVoiceStatus.InputWordLength

Parts

ISpeechVoiceStatus
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the word length.

Example

The following Visual Basic form code demonstrates the use of the InputWordLength and InputWordPosition properties of an ISpeechVoiceStatus object. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1
  • Set the HideSelection property of Text1 to False

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object and places a sentence in the text box. The Command1_Click procedure speaks the contents of the text box asynchronously and loops until the voice finishes speaking. In this loop, the code uses InputSentencePosition and InputSentenceLength properties to highlight each word in the text box as it is spoken by the TTS engine. A RunningState property of SRSEDone indicates that the voice has finished speaking.

Option Explicit

Dim V As SpeechLib.SpVoice

Private Sub Command1_Click()

    Dim ii As Integer
    Dim S As SpeechLib.ISpeechVoiceStatus

    On Error GoTo EH

    V.Speak Text1.Text, SVSFlagsAsync   'Speak the user-editable text

    'Check status periodically
    Do
        For ii = 0 To 5000
            DoEvents
        Next ii

        Set S = V.Status    'Get status in an ISpeechVoiceStatus object

        'Text1.HideSelection must be False for this selection to be seen!

        Text1.SelStart = S.InputWordPosition
        Text1.SelLength = S.InputWordLength

    Loop Until V.Status.RunningState = SRSEDone 'Exit when voice stops

    Text1.SelLength = 0

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()

    On Error GoTo EH
    Set V = New SpVoice
    Text1.Text = "This is a sentence containing several words."

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechVoiceStatus InputWordPosition Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

InputWordPosition Property

The InputWordPosition property retrieves the position one character prior to the beginning of the word currently being spoken by the text-to-speech (TTS) engine.

The InputWordPosition property of an ISpeechVoiceStatus object is valid only when its RunningState property is SRSEIsSpeaking.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechVoiceStatus.InputWordPosition

Parts

ISpeechVoiceStatus
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the character position.

Example

The following Visual Basic form code demonstrates the use of the InputWordLength and InputWordPosition properties of an ISpeechVoiceStatus object. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1
  • Set the HideSelection property of Text1 to False

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object and places a sentence in the text box. The Command1_Click procedure speaks the contents of the text box asynchronously and loops until the voice finishes speaking. In this loop, the code uses InputSentencePosition and InputSentenceLength properties to highlight each word in the text box as it is being spoken by the TTS engine. A RunningState property of SRSEDone indicates that the voice has finished speaking.

Option Explicit

Dim V As SpeechLib.SpVoice

Private Sub Command1_Click()

    Dim ii As Integer
    Dim S As SpeechLib.ISpeechVoiceStatus

    On Error GoTo EH

    V.Speak Text1.Text, SVSFlagsAsync   'Speak the user-editable text

    'Check status periodically
    Do
        For ii = 0 To 5000
            DoEvents
        Next ii

        Set S = V.Status    'Get status in an ISpeechVoiceStatus object

        'Text1.HideSelection must be False for this selection to be seen!

        Text1.SelStart = S.InputWordPosition
        Text1.SelLength = S.InputWordLength

    Loop Until V.Status.RunningState = SRSEDone 'Exit when voice stops

    Text1.SelLength = 0

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()

    On Error GoTo EH
    Set V = New SpVoice
    Text1.Text = "This is a sentence containing several words."

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechVoiceStatus LastBookmark Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

LastBookmark Property

The LastBookmark property retrieves the text value of the last bookmark encountered by the text-to-speech (TTS) engine.

The text value of a bookmark is enclosed in an XML attribute called Mark.

Syntax

Set: | (This property is read-only)
Get: | String = ISpeechVoiceStatus.LastBookmark

Parts

ISpeechVoiceStatus
The owning object.
String
Set: (This property is read-only)
Get: A String variable returning the string value of the last bookmark.

Example

The following Visual Basic form code demonstrates the use of the LastBookmark and LastBookmarkId properties. To run this code, create a form without any controls and paste the code into the form's Declarations section.

The code creates a voice that speaks a text stream containing two bookmarks, and then calls the Status method to get an ISpeechVoiceStatus object. The code then shows how these two properties return the bookmark text and display the format of the bookmark.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Dim objVOICE As SpeechLib.SpVoice
    Dim objSTATUS As SpeechLib.ISpeechVoiceStatus

    Set objVOICE = New SpVoice

    objVOICE.Speak "<BOOKMARK MARK='1. Monday'/> monday " _
            & "<bookmark mark='2. Tuesday'/> tuesday ", SVSFIsXML

    Set objSTATUS = objVOICE.Status

    MsgBox "LastBookmark is " & objSTATUS.LastBookmark      ' "2. Tuesday"
    MsgBox "LastBookmarkId is " & objSTATUS.LastBookmarkId  ' "2"
    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechVoiceStatus LastBookmarkId Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

LastBookmarkId Property

The LastBookmarkId property retrieves the ID of the last bookmark encountered by the text-to-speech (TTS) engine.

The text value of a bookmark is enclosed in an XML attribute called Mark. The bookmark ID consists of the numeric integer value of the leading characters of the bookmark text. For example, in a bookmark with text "17.53.01 Section 53," the bookmark ID would be "17." A bookmark with text that begins with a non-numeric character will always have a bookmark ID of zero.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechVoiceStatus.LastBookmarkId

Parts

ISpeechVoiceStatus
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the ID of the last bookmark.

Example

The following Visual Basic form code demonstrates the use of the LastBookmark and LastBookmarkId properties. To run this code, create a form without any controls and paste the code into the form's Declarations section.

The code creates a voice that speaks a text stream containing two bookmarks, and then calls the Status method to get an ISpeechVoiceStatus object. The code then shows how these two properties return the bookmark text and display the format of the bookmark.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Dim objVOICE As SpeechLib.SpVoice
    Dim objSTATUS As SpeechLib.ISpeechVoiceStatus

    Set objVOICE = New SpVoice

    objVOICE.Speak "<BOOKMARK MARK='1. Monday'/> monday " _
            & "<bookmark mark='2. Tuesday'/> tuesday ", SVSFIsXML

    Set objSTATUS = objVOICE.Status

    MsgBox "LastBookmark is " & objSTATUS.LastBookmark      ' "2. Tuesday"
    MsgBox "LastBookmarkId is " & objSTATUS.LastBookmarkId  ' "2"
    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechVoiceStatus LastHResult Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

LastHResult Property

The LastHResult property retrieves the HResult, or internal status code, from the last Speak or SpeakStream operation performed by the SpVoice object.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechVoiceStatus.LastHResult

Parts

ISpeechVoiceStatus
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the HResult.

Example

The following Visual Basic form code demonstrates the use of the LastHResult property of an ISpeechVoiceStatus object. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object. The Command1_Click procedure speaks a text stream asynchronously. The LastHResult property value is displayed in the text box. A value of 0 indicates completion with no error.

Option Explicit

Dim V As SpeechLib.SpVoice

Private Sub Command1_Click()
    On Error GoTo EH

    V.Speak "This is a text stream", SVSFlagsAsync

    'wait for maximum 10 seconds to finish speaking
    V.WaitUntilDone 10000

    Text1.Text = Format(V.Status.LastHResult)

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()

    Set V = New SpVoice

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechVoiceStatus LastStreamNumberQueued Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

LastStreamNumberQueued Property

The LastStreamNumberQueued property retrieves the number of the last audio stream enqueued by the voice.

Syntax

Set: | (This property is read-only)
Get: | Long = ISpeechVoiceStatus.LastStreamNumberQueued

Parts

ISpeechVoiceStatus
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the stream number of the last audio stream spoken.

Example

The following code snippet demonstrates the use of the LastStreamNumberQueued property. To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object. The Command1_Click procedure speaks three streams asynchronously, creates an ISpeechVoiceStatus object and prints the LastStreamNumberQueued property value. The WaitUntilDone method then blocks execution until the voice finishes speaking the three streams, and the LastStreamNumberQueued property value is printed again. The value of the LastStreamNumberQueued property in both cases is 3.

Option Explicit

Private V As SpeechLib.SpVoice
Private S As SpeechLib.ISpeechVoiceStatus

Private Sub Command1_Click()
    On Error GoTo EH

    'Enqueue three streams

    V.Speak "this is stream number one.", SVSFlagsAsync
    V.Speak "a second stream, now.", SVSFlagsAsync
    V.Speak "the third stream is next", SVSFlagsAsync

    'Get status while voice is speaking

    Set S = V.Status  'Get status thru ISpeechVoiceStatus object

    Print "Voice is speaking and LastStreamNumberQueued is " _
            & S.LastStreamNumberQueued
    DoEvents  'Let Print results be seen immediately

    V.WaitUntilDone (99999)     'Wait until voice finishes

    'Get status thru "Voice.Status.Property" syntax

    Print "Voice is finished and LastStreamNumberQueued is " _
            & V.Status.LastStreamNumberQueued

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()

    Set V = New SpVoice

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechVoiceStatus PhonemeId Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

PhonemeId Property

The PhonemeId property retrieves the ID of the current phoneme being spoken by the voice.

Syntax

Set: | (This property is read-only)
Get: | Integer = ISpeechVoiceStatus.PhonemeId

Parts

ISpeechVoiceStatus
The owning object.
Integer
Set: (This property is read-only)
Get: An Integer variable returning the Phoneme ID.

Example

The following Visual Basic form code demonstrates the use of the PhonemeId property of an ISpeechVoiceStatus object. To run this code, create a form with the following controls:

  • A command button called Command1
  • Two text boxes called Text1 and Text2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object and places a sentence in the text box. The Command1_Click procedure speaks the contents of the text box asynchronously, and loops until the voice has finished speaking. Inside the loop, the code checks PhonemeId property periodically and displays it in Text2.

Option Explicit

Private V As SpeechLib.SpVoice

Private Sub Command1_Click()
    Dim ii As Integer

    On Error GoTo EH

    Text2.Text = ""
    V.Speak Text1.Text, SVSFlagsAsync

    Do
        For ii = 0 To 20000
            DoEvents
        Next ii
        Text2.Text = Text2.Text & V.Status.PhonemeId & " "

    Loop While V.Status.RunningState = SRSEIsSpeaking

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Set V = New SpVoice
    Text1.Text = "way, we, why, woe, woo."
    Text2.Text = ""

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechVoiceStatus RunningState Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

RunningState Property

The RunningState property retrieves the run state of the voice, which indicates whether the voice is speaking or inactive.

The values of the RunningState property are contained in the SpeechRunState enumeration.

Syntax

Set: | (This property is read-only)
Get: | SpeechRunState = ISpeechVoiceStatus.RunningState

Parts

ISpeechVoiceStatus
The owning object.
SpeechRunState
Set: (This property is read-only)
Get: A SpeechRunState constant returning the run state of the voice.

Example

The following Visual Basic form code demonstrates the use of the RunningState property of an ISpeechVoiceStatus object. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1
  • A timer called Timer1

Paste this code into the Declarations section of the form.

The Form_Load procedure places a sentence in the text box and creates two voice objects, one with an alert Priority setting. In the Command1_Click procedure, the timer is activated, and the normal Priority voice enqueues the contents of the text box, and waits a tenth of a second. Then the alert Priority voice speaks a short stream which interrupts the normal voice.

The timer procedure changes the color of the text box depending on the run state of the normal voice. When the normal voice is speaking, the text color is red; when it is done speaking, the text color is blue; when the voice is not speaking, the text color is black.

The text color change in this example has no significance other than indicating the running state of the normal voice.

Option Explicit

Private V As SpeechLib.SpVoice
Private VHim As SpeechLib.SpVoice

Private Sub Command1_Click()
    On Error GoTo EH

    Timer1.Interval = 250
    Timer1.Enabled = True

    'Make sure normal voice starts first
    V.Speak Text1.Text, SVSFlagsAsync
    V.WaitUntilDone (100)
    VHim.Speak "Alert voice!", SVSFlagsAsync

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Set V = New SpVoice
    Text1.Text = "turn this text red while the voice is speaking it"
    Set V.Voice = V.GetVoices("Gender=Female").Item(0)

    Set VHim = New SpVoice
    VHim.Priority = SVPAlert
    Set VHim.Voice = VHim.GetVoices("Gender=Male").Item(0)
EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Timer1_Timer()
    On Error GoTo EH

    Select Case V.Status.RunningState
        Case SRSEIsSpeaking
            Text1.ForeColor = vbRed
        Case SRSEDone
            Text1.ForeColor = vbBlue
        Case Else
            Text1.ForeColor = vbBlack
    End Select

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechVoiceStatus VisemeId Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

VisemeId Property

The VisemeId property retrieves the ID of the current viseme being spoken by the voice.

Syntax

Set: | (This property is read-only)
Get: | Integer = ISpeechVoiceStatus.VisemeId

Parts

ISpeechVoiceStatus
The owning object.
Integer
Set: (This property is read-only)
Get: An Integer variable returning the VisemeId.

Example

The following Visual Basic form code demonstrates the use of the VisemeId property of an ISpeechVoiceStatus object. To run this code, create a form with the following controls:

  • A command button called Command1
  • Two text boxes called Text1 and Text2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object and places a sentence in the text box. The Command1_Click procedure speaks the contents of the text box asynchronously, and loops until the voice has finished speaking. Inside the loop, the code checks VisemeId property periodically and displays it in Text2.

Option Explicit

Private V As SpeechLib.SpVoice

Private Sub Command1_Click()
    Dim ii As Integer

    On Error GoTo EH

    Text2.Text = ""
    V.Speak Text1.Text, SVSFlagsAsync

    Do
        For ii = 0 To 20000
            DoEvents
        Next ii
        Text2.Text = Text2.Text & V.Status.VisemeId & " "

    Loop While V.Status.RunningState = SRSEIsSpeaking

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()

    Set V = New SpVoice
    Text1.Text = "say, see, sigh, so, sue."
    Text2.Text = ""

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechVoiceStatus Example (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechVoiceStatus

ISpeechVoiceStatus

Example

The following code snippet demonstrates the use of all ISpeechVoiceStatus properties. To run this code, create a form with the following controls:

  • A command button called Command1
  • A list box called List1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object. The Command1_Click procedure speaks two streams asynchronously, and adds status information into the list box every one-half second until both streams have been spoken.

Option Explicit

Private V As SpeechLib.SpVoice

Private Sub Command1_Click()
    On Error GoTo EH
    List1.Clear

    'Enqueue two streams containing bookmarks:
    V.Speak "this is stream number<bookmark mark='1one'/> one.", SVSFlagsAsync + SVSFIsXML
    List1.AddItem "LastStreamNumberQueued is " & V.Status.LastStreamNumberQueued
    DoEvents

    V.Speak "this is stream number<bookmark mark='2two'/> two.", SVSFlagsAsync + SVSFIsXML
    List1.AddItem "LastStreamNumberQueued is " & V.Status.LastStreamNumberQueued
    DoEvents

    Do
        V.WaitUntilDone (500) 'Wait for 0.5 second so we won't get too many outputs

        List1.AddItem ""
        List1.AddItem "LastStreamNumberQueued is " & V.Status.LastStreamNumberQueued
        List1.AddItem "CurrentStreamNumber is " & V.Status.CurrentStreamNumber
        List1.AddItem "InputSentenceLength is " & V.Status.InputSentenceLength
        List1.AddItem "InputSentencePosition is " & V.Status.InputSentencePosition
        List1.AddItem "InputWordLength is " & V.Status.InputWordLength
        List1.AddItem "InputWordPosition is " & V.Status.InputWordPosition
        List1.AddItem "RunningState is " & V.Status.RunningState
        List1.AddItem "LastBookmark is " & V.Status.LastBookmark
        List1.AddItem "LastBookmarkId is " & V.Status.LastBookmarkId
        List1.AddItem "VisemeId is " & V.Status.VisemeId
        List1.AddItem "PhonemeId is " & V.Status.PhonemeId
        List1.AddItem "LastHResult is " & V.Status.LastHResult
        DoEvents

    Loop Until V.Status.RunningState = SRSEDone 'Exit when voice stops

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    Set V = New SpVoice
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechXMLRecoResult (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechXMLRecoResult

New in SAPI 5.3

Gets recognition results from the ISpXMLRecoResult as an SML document.

The ISpeechXMLRecoResult automation interface is used to acquire the semantic results of speech recognition and return them as an SML document.

Recognition results are returned in Semantic Markup Language (SML), an XML format defined in the W3C document Semantic Interpretation for Speech Recognition.

Automation Interface Elements

The ISpeechXMLRecoResult automation interface contains the following elements:

Methods | Description
GetXMLResult | Returns the recognition result as Semantic Markup Language (SML).
GetXMLErrorInfo | Returns details of an error that occurred during semantic processing.


ISpeechXMLRecoResult GetXMLErrorInfo Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechXMLRecoResult

GetXMLErrorInfo Method

The GetXMLErrorInfo method is used to discover the details of an error that occurred during semantic processing.

ISpeechXMLRecoResult.GetXMLErrorInfo(
    LineNumber As Long,
    ScriptLine As String,
    Source As String,
    Description As String,
    ResultCode As Long
) As Boolean

Parameters

LineNumber
The line number where the error occurred.
ScriptLine
The text of the line where the error occurred.
Source
The location of the file in which the error occurred.
Description
A description of the error.
ResultCode
The code number of the error.

Return Value

True if an error did occur during semantic processing or else false.


ISpeechXMLRecoResult GetXMLResult Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechXMLRecoResult

GetXMLResult Method

The GetXMLResult method returns the result as Semantic Markup Language (SML).

Recognition results are returned in Semantic Markup Language (SML), an XML format defined in the W3C document Semantic Interpretation for Speech Recognition.

ISpeechXMLRecoResult.GetXMLResult(
    Options As SPXMLRESULTOPTIONS
) As String

Parameters

Options
An element in the enumeration that specifies whether the primary result (0) or the alternate results (1) should be returned.

Return Value

A String that is the result formatted as Semantic Markup Language.


SpAudioFormat Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpAudioFormat

The SpAudioFormat automation object represents an audio format.

Most applications using standard audio formats will use the Type property to set and retrieve formats. Non-standard formats using wav files will use SetWavFormatEx and GetWaveFormatEx to set and retrieve formats, respectively. Non-standard formats using sources other than wav files use Guid.

Automation Interface Elements

The SpAudioFormat automation object has the following elements:

Properties | Description
Guid Property | Returns the GUID of the default format.
Type Property | Gets and sets the speech audio format as a SpeechAudioFormatType.
Methods | Description
GetWaveFormatEx Method | Gets the audio format as an SpWaveFormatEx object.
SetWaveFormatEx Method | Sets the audio format with an SpWaveFormatEx object.


SpAudioFormat GetWaveFormatEx method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpAudioFormat
Type: Hidden

GetWaveFormatEx Method

The GetWaveFormatEx method gets the audio format as an SpWaveFormatEx object.

Non-standard formats using wav files should use GetWaveFormatEx to retrieve formats.

SpAudioFormat.GetWaveFormatEx() As SpWaveFormatEx

Parameters

None.

Return Value

The GetWaveFormatEx method returns an SpWaveFormatEx variable.

Example

The following Visual Basic form code demonstrates the use of the GetWaveFormatEx and SetWaveFormatEx properties. To run this code, create a form with the following controls:

  • Two command buttons called Command1 and Command2

Paste this code into the Declarations section of the form.

The Command1 procedure creates an SpAudioFormat object and sets it to the audio format SAFT22kHz16BitStereo. It then gets the format object's SpWaveFormatEx object and displays the properties. The code then changes the format of the SpAudioFormat object to SAFT11kHz16BitMono, gets a new SpWaveFormatEx object and displays its properties again. Note that the SpWaveFormatEx properties have changed to reflect the new audio format.

The Command2 procedure creates an SpAudioFormat object and sets it to the audio format SAFT22kHz16BitStereo. It then gets the format object's SpWaveFormatEx object and displays the properties. The code then changes the properties of the SpWaveFormatEx object to match the SAFT11kHz16BitMono format and sets the format of the SpAudioFormat object with the SetWaveFormatEx method. Note that the SpAudioFormat object's Type property has changed to SAFT11kHz16BitMono to reflect the new SpWaveFormatEx properties.

Option Explicit

Dim F As SpeechLib.SpAudioFormat
Dim W As SpeechLib.SpWaveFormatEx

Private Sub Command1_Click()
    On Error GoTo EH

    'Create an empty SpAudioFormat object
    'Set it to the default format
    'Get its format in an SpWaveFormatEx object
    Set F = New SpAudioFormat
    F.Type = SAFT22kHz16BitStereo
    Set W = F.GetWaveFormatEx

    Debug.Print
    Debug.Print "Default SpAudioFormat and SpWaveFormatEx"
    Debug.Print "Format:        SAFT22kHz16BitStereo"
    Debug.Print "Format code:   " & F.Type
    Debug.Print "AvgBytesPerSec " & W.AvgBytesPerSec
    Debug.Print "BitsPerSample  " & W.BitsPerSample
    Debug.Print "BlockAlign     " & W.BlockAlign
    Debug.Print "Channels       " & W.Channels
    Debug.Print "ExtraData      " & W.ExtraData
    Debug.Print "FormatTag      " & W.FormatTag
    Debug.Print "SamplesPerSec  " & W.SamplesPerSec

    'Give the SpAudioFormat object an audio type
    'Get its format in an SpWaveFormatEx object
    F.Type = SAFT11kHz16BitMono
    Set W = F.GetWaveFormatEx

    Debug.Print
    Debug.Print "Changing SpAudioFormat changes SpWaveFormatEx"
    Debug.Print "Format:        SAFT11kHz16BitMono"
    Debug.Print "Format code:   " & F.Type
    Debug.Print "AvgBytesPerSec " & W.AvgBytesPerSec
    Debug.Print "BitsPerSample  " & W.BitsPerSample
    Debug.Print "BlockAlign     " & W.BlockAlign
    Debug.Print "Channels       " & W.Channels
    Debug.Print "ExtraData      " & W.ExtraData
    Debug.Print "FormatTag      " & W.FormatTag
    Debug.Print "SamplesPerSec  " & W.SamplesPerSec

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH

    'Create an empty SpAudioFormat object
    'Set it to the default format
    'Get its format in an SpWaveFormatEx object

    Set F = New SpAudioFormat
    F.Type = SAFT22kHz16BitStereo
    Set W = F.GetWaveFormatEx

    Debug.Print
    Debug.Print "Default SpAudioFormat and SpWaveFormatEx:"
    Debug.Print "Format:        SAFT22kHz16BitStereo"
    Debug.Print "Format code:   " & F.Type
    Debug.Print "AvgBytesPerSec " & W.AvgBytesPerSec
    Debug.Print "BitsPerSample  " & W.BitsPerSample
    Debug.Print "BlockAlign     " & W.BlockAlign
    Debug.Print "Channels       " & W.Channels
    Debug.Print "ExtraData      " & W.ExtraData
    Debug.Print "FormatTag      " & W.FormatTag
    Debug.Print "SamplesPerSec  " & W.SamplesPerSec

    'Set SpWaveFormatEx properties as in SAFT11kHz16BitMono format;
    'this will reset the SpAudioFormat Type.

    Debug.Print
    Debug.Print "Changing SpWaveFormatEx properties changes SpAudioFormat:"
    W.AvgBytesPerSec = 22050
    W.BitsPerSample = 16
    W.BlockAlign = 2
    W.Channels = 1
    W.SamplesPerSec = 11025

    Call F.SetWaveFormatEx(W)
    Debug.Print "Format code:   " & F.Type

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpAudioFormat Guid Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpAudioFormat

Guid Property

The Guid property returns the GUID of the default audio format.

Non-standard formats using sources other than wav files should use Guid to set and retrieve formats.

Syntax

Set: | SpAudioFormat.Guid = String
Get: | String = SpAudioFormat.Guid

Parts

SpAudioFormat
The owning object.
String
Set: A String variable that sets the property.
Get: A String variable that gets the property.

Example

For an example of the use of the Guid property, see the code example in the Type section.


SpAudioFormat SetWaveFormatEx method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpAudioFormat
Type: Hidden

SetWaveFormatEx Method

The SetWaveFormatEx method sets the audio format with an SpWaveFormatEx object.

Non-standard formats using wav files should use SetWavFormatEx to set formats.

SpAudioFormat.SetWaveFormatEx(
     WaveFormatEx As SpWaveFormatEx
)

Parameters

WaveFormatEx
Specifies the WaveFormatEx.

Return Value

None.

Example

For an example of the use of the SetWaveFormatEx method, see the GetWaveFormatEx section.


SpAudioFormat Type Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpAudioFormat

Type Property

The Type property gets and sets the speech audio format as a SpeechAudioFormatType.

Most applications using standard audio formats should use Type to set and retrieve formats.

Syntax

Set: | SpAudioFormat.Type = SpeechAudioFormatType
Get: | SpeechAudioFormatType = SpAudioFormat.Type

Parts

SpAudioFormat
The owning object.
SpeechAudioFormatType
Set: A SpeechAudioFormatType object that sets the property.
Get: A SpeechAudioFormatType object that gets the property.

Example

The following Visual Basic form code demonstrates the use of the Type and Guid properties. To run this code, create a form with the following controls:

  • Two command buttons called Command1 and Command2

Paste this code into the Declarations section of the form.

The Command1 procedure creates a token category object and sets it to the category of audio inputs, selects a token for the first MMSys resource, and instantiates an SpMMAudioIn object with the token's CreateInstance method. The code then creates an SpAudioFormat object from the SpMMAudioIn object, and changes the Type property of the SpAudioFormat object. Finally, the code sets the Format property of the SpMMAudioIn object with the SpAudioFormat object.

The Command2 procedure performs the same series of operations with audio outputs instead of audio inputs.

Option Explicit

Dim C As SpeechLib.SpObjectTokenCategory
Dim T As SpeechLib.SpObjectToken

Dim I As SpeechLib.SpMMAudioIn
Dim O As SpeechLib.SpMMAudioOut

Dim F As SpeechLib.SpAudioFormat

Private Sub Command1_Click()
    On Error GoTo EH

    Debug.Print
    Debug.Print "MMSys AudioIn"
    Debug.Print

    'Set category object to audio input resources
    Set C = New SpObjectTokenCategory
    C.SetId SpeechCategoryAudioIn

    'Set token object to first MMSys input resource
    Set T = C.EnumerateTokens("Technology=MMSys").Item(0)
    Debug.Print "First device: " & T.GetDescription

    'Create an SpMMAudioIn object from the token,
    'and show some of its properties
    Set I = T.CreateInstance()
    Debug.Print "DeviceId: " & I.DeviceId
    Debug.Print "original Audio Format:" & I.Format.Type

    'Create an Audio Format object from resource
    'If Audio Format's Type is standard, then change it
    Set F = I.Format
    If F.Type = SAFT22kHz16BitMono Then
        F.Type = SAFT11kHz16BitMono
    End If

    'Set Audioinput's format with changed format object
    Set I.Format = F
    Debug.Print " changed Audio Format:" & I.Format.Type
    Debug.Print "Guid:" & F.Guid

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH

    Debug.Print
    Debug.Print "MMSys AudioOut"
    Debug.Print
    Set C = New SpObjectTokenCategory
    C.SetId SpeechCategoryAudioOut
    Set T = C.EnumerateTokens("Technology=MMSys").Item(0)
    Debug.Print "First device: " & T.GetDescription
    Set O = T.CreateInstance()
    Debug.Print "DeviceId: " & O.DeviceId
    Debug.Print "original Audio Format:" & O.Format.Type
    Set F = O.Format
    If F.Type = SAFT22kHz16BitMono Then
        F.Type = SAFT11kHz16BitMono
    End If
    Set O.Format = F
    Debug.Print " changed Audio Format:" & O.Format.Type
    Debug.Print "Guid:" & F.Guid

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpCustomStream Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpCustomStream

The SpCustomStream automation object supports the use of existing IStream objects in SAPI.

The Format property and the Read, Write and Seek methods are inherited from the ISpeechBaseStream interface.

Automation Interface Elements

The SpCustomStream automation object has the following elements:

Properties | Description
BaseStream Property | Gets and sets the base stream object in a custom stream.
Format Property | Gets and sets the cached wave format of the stream as an SpAudioFormat object.
Methods | Description
Read Method | Reads data from an audio stream.
Seek Method | Returns the current read position of the audio stream in bytes.
Write Method | Writes data to the audio stream.


SpCustomStream BaseStream Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpCustomStream

BaseStream Property

The BaseStream property gets and sets the base stream object in a custom stream.

Syntax

Set: | SpCustomStream.BaseStream = IUnknown
Get: | IUnknown = SpCustomStream.BaseStream

Parts

SpCustomStream
The owning object.
IUnknown
Set: An Unknown variable that sets the base stream.
Get: An Unknown variable that gets the base stream.

Example

The following Visual Basic form code demonstrates the use of the BaseStream property. To run this code, create a form with following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

The From_Load procedure creates two voice objects. The Command1 procedure creates a new custom stream, uses the CreateStreamOnHGlobal API to create a new genetic Istream object, and sets the Istream as the custom stream's BaseStream property. Finally, it uses the first voice to speak a phrase into the custom stream, and then plays back the custom stream audio with the second voice.

Option Explicit

Dim V1 As SpeechLib.SpVoice
Dim V2 As SpeechLib.SpVoice
Dim C As SpeechLib.SpCustomStream

Private Declare Function CreateStreamOnHGlobal Lib "Ole32.dll" ( _
    ByVal hGlobal As Any, ByVal fDeleteOnRelease As Boolean, _
    ByRef ppStream As IStream) As Long

Private Sub Command1_Click()
    Dim GeneticIstream As SpeechLib.IStream

    On Error GoTo EH

    'Create a genetic Istream object,
    'Use as custom stream's base stream
    CreateStreamOnHGlobal 0&, True, GeneticIstream
    Set C = New SpCustomStream
    Set C.BaseStream = GeneticIstream

    'Set custom stream as voice's output stream
    'Make voice speak into the stream
    Set V1.AudioOutputStream = C
    V1.Speak "hello world"

    'Seek to beginning of stream, and speak stream
    C.Seek 0, SSSPTRelativeToStart
    V2.SpeakStream C

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    Set V1 = New SpVoice    'Creates a custom stream
    Set V2 = New SpVoice    'Speaks the custom stream
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpFileStream Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpFileStream

The SpFileStream automation object enables data streams to be read and written as files.

SpFileStream objects normally contain audio data, but may also be used for text data.

The Format property and the Read, Write and Seek methods are inherited from the ISpeechBaseStream interface.

Automation Interface Elements

The SpFileStream automation object has the following elements:

Properties | Description
Format Property | Gets and sets the cached wave format of the stream as an SpAudioFormat object.
Methods | Description
Close Method | Closes the filestream object.
Open Method | Opens a filestream object for reading or writing.
Read Method | Reads data from an audio stream.
Seek Method | Returns the current read position of the audio stream in bytes.
Write Method | Writes data to the audio stream.


SpFileStream Close Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpFileStream

Close Method

The Close method closes the filestream object.

SpFileStream.Close()

Parameters

None.

Return Value

None.

Example

For a simple example using the SpFileStream.Close method, see the SpFileStream.Open method.

The ISpeechPhraseElement code example demonstrates further use of the SPFileStream object. This example uses a text-to-speech voice to speak into an SPFileStream object, and uses the resulting file as the input for speech recognition.


SpFileStream Open Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpFileStream

Open Method

The Open method opens a filestream object for reading or writing.

SpFileStream.Open(
     FileName As String,
     [FileMode As SpeechStreamFileMode = SSFMOpenForRead],
     [DoEvents As Boolean = False]
)

Parameters

FileName
Specifies the FileName.
FileMode
[Optional] Specifies the FileMode. Default value is SSFMOpenForRead.
DoEvents
[Optional] When FileMode is SSFMCreateForWrite, DoEvents specifies whether playback of the resulting sound file will generate voice events. Default value is False.

Return Value

None.

Remarks

When the SpFileStream object is used with audio data, the FileMode parameter controls access strictly. That is, the FileMode parameter SFMOpenForRead prevents write access, and the FileMode parameter SSFMCreateForWrite prevents read access. When the SpFileStream object is used with text data, only the SFMOpenForRead FileMode parameter controls access strictly. The FileMode parameter SFMOpenForRead prevents write access, but the SSFMCreateForWrite parameter allows text data to be read as well as written.

When an SpVoice object creates an SPFileStream object, the engine may embed event data in the stream. In order to embed these events in the file stream, it must be opened for writing with the DoEvents parameter set to True. In order to receive these events when the stream is played back, it must be opened for reading with the DoEvents parameter set to True. Several other factors are involved. Please see SpVoice events for further details.

Example

The following Visual Basic form code demonstrates the use of a SpFileStream object to capture the output of a voice in a file. To run this code, create a form without any controls and paste this code into the Declarations section of the form.

The ISpeechPhraseElement code example demonstrates further use of the SpFileStream object. This example uses a text-to-speech voice to speak into an SpFileStream object, and uses the resulting file as the input for speech recognition.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Dim objVOICE As SpeechLib.SpVoice
    Dim objFSTRM As SpeechLib.SpFileStream

    Set objVOICE = New SpVoice
    Set objFSTRM = New SpFileStream

    'Open file path as a stream
    Call objFSTRM.Open("c:\VoiceToFile.wav", SSFMCreateForWrite, False)

    'Set voice output to the stream and speak
    Set objVOICE.AudioOutputStream = objFSTRM
    objVOICE.Speak "cee : \ voice to file dot wave", SVSFNLPSpeakPunc

    Call objFSTRM.Close

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechRecoContext

The ISpeechRecoContext automation interface defines a recognition context.

For a list of available methods and properties, see Method/Property List.

What is a Recognition Context?

A recognition context is the primary means by which an application interacts with the Microsoft Speech Platform for speech recognition. It is an object that allows an application to start and stop recognition, receive recognition results and other events. It also controls which words and phrases are available for the user to speak. An application may have several recognition contexts open at the same time, each controlling a different part of the application. A specific recognition context controls the collection of available words and is associated with a specific part of the application. In a more general sense, that word collection is the confine to which speech recognition attempts are restricted and will poll within to match words. Words not contained in the collection or context, will not be used for that speech recognition attempt. By setting recognition contexts, applications limit or expand the scope of the words needed for a particular aspect of the application. This granularity for speech recognition improves the quality of recognition by removing words not needed at that moment. Conversely, the granularity also allows words to be added to the application if needed.

For example, an application may have only one recognition context: that of all the words in the dictionary and those words are available all the time. If that application were purely dictation, the one-context model would work well. The user could say any word at any time to the application and it would probably be successfully recognized. However, if the application had a new requirement of exiting when the user said "close," that one-context model breaks down. The user would be disappointed if, in the course of dictation, the word "close" were spoken and the application suddenly stopped and closed.

Clearly, there are two uses (or contexts) for the word "close." The first is a part of speech ("please close the door," "that was too close for comfort," "we'll close in on the criminal"). The second context is that of a specific command. There must be a method to differentiate the two. A recognition context permits applications to do that.

Applications may have more than one recognition context. In fact, it is recommended to have as many as makes sense. For example, one recognition context may be assigned to the menu bar, another to the dictation screen, yet another to dialog boxes, even if only temporarily such as a Yes/No/Cancel dialog box. Programmers need to decide the scope of the recognition context. The menu system for an application may even have multiple recognition contexts, perhaps one for each menu bar item. This granularity grants applications the ability to concentrate resources robustly. For example, a small menu may only have 12 items associated with it. Not only that, but it would be 12 very specific words. It makes little sense, therefore, to have the entire dictation collection, some 65,000 to 100,000 words, available when in fact only 12 words are needed. The larger-than-needed vocabulary would not only take up more processing time, but could result in more mismatched words. By the same reasoning, in the "close" example above, a dictation model should treat the word "close" no differently than any other word. Two recognition contexts could be used to separate the differences.

Using Recognition Contexts

Creating a recognition context is done using a two-step process. The context must be declared and then created. The following code sample creates an instance of a recognition context named RC. The keyword New creates a reference to a new object of the specified class.

Public WithEvents RC As SpSharedRecoContext
Set RC = New SpSharedRecoContext

Recognition context types

Recognition contexts may be one of two types: shared or in process (InProc). A shared context allows resources to be used by other recognition contexts or applications. All applications on the machine using shared recognition contexts are sharing a single audio input, SR engine, and grammars. When the user speaks, the SR engine will do recognition, and SAPI decides which context to send the recognition result to, based on which grammar the result best matches. In general, most applications should use shared contexts. The following code snippet declares a shared recognition context.

Public WithEvents RC As SpSharedRecoContext

InProc contexts restrict available resources to one context or application. That is, an SR engine or microphone used by an InProc recognition context may not be used by any other applications. In situations requiring the highest performance standards, response time or exacting recognition quality, use the InProc context. InProc contexts are important to embedded systems in other hardware platforms. InProc contexts are also used for non-microphone recognition such as recognizing from a file. However, InProc should be used sparingly since it excludes other applications from the speech recognition resources. The following code snippet declares an InProc recognition context.

Public WithEvents RC As SpInProcRecoContext

In either case, the two types are based on ISpeechRecoContext. Any declaration should include the keyword WithEvents so that recognition context also supports events.

Defaults

Recognition context is created with intelligent defaults using the defaults of the computer system. These defaults are assigned using Speech properties in Control Panel. While applications may override default values for specific reasons, applications should not manually set or change default values directly. These defaults include:

  • Recognizer to determine the speech recognition engine
  • EventInterests to determine which events the speech recognition engine generates
  • RetainedAudio to persist the actual audio for the speech
  • RetainedAudioFormat to determine the retained audio format
  • Voice to speak the text

Grammars

The only resource that must be explicitly created is the grammar using CreateGrammar. The grammar defines the set of words for the recognition context. Grammars also may be of two types: dictation and command and control (C and C). Dictation grammars are usually an unrestricted word list designed to encompass the full range of words in a language. Dictation allows any word or phrase to be spoken and it is used in the traditional sense to dictate a letter or paper, for example. The following code snippet declares a dictation grammar. It assumes a valid RC recognition context.

Set myGrammar = RC.CreateGrammar
myGrammar.DictationSetState SGDSActive

A command and control grammar is a limited word list restricting the speaker to a small set of words. In this way, users can speak a command, usually a single word, with greater chance of recognition. The smaller scope of words disallows words not on a specific list. A grammar is useful for speech-enabling menus, for example. Menu grammars are typically smaller with exact word or phrase commands such as "New," "Exit," or "Open." The following code snippet declares a command and control grammar. It assumes a valid RC recognition context.

Set myGrammar = RC.CreateGrammar
myGrammar.CmdLoadFromFile "sol.xml", SLODynamic
myGrammar.CmdSetRuleIdState 101, SGDSActive

Because the word list is limited, an explicit list is used. In this case, the command file sol.xml is used. In addition, the code sample activates one rule; the rule has an identification value of 101. For a more thorough discussion of grammars and designing grammars see Text grammar format.

States

While individual grammar rules may be activated or deactivated as conditions change, all grammars in the recognition context may also be activated or deactivated with the State property. Grammars can be turned off, for example, if the window is no longer the current focus and likewise turned back on when the window becomes foremost again. In addition the recognition context may be momentarily stopped and then restarted. The Pause method halts the speech recognition temporarily for the engine to synchronize with the grammars. After a pause, Resume resumes the recognition process. While paused, the engine will continue to accept sound input and speech processing, provided the pause is not excessive; by default, this is not more than 30 seconds.

The ISpeechRecoContext object is always associated with a single speech recognition engine (also called a recognizer). However, a single recognizer may have many recognition contexts.

Events

As a result of interactions with the recognition context, the SR engine sends back certain information to the application using the Events mechanism. An event is a specific occurrence that might be of interest to the user or application. Examples of events include notifying the application of a successful recognition or indicating that a designated position in the stream has been reached. Regardless, the application is free to process events or ignore them.

In addition, events may be filtered, allowing the engine to return some or all events, or to prevent an event from being generated in the first place if it has no significance to the application. Filtering is controlled by EventInterests.

A complete list of events is described in ISpeechRecoContext events.

Automation Interface Elements

The ISpeechRecoContext automation interface contains the following elements:

Properties | Description
AllowVoiceFormatMatchingOnNextSet Property | Determines if the recognition context can change the voice format to match that of the engine.
AudioInputInterferenceStatus Property | Returns information about interference with the recognition context's audio input.
CmdMaxAlternates Property | Specifies the maximum number of alternates that will be generated for command and control grammars.
EventInterests Property | Specifies the types of events raised by the object.
Recognizer Property | Identifies the recognizer associated with the recognition context.
RequestedUIType Property | Specifies the UIType of the last UI requested from the engine.
RetainedAudio Property | Gets and sets the audio retention status of the recognition context.
RetainedAudioFormat Property | Gets and sets the format of audio retained by the recognition context.
State Property | Gets or sets the active state of the recognition context.
Voice Property | Specifies the SpVoice object associated with the recognition context.
VoicePurgeEvent Property | Gets and sets the collection of SpeechRecoEvents which will stop the voice and purge the voice queue.
Methods | Description
Bookmark Method | Sets a bookmark within the current recognition stream.
CreateGrammar Method | Creates an SpGrammar object.
CreateResultFromMemory Method | Creates a recognition result object from a phrase that has been saved to memory.
Pause Method | Pauses the engine object to synchronize with the SR engine.
Resume Method | Releases the SR engine from the paused state and restarts the recognition process.
SetAdaptationData Method | Passes the SR engine a string of adaptation data.


SpeechRecoContext AllowVoiceFormatMatchingOnNextSet Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext
Type: Hidden

AllowVoiceFormatMatchingOnNextSet Property

The AllowVoiceFormatMatchingOnNextSet property determines if the recognition context can change the audio format of the output voice to match the audio format of the input stream.

AllowVoiceFormatMatchingOnNextSet can be used only if a voice has been created through the recognition context. If this property is set to True, the voice's output format will be set to the same format as the associated SR engine's audio input format. This conversion takes place only during the next setting of the SpVoice.Voice. However, if this voice object has already been bound to a stream which has specific format, the voice's format will not be changed to the SR engine's audio input format even if set to True. If False, the conversion is not made.

Using the same audio format for input and output source is useful for sound cards that do not support full-duplex audio (i.e., input format must match output format). If the input format quality is lower than the output format quality, the output format quality will be reduced to equal the input quality.

By default, AllowVoiceFormatMatchingOnNextSet is set to True.

Syntax

Set: | ISpeechRecoContext.AllowVoiceFormatMatchingOnNextSet = Boolean
Get: | Boolean = ISpeechRecoContext.AllowVoiceFormatMatchingOnNextSet

Parts

SpeechRecoContext
The owning object.
Boolean
Set: A Boolean variable that sets the property.
Get: A Boolean variable that gets the property.

Example

The following Visual Basic form code demonstrates retrieving and setting AllowVoiceFormatMatchingOnNextSet. Paste this code into the Declarations section of the form.

Option Explicit

Public WithEvents RecognitionContext As SpSharedRecoContext
Private Sub Form_Load()
    On Error GoTo EH

    Set RecognitionContext = New SpSharedRecoContext
    Dim voiceChange As Boolean

    voiceChange = RecognitionContext.AllowVoiceFormatMatchingOnNextSet
    RecognitionContext.AllowVoiceFormatMatchingOnNextSet = True
    voiceChange = RecognitionContext.AllowVoiceFormatMatchingOnNextSet

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext AudioInputInterferenceStatus Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

AudioInputInterferenceStatus Property

The AudioInputInterferenceStatus property returns information about interference with the audio input of the recognition context.

This information is usually returned by the ISpeechRecoContext Interference event.

Syntax

Set: | (This property is read-only)
Get: | SpeechInterference = SpeechRecoContext.AudioInputInterferenceStatus

Parts

SpeechRecoContext
The owning object.
SpeechInterference
Set: (This property is read-only)
Get: A SpeechInterference constant reflecting the interference type.

Example

The following Visual Basic form code demonstrates retrieving the interference status for the last recognition. To run this code, paste it into the Declarations section of a form.

Option Explicit

Public WithEvents RecognitionContext As SpSharedRecoContext

Private Sub Form_Load()
    On Error GoTo EH

    Const NL = vbNewLine
    Dim Interference As SpeechInterference
    Dim T As String

    ' Speech processing code would go here.

    Set RecognitionContext = New SpSharedRecoContext
    Interference = RecognitionContext.AudioInputInterferenceStatus

    If Interference = 0 Then
        T = "No interference. The AudioInputInterferenceStatus" & NL
        T = T & "property must return a value greater than 0 in order" & NL
        T = T & "to raise the Interference event of a recognition object."
        MsgBox T, vbInformation
    End If

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext Bookmark Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

Bookmark Method

The Bookmark method sets a bookmark within the current recognition stream.

A bookmark relates an audio stream position with an occurrence significant to the application. The speech recognition (SR) engine has a latency period between the speech and the recognition. This latency may be caused by a long speech period (the engine must have all the phrase before processing it) or other events may already be queued and the engine must finishing process those first. However, during that latent period, the user or application may continue operations (such as moving the mouse or speaking). As a result, the condition of the application may be different when the recognition comes back than it was when recognition was initiated. A bookmark allows the application to mark or record a condition of the application to a particular recognition attempt.

Bookmark is a convenient alternative to polling the engine for stream position (see ISpeechRecognizer.Status). A Bookmark event is returned when the bookmark has been processed by the engine. See ISpeechRecoContext.Bookmark for further information.

SpeechRecoContext.Bookmark(
     Options As SpeechBookmarkOptions,
     StreamPos As Variant,
     BookmarkId As Variant
)

Parameters

Options
Specifies whether the recognition context will pause when encountering bookmarks. This must be value of type SpeechBookmarkOptions.
StreamPos
Specifies the stream position. This value may be anywhere in the stream and will send a Bookmark event when that position is reached. Additionally it may be any one of two special values: Speech_StreamPos_Asap or Speech_StreamPos_RealTime.
BookmarkId
Specifies the BookmarkId. BookmarkId is additional information provided by the application and is unique to the application. As a Variant data type, it may be numeric, String, or any other format and is used to pass information within the method or event. If BookmarkId is a String, the value must be able to convert to a numeric value. This information is returned back using the Bookmark event.

Return Value

None.

Remarks

An application that wants to display a recognition progress meter, for example could use ISpeechRecoContext.Bookmark and update the UI when each bookmark is received.

Example

The following Visual Basic form code demonstrates the use of the Bookmark method and its associated event. Each Bookmark event can be identified by the setting of the BookmarkId paramater and that value may be used inside the event for additional processing. Additional events may be raised by adding new Bookmarks. This example assumes that the grammar file is located at C:\sol.xml.

To run this code, paste it into the Declarations section of a form without any controls.

Option Explicit

Dim WithEvents RecoContext As SpInProcRecoContext

Private Sub Form_Load()
    On Error GoTo EH

    Const Text = "One of the world's seven wonders"
    Dim Grammar As ISpeechRecoGrammar
    Dim Recognizer As SpInprocRecognizer
    Dim Voice As SpVoice

    Set Voice = New SpVoice
    Set Recognizer = New SpInprocRecognizer

    ' Set up speech recognition and grammar (assumes
    ' grammar file is at "C:\sol.xml"):
    Set RecoContext = Recognizer.CreateRecoContext
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.CmdLoadFromFile "C:\sol.xml"

    ' Set first bookmark before recognition.
    RecoContext.Bookmark SBONone, 0, "5"

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    ' Set second bookmark after recognition.
    RecoContext.Bookmark SBONone, 0, "10"

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Bookmark _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal BookmarkId As Variant, _
    ByVal Options As SpeechLib.SpeechBookmarkOptions)

    If BookmarkId = 5 Then
        MsgBox "Bookmark 5 event raised", vbInformation
    ElseIf BookmarkId = 10 Then
        MsgBox "Bookmark 10 event raised", vbInformation
    End If

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext CmdMaxAlternates Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

CmdMaxAlternates Property

The CmdMaxAlternates property specifies the maximum number of alternates that will be generated for command and control grammars.

By default, the maximum alternates value is zero, so an application must call this method before attempting to retrieve or depend on alternates for command and control. Not all speech recognition engines support command and control or proprietary grammar alternates. If the particular engine does not support alternates, this method will indicate it has succeeded but the number of alternates returned will always be zero.

CmdMaxAlternates has no effect on dictation alternates. See ISpeechRecoResult.Alternates for information regarding dictation alternates.

Syntax

Set: | SpeechRecoContext.CmdMaxAlternates = Long
Get: | Long = SpeechRecoContext.CmdMaxAlternates

Parts

SpeechRecoContext
The owning object.
Long
Set: A Long variable setting the maximum number of alternates.
Get: A Long variable retrieving the maximum number of alternates.

Remarks

Versions of the Microsoft speech recognition engine up to 5.1 did not support command and control alternates, but versions 6.0 and above do. Other manufacturers' engines may also support alternates.

Example

The following Visual Basic form code demonstrates how to retrieve the current number of alternates. However, because not all engines support the alternates feature, SAPI may throw an SPERR_NOT_FOUND exception (that is, -2147200966) if the attribute does not exist. If the attribute does exist, no error will occur and cfgAttribute will be valid, even if only as Empty.

To run this code, paste it into the Declarations section of a form that contains no controls. This code also needs a reference set to simpleaudio 1.0 Type Library to run correctly.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition and explicitly set
    ' flag to retain audio portion of recognition
    ' (default behavior is not to retain):
    Set RecoContext = Recognizer.CreateRecoContext
    RecoContext.RetainedAudio = SRAORetainAudio
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim cfgAttribute As String
    Dim numAlternates As Long
    Dim objToken As Object

    On Error GoTo EH

    Set objToken = Result.RecoContext.Recognizer.Recognizer
    cfgAttribute = objToken.GetAttribute("CGFAlternates")
    numAlternates = Result.RecoContext.CmdMaxAlternates
    MsgBox "# of alternates", vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext CreateGrammar Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

CreateGrammar Method

The CreateGrammar method creates an object based on ISpeechRecoGrammar.

Before speech recognition takes place, a speech recognition (SR) engine requires two things: grammar creation and grammar activation. A recognizer may have more than one grammar associated with it although they are usually limited to one each of two types: dictation and context free grammar (CFG). CFG is used for command and control. The recognizer can have more than one active grammar of the same type open at one time. In this case, the recognition is assigned to the grammar in which a unique match is made. If more than one grammar can match the recognition, the earliest opened grammar will receive the recognition.

A grammar must be activated prior to use. Call ISpeechRecoGrammar.DictationSetState to activate or deactivate a dictation grammar. ISpeechRecoGrammar.CmdSetRuleState is used to activate or deactivate a command and control rule which also controls the associated grammar. By controlling the state of grammars, different grammars may be used at different times.

SpeechRecoContext.CreateGrammar(
     [GrammarId As Variant = 0]
) As ISpeechRecoGrammar

Parameters

GrammarId
[Optional] Specifies the GrammarId. The GrammarId identifies each grammar. The values do not have to be unique although each grammar instance can only have one identifier. The default value is zero.

Return Value

The CreateGrammar method returns an ISpeechRecoGrammar variable.

Example

The following Visual Basic form code demonstrates two ways of creating and activating a grammar: a dictation grammar or a command and control grammar. Both example grammars have a GrammarId of zero. The zero for the GrammarId is not required as it is the default. In the case of the dictation grammar, it is set up and activated by calling ISpeechRecoGrammar.DictationLoad and ISpeechRecoGrammar.DictationSetState.

The command and control grammar is handled differently. You first need to specify a grammar file by calling one of the command load methods (in this example, ISpeechRecoGrammar.CmdLoadFromFile. See the ISpeechRecoGrammar interface for more loading options. Then a call to ISpeechRecoGrammar.CmdSetRuleIdState activates the grammar.

To run this code, paste it into the Declarations section of a form that contains two command button controls named Command1 and Command2.

Option Explicit

Dim RC As SpSharedRecoContext
Dim Grammar As ISpeechRecoGrammar

Private Sub Form_Load()
    On Error GoTo EH

    Set RC = New SpSharedRecoContext
    Set Grammar = RC.CreateGrammar(0)

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()
    On Error GoTo EH

    With Grammar
        .DictationLoad
        .DictationSetState SGDSActive
        MsgBox .State, vbInformation
        End
    End With

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH

    With Grammar
        .CmdLoadFromFile "C:\sol.xml", SLODynamic
        .CmdSetRuleIdState 0, SGDSActive
        MsgBox .State, vbInformation
    End With

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext CreateResultFromMemory Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

CreateResultFromMemory Method

The CreateResultFromMemory method creates a recognition result object from a saved recognition result.

The result must have been created with ISpeechRecoResult.SaveToMemory.

SpeechRecoContext.CreateResultFromMemory(
     ResultBlock As Variant
) As ISpeechRecoResult

Parameters

ResultBlock
A Variant variable containing a saved recognition result.

Return Value

An ISpeechRecoResult object.

Example

The following Visual Basic form code demonstrates the use of the SpeechRecoContext.CreateResultFromMemory and ISpeechRecoResult.SaveToMemory methods. The example displays the text of the current recognition as well as the previous one; it also plays the retained audio associated with the last recognition.

To run this code, create a form with the following controls:

  • A command button called Command1
  • A command button called Command2

Paste this code into the Declarations section of the form. The code also needs a reference to be set to simpleaudio 1.0 Type Library to run correctly.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Dim LastPhrase As Variant
Dim Output As Variant

Private Sub Form_Load()
    On Error GoTo EH

    LastPhrase = Empty
    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition:
    Set RecoContext = Recognizer.CreateRecoContext
    RecoContext.RetainedAudio = SRAORetainAudio
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()

    Const Text = "One of the world's seven wonders"

    On Error GoTo EH
    EndofStream = False

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()

    Const Text = "Good man is hard to find"

    On Error GoTo EH
    EndofStream = False

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Dim SavedText As String
    Static T As String

    On Error GoTo EH

    If IsEmpty(LastPhrase) = False Then
        Dim GetRecoResult As ISpeechRecoResult
        Set GetRecoResult = RecoContext.CreateResultFromMemory(LastPhrase)

        SavedText = GetRecoResult.PhraseInfo.GetText
        T = "Last phrase: " & SavedText
        GetRecoResult.SpeakAudio
    End If

    LastPhrase = Result.SaveToMemory

    T = T & vbNewLine & "New phrase: " & Result.PhraseInfo.GetText
    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext EventInterests Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

EventInterests Property

The EventInterests property specifies the types of events accepted by the SpeechRecoContext object.

An event interest is a filtering mechanism for each recognition context. By setting EventInterests, the recognition context allows or denies speech recognition engine events to reach the application. All, none or selected types of events my be filtered. By default, speech recognition allows all events except SREAudioLevel (a change in audio level).

Syntax

Set: | SpeechRecoContext.EventInterests = SpeechRecoEvents
Get: | SpeechRecoEvents = SpeechRecoContext.EventInterests

Parts

SpeechRecoContext
The owning object.
SpeechRecoEvents
Set: One or more SpeechRecoEvents constants which set the property.
Get: A SpeechRecoEvents variable which gets the value of the property.

Remarks

href="VB_Enum_SpeechRecoEvents.htm">SpeechRecoEvents enumeration list. Each type of event is represented by its own enumerated value. The default value is 327,679 (all SpeechRecoEvents values except SREAudioLevel). The value passed in to EventInterests is the total of each of the events required for the application. For example:

SRESoundStart + SRERecognition
could be passed as the value. Alternatively the same two interests could be passed as the single value of 18; SRESoundStart (value 2) plus SRERecognition (value 16). Conversely, if the application retrieved the current event setting and the value was 1064, it indicates that three events are active. Only SREPhraseStart (value 8), SREHypothesis (value 32), and SREInterference (value 1024) add up to that 1064 value.

See SpVoice.EventInterests for additional details. SpVoice.EventInterests is a similar function but affects text-to-speech events.

Example

The following Visual Basic form code demonstrates reading and setting the event interest. To run this code, paste it into the Declarations section of a form that contains no controls.

Option Explicit

Private Sub Form_Load()

    Dim EvtInterests As SpeechRecoEvents
    Dim RecoContext As SpInProcRecoContext
    Dim Recognizer As SpInprocRecognizer

    On Error GoTo EH

    Set Recognizer = New SpInprocRecognizer
    Set RecoContext = Recognizer.CreateRecoContext

    ' Read default value of EventInterests:
    EvtInterests = RecoContext.EventInterests
    MsgBox "Default: " & EvtInterests, vbInformation

    ' Set EventInterests to combination of three values:
    RecoContext.EventInterests = SRESoundStart + SREBookmark + SREFalseRecognition
    EvtInterests = RecoContext.EventInterests
    MsgBox EvtInterests, vbInformation
    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext Pause Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

Pause Method

The Pause method pauses the engine object to synchronize with the speech recognition (SR) engine.

Pause stops the SR engine at a synchronization point to change grammars and rule states. A synchronization point occurs after any Recognition event, Bookmark event or as soon as possible after explicitly calling Pause. After synchronizing grammars and rule states, the engine continues recognizing if Resume is called.

After the application has changed the state or grammar, it should call ISpeechRecoContext.Resume. A call to Resume must be made for every call made to Pause. SAPI will automatically feed the buffered audio data into the SR engine, ensuring that no real-time audio data is lost and that the user experience is not interrupted. SAPI will restart the SR engine once Resume has been called.

During the pause, SAPI continues to collect and store audio input in an audio buffer. The SAPI audio buffer has a static limit to prevent SAPI applications or SR engines from consuming large amounts of system memory. If the speech recognition engine pauses too long, and the audio buffer fills, then a buffer overflow (SPERR_AUDIO_BUFFER_OVERFLOW) occurs. This would result in interruptions of other applications running SAPI. The buffer is set to 30 times the average bytes per second or approximately 30 seconds. Consequently, the audio data collected between the point when the buffer overflow occurred, and when the stream was reactivated, will be completely lost. Use Pause only for very short periods and call Resume immediately once grammars and rules states have changed.

SpeechRecoContext.Pause()

Parameters

None.

Return Value

None.

Remarks

Grammar and rule state changes can be requested while the SR engine is running. However, the changes will not take place until the engine stops and synchronizes. Since a Recognition event is a common synchronization point, in many situations, it may not be necessary to call Pause. However, if the grammar or state change needs to be implemented immediately, call Pause, make the change and then call Resume.

The SAPI 5 SR engine synchronizes close to every 60 seconds, which aids in timely shutdowns and avoids problems with loud and continuous background noises. There is no requirement for other manufacturer's engines to also synchronize like this although it is encouraged.

Example

The following Visual Basic form code demonstrates the Pause and Resume methods. To run this code, paste it into the Declarations section of a form that contains no controls.

Option Explicit

Private Sub Form_Load()

    Dim RecoContext As SpInProcRecoContext
    Dim Recognizer As SpInprocRecognizer

    On Error GoTo EH

    Set Recognizer = New SpInprocRecognizer
    Set RecoContext = Recognizer.CreateRecoContext

    ' Suspend event notifications.
    RecoContext.Pause

    ' Do some grammar or rule state changes here.....

    ' Resume event notifications.
    RecoContext.Resume

    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext Recognizer Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

Recognizer Property

The Recognizer property identifies the recognizer associated with the recognition context.

Syntax

Set: | (This property is read-only)
Get: | ISpeechRecognizer = SpeechRecoContext.Recognizer

Parts

SpeechRecoContext
The owning object.
SpeechRecognizer
Set: (This property is read-only)
Get: A SpeechRecognizer object that gets the value of the property.

Remarks

Though it is usually acceptable to declare an object with the exact class name, ISpeechRecognizer is most often implemented as either SpSharedRecognizer or SpInprocRecognizer. Because it is not always known ahead of time which type of recognizer will be used, it is often safer to declare the object as Object.

Example

The following Visual Basic form code demonstrates retrieving the recognizer associated with recognition context, both for a Shared and an InProc recognizer. To run this code, paste it into the Declarations section of a form that contains no controls.

Option Explicit

Private Sub Form_Load()

    Dim RecoContext1 As SpInProcRecoContext
    Dim RecoContext2 As SpSharedRecoContext
    Dim Recognizer1 As SpInprocRecognizer
    Dim Recognizer2 As SpSharedRecognizer

    On Error GoTo EH

    Set RecoContext1 = New SpSharedRecoContext
    Set Recognizer1 = New SpSharedRecognizer
    Set Recognizer1 = RecoContext1.Recognizer
    MsgBox "Shared: " & Recognizer1.IsShared, vbInformation

    Set RecoContext2 = New SpInProcRecoContext
    Set Recognizer2 = New SpInprocRecognizer
    Set Recognizer2 = RecoContext2.Recognizer
    MsgBox "Shared: " & Recognizer2.IsShared, vbInformation

    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext RequestedUIType Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

RequestedUIType Property

The RequestedUIType property specifies the UIType of the last UI requested from the engine.

After a speech recognition (SR) engine sends a RequestUI event, the UIType persists until the next RequestUI event. This way the application can check for the last requested UI type. If no UI has been requested, the UIType string will be Empty.

Syntax

Set: | (This property is read-only)
Get: | String = SpeechRecoContext.RequestedUIType

Parts

SpeechRecoContext
The owning object.
String
Set: (This property is read-only)
Get: A String variable specifying the UIType. The UIType is a String corresponding to the UI requested.

Remarks

See RequestUI event and ISpeechRecognizer.DisplayUI for more information.

Example

The following Visual Basic form code demonstrates retrieving the UI last requested from the engine. Due to the complexity of replicating a RequestUI, the UI this code retrieves is a zero-length string. To run this code, paste it into the Declarations section of a form that contains no controls.

Option Explicit

Private Sub Form_Load()

    Dim RecoContext As SpInProcRecoContext
    Dim T As String
    Dim UI As String

    On Error GoTo EH

    Set RecoContext = New SpSharedRecoContext
    UI = RecoContext.RequestedUIType

    If Len(UI) = 0 Then
        T = "No user interface type has been requested by the engine."
        MsgBox T, vbInformation
    End If

    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext Resume Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

Resume Method

The Resume method releases the speech recognition (SR) engine from the paused state and restarts the recognition process.

See ISpeechRecoContext.Pause for details.

SpeechRecoContext.Resume()

Parameters

None.

Return Value

None.

Example

See ISpeechRecoContext.Pause for an example.


SpeechRecoContext RetainedAudio Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

RetainedAudio Property

The RetainedAudio property gets and sets the audio retention status of the recognition context.

By default, a recognition context does not retain audio and is initially set to SRAONone. Calls attempting to access non-existent audio result in an SPERR_NO_AUDIO_DATA error. The calls ISpeechRecoResult.Audio and ISpeechRecoResult.SpeakAudio result in this error. The error can also occur when setting an SpAudioFormat instance.

To retain the audio, set this property to SRAORetainAudio.

Syntax

Set: | SpeechRecoContext.RetainedAudio = SpeechRetainedAudioOptions
Get: | SpeechRetainedAudioOptions = SpeechRecoContext.RetainedAudio

Parts

SpeechRecoContext
The owning object.
SpeechRetainedAudioOptions
Set: A SpeechRetainedAudioOptions constant that sets the property.
Get: A SpeechRetainedAudioOptions constant that gets the property.

Example

See ISpeechRecoContext.CreateResultFromMemory for an example.


SpeechRecoContext RetainedAudioFormat Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

RetainedAudioFormat Property

The RetainedAudioFormat property gets and sets the format of audio retained by the recognition context.

By default, the retained audio format will be the same as the input audio format. The input audio format is retrieved by calling Recognizer.GetFormat with SFTInput as the parameter. The audio format may be set, or reset if the format has previously changed, to the same format as the engine uses by passing Nothing in as the parameter.

Syntax

Set: | SpeechRecoContext.RetainedAudioFormat = SpAudioFormat
Get: | SpAudioFormat = SpeechRecoContext.RetainedAudioFormat

Parts

SpeechRecoContext
The owning object.
SpAudioFormat
Set: An SpAudioFormat object that sets the audio format.
Get: An SpAudioFormat object that returns the audio format.

Remarks

The recognition context's RetainedAudio need not be set to SRAORetainAudio for RetainedAudioFormat to be called successfully. RetainedAudioFormat indicates the format in which the audio would be retained, regardless of whether it is currently retained.

Example

The following Visual Basic form code demonstrates retrieving the audio format of the audio input stream, through the RetainedAudioFormat reference. To run this code, paste it into the Declarations section of a form that contains no controls.

Option Explicit

Private Sub Form_Load()

    Dim AudioFormat As SpAudioFormat
    Dim Recognizer As SpSharedRecognizer
    Dim RecoContext As SpSharedRecoContext

    On Error GoTo EH

    Set Recognizer = New SpSharedRecognizer
    Set RecoContext = Recognizer.CreateRecoContext
    Set AudioFormat = RecoContext.RetainedAudioFormat
    MsgBox AudioFormat.Type, vbInformation
    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext SetAdaptationData Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

SetAdaptationData Method

The SetAdaptationData method passes the speech recognition (SR) engine a string of adaptation data.

An application can improve recognition accuracy for dictating uncommon words, or uncommon word groupings by training the SR engine for the new words or word groupings. An application creates or obtains typical text and sends the results to the engine using the SetAdaptationData method.

SpeechRecoContext.SetAdaptationData(
     AdaptationString As String
)

Parameters

AdaptationString
Specifies the AdaptationString.

Return Value

None.

Remarks

Applications using adaptation data should break the data into small sections (1KB or less) and submit the sections individually. First, specify interest in adaptation events using the ISpeechRecoContext.EventInterests method. The Adaptation event interest is on by default. Then, send a small data section to the SR engine using the SetAdaptationData method, and wait for an ISpeechRecoContext.Adaptation event, which indicates that the adaptation data has been processed. Send all successive data sections in this way. Finally, use the EventInterests method to turn off Adaptation events. Since this event is returned only after an explicit SetAdaptationData call, the event interest does not need to be removed unless an excessive number of words is added and the processing time becomes unacceptable. The Adaptation event indicates that the engine has processed the AdaptationString and that it is ready to accept another SetAdaptationData call.

Example

The following Visual Basic form code demonstrates adding an uncommon word, which raises the recognition context's Adaptation event. To run this code, paste it into the Declarations section of a form that contains no controls.

Option Explicit

Public WithEvents RecoContext As SpSharedRecoContext

Private Sub Form_Load()

    Dim Grammar As ISpeechRecoGrammar
    Dim Recognizer As SpSharedRecognizer

    On Error GoTo EH

    ' Set up speech recognition and grammar:
    Set Recognizer = New SpSharedRecognizer
    Set RecoContext = Recognizer.CreateRecoContext
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Raise Adaptation event.
    RecoContext.SetAdaptationData "Simmiting"

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Adaptation _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    MsgBox "Adaptation data/word(s) just added.", vbInformation
    End

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext State Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

State Property

The State property gets or sets the active state of the recognition context.

The entire grammar associated with the recognition context can be disabled or enabled. The individual rule states of the grammar are unaffected otherwise. These conditions allow the application to control the state of the grammars at a high level. For example, if the window loses the current focus, the recognition context (s) associated with that window may be disabled if recognitions are not needed. Likewise, when the window regains the focus, all the recognition contexts may be enabled.

Syntax

Set: | SpeechRecoContext.State = SpeechRecoContextState
Get: | SpeechRecoContextState = SpeechRecoContext.State

Parts

SpeechRecoContext
The owning object.
SpeechRecoContextState
Set: A SpeechRecoContextState variable that sets the property.
Get: A SpeechRecoContextState variable that gets the property.

Example

The following Visual Basic form code demonstrates how disabling and enabling the state of a recognition context does not affect the state of the context's command and control grammar. To run this code, paste it into the Declarations section of a form that contains no controls. Note that the code requires the grammar file C:\sol.xml to run correctly.

Option Explicit

Private Sub Form_Load()

    Dim Grammar As ISpeechRecoGrammar
    Dim RecoContext As SpSharedRecoContext
    Dim Recognizer As SpSharedRecognizer
    Dim T As String

    On Error GoTo EH

    ' Set up speech recognition and grammar:
    Set Recognizer = New SpSharedRecognizer
    Set RecoContext = Recognizer.CreateRecoContext
    Set Grammar = RecoContext.CreateGrammar

    With Grammar

        ' Load command and control grammar
        ' and disable that grammar:
        .CmdLoadFromFile "C:\sol.xml", SLODynamic
        MsgBox "Grammar state before disabling: " & .State
        .State = SGSDisabled
        MsgBox "Grammar state after disabling: " & .State

        ' Disable and then reenable recognition context
        ' and demonstrate that grammar is still disabled:
        RecoContext.State = SRCS_Disabled
        RecoContext.State = SRCS_Enabled
        T = "Grammar state after disabling/reenabling "
        T = T & "the recognition context: " & .State
        MsgBox T, vbInformation

    End With

    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext Voice Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

Voice Property

The Voice property specifies the SpVoice object associated with the recognition context.

Syntax

Set: | SpeechRecoContext.Voice = SpVoice
Get: | SpVoice = SpeechRecoContext.Voice

Parts

SpeechRecoContext
The owning object.
SpVoice
Set: An SpVoice object that sets the Voice property.
Get: An SpVoice object that gets the Voice property.

Remarks

ISpeechRecoContext.Voice allows the voice to be changed temporarily and for limited contexts. Change the voice using Speech properties in Control Panel.

Example

The following Visual Basic form code demonstrates speaking a successful recognition using the Voice property. The first text ("One of the world's seven wonders") is spoken using the default system voice, which is specified using Speech properties in Control Panel. The example code then changes the current voice to "Microsoft Sam" if it is available and speaks the name of the newly specified system voice.

To run this code, paste it into the Declarations section of a form that contains no controls. In addition to the usual reference to the Microsoft Speech Object Library, this code also needs a reference to the simpleaudio 1.0 Type Library.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition:
    Set RecoContext = Recognizer.CreateRecoContext
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Const NewVoiceName = "name=Microsoft Sam"
    Dim RC As SpInProcRecoContext

    On Error GoTo EH
    Set RC = RecoContext

    RC.Voice.Speak Result.PhraseInfo.GetText
    Set RC.Voice.Voice = RC.Voice.GetVoices(NewVoiceName).Item(0)
    RC.Voice.Speak "I have changed to " & RC.Voice.Voice.GetDescription
    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecoContext VoicePurgeEvent Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext

VoicePurgeEvent Property

The VoicePurgeEvent property gets and sets the RecoContext event which will stop the RecoContext's voice and purge the voice queue.

Applications can use the Voice property of a RecoContext object to prompt a user for spoken input. Setting the VoicePurgeEvent to the SRESoundStart event will cause the RecoContext's voice to stop speaking when the user begins speaking.

Syntax

Set: | SpeechRecoContext.VoicePurgeEvent = SpeechRecoEvents
Get: | SpeechRecoEvents = SpeechRecoContext.VoicePurgeEvent

Parts

SpeechRecoContext
The owning object.
SpeechRecoEvents
Set: A SpeechRecoEvents constant that sets the VoicePurgeEvent.
Get: A SpeechRecoEvents constant that gets the VoicePurgeEvent

Example

The following Visual Basic form code demonstrates the use of the VoicePurgeEvent property. To run this code, create a form with the following controls:

  • Two command buttons, called Command1 and Command2

Paste this code into the Declarations section of the form.

The code creates a RecoContext with a grammar and a voice. The grammar is loaded with a set of rules (located in the file C:\sol.xml) so that the RecoContext can begin recognition as soon as the grammar is activated. Both command button Click event procedures speak text that contains a bookmark. The RecoContext's bookmark event activates the grammar, which initiates recognition, and the activated RecoContext receives an SRESoundStart event.

In the Command1_Click procedure, the voice continues speaking after recognition has begun, because the VoicePurgeProperty has been set to zero, and the SRESoundStart event does not effect either the RecoContext or its Voice. In the Command2_Click procedure, the VoicePurgeProperty causes the SRESoundStart event to stop the voice.

Option Explicit

Dim WithEvents Voice As SpVoice
Dim Context As SpSharedRecoContext
Dim RecoGrammar As ISpeechRecoGrammar

Const SpeakStr1 = "Recognition is started by the next bookmark."
Const SpeakStr2 = " but the voice keeps speaking."

Private Sub Form_Load()
    On Error GoTo EH

    Set Context = New SpSharedRecoContext
    Set RecoGrammar = Context.CreateGrammar(123)
    RecoGrammar.CmdLoadFromFile "c:\sol.xml"

    'The voice must be
    Set Voice = Context.Voice
    Voice.EventInterests = SVEBookmark + SVEEndInputStream + SVEStartInputStream

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()
    On Error GoTo EH

    ' Speak with no VoicePurgeEvent:
    Context.VoicePurgeEvent = 0
    Voice.Speak SpeakStr1, SVSFIsXML + SVSFlagsAsync
    Voice.Speak SpeakStr2, SVSFIsXML + SVSFlagsAsync
    Voice.WaitUntilDone (999)
    RecoGrammar.CmdSetRuleState "", SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH

    ' Speak with VoicePurgeEvent on SRESoundStart:
    Context.VoicePurgeEvent = SRESoundStart
    Voice.Speak SpeakStr1, SVSFIsXML + SVSFlagsAsync
    Voice.Speak SpeakStr2, SVSFIsXML + SVSFlagsAsync
    Voice.WaitUntilDone (999)
    RecoGrammar.CmdSetRuleState "", SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_Bookmark _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal Bookmark As String, _
    ByVal BookmarkId As Long)

    On Error GoTo EH

    ' After the first bookmark, we activate the grammar,
    ' and the SR sound start event should pause TTS voice.
    RecoGrammar.CmdSetRuleState "", SGDSActive  'active the rule

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechRecoContext (Events) Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechRecoContext (Events)

The ISpeechRecoContext (Events) automation interface defines the types of events that a recognition context can receive.

Automation Interfaces

The ISpeechRecoContext (Events) automation interface contains the following elements:

Events | Description
Adaptation Event | Occurs when the SR engine has finished processing a block of adaptation data.
AudioLevel Event | Occurs when the SAPI audio object detects a change in audio level.
Bookmark Event | Occurs when the SR engine encounters a bookmark within the current recognition stream.
EndStream Event | Occurs when the SR engine encounters the end of an input audio stream.
EnginePrivate Event | Occurs when a private SR engine raises a private event.
FalseRecognition Event | Occurs when the SR engine produces a false recognition.
Hypothesis Event | Occurs when the SR engine produces a hypothesis.
Interference Event | Occurs when the SR engine encounters interference in the input audio stream.
PhraseStart Event | Occurs when the SR engine identifies the start of a phrase.
PropertyNumberChange Event | Occurs when the speech recognition engine detects a change in a property number value.
PropertyStringChange Event | Occurs when the speech recognition engine detects a change in a property String value.
Recognition Event | Occurs when the SR engine produces a recognition.
RecognitionForOtherContext Event | Occurs when the recognition context encounters a recognition result that belongs to another recognition context.
RecognizerStateChange Event | Occurs when the SR engine changes state.
RequestUI Event | Occurs when the SR engine requests additional information from the user.
SoundEnd Event | Occurs when the SR engine encounters an end of sound in the audio input stream.
SoundStart Event | Occurs when the SR engine encounters the start of sound in the audio input stream.
StartStream Event | Occurs when the SR engine encounters the start of an audio input stream.


SpeechRecoContext Adaptation Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

Adaptation Event

The Adaptation event occurs when the SR engine has finished processing a block of adaptation data.

The Adaptation event not only indicates the engine has processed the word but also that the engine is ready to accept another SetAdaptationData call.

See ISpeechRecoContext.SetAdaptationData for additional details.

SpeechRecoContext.Adaptation(
     StreamNumber As Long,
     StreamPosition As Variant
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the position within the stream.

Example

See ISpeechRecoContext.SetAdaptationData for a code example.


SpeechRecoContext AudioLevel Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

AudioLevel Event

The AudioLevel event occurs when the SAPI audio object detects a change in audio level.

The AudioLevel event is the only speech recognition event in SAPI automation that is not set by default. If this event is needed, it must be explicitly set with EventInterests.

SpeechRecoContext.AudioLevel(
     StreamNumber As Long,
     StreamPosition As Variant,
     AudioLevel As Long
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the position within the stream.
AudioLevel
Specifies the AudioLevel.

Example

The following Visual Basic form code demonstrates the use of the AudioLevel event. The application displays the audio level of the speaker's voice as well as the text of a successful recognition. The value of the speaker's voice is shown as both a numeric value as well as a histogram.

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar. Because the AudioLevel event is not set by default, it must be explicitly set with EventInterests. In this case, EventInterests is reset for only two events, with a Recognition as the second one.

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive

    RC.EventInterests = SRERecognition + SREAudioLevel
End Sub

Private Sub RC_AudioLevel(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal AudioLevel As Long)
    Label2.Caption = Val(AudioLevel)

    Label2.Caption = Label2.Caption & vbCrLf

    For i = 1 To AudioLevel
        Label2.Caption = Label2.Caption & "*"
    Next
End Sub

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label1.Caption = Result.PhraseInfo.GetText
End Sub


SpeechRecoContext Bookmark Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

Bookmark Event

The Bookmark event occurs when the speech recognition (SR) engine encounters a bookmark within the current recognition stream.

See ISpeechRecoContext.Bookmark for further information.

SpeechRecoContext.Bookmark(
     StreamNumber As Long,
     StreamPosition As Variant,
     BookmarkId As Variant,
     Options As SpeechBookmarkOptions
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the stream position to initiate the Bookmark event. Due to the latency period of the engines, there may be a delay between the cause of the event and the initiation of the event.
BookmarkId
Specifies the BookmarkId. BookmarkId is additional information provided by the application and is unique to the application. As a Variant data type, it may be numeric, String, or any other format and is used to pass information within the method or event. If BookmarkId is a String, the value must be able to convert to a numeric value. This information is returned back using the Bookmark event.
Options
Specifies the options, specifically whether the recognition pauses during the bookmark processing.

Example

See ISpeechRecoContext.Bookmark for further information.


SpeechRecoContext EndStream Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

EndStream Event

The EndStream event occurs when the speech recognition engine encounters the end of an input audio stream.

SpeechRecoContext.EndStream(
     StreamNumber As Long,
     StreamPosition As Variant,
     StreamReleased As Boolean
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the position within the stream.
StreamReleased
Indicates that the stream was released. Usually, stopping a stream does not release it and StreamReleased should be False. However, if the stream is not associated with an audio device or if the stream ran out of data while in the run state, the stream will be both stopped and released; in this case, StreamReleased will be True.

Example

The following Visual Basic form code demonstrates the use of the StartStream and EndStream events. The application displays the status of the stream and a stream number. It also displays a successful recognition if a stream is active.

To run this code, create a form with the following controls:

  • A command button called Command1
  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form. The Form_Load procedure creates and activates a dictation grammar.

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar
Public fRecoEnabled As Boolean

Private Sub Command1_Click()
    If fRecoEnabled = True Then
        myGrammar.DictationSetState SGDSInactive
        fRecoEnabled = False
    Else
        myGrammar.DictationSetState SGDSActive
        fRecoEnabled = True
    End If
End Sub

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext
    Set myGrammar = RC.CreateGrammar

    myGrammar.DictationSetState SGDSActive
    fRecoEnabled = True

    Command1.Caption = "Start Recognition"
End Sub

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label1.Caption = Result.PhraseInfo.GetText
End Sub

Private Sub RC_EndStream(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal StreamReleased As Boolean)
    Label2.Caption = "Stream stopped at position: " & StreamPosition
End Sub

Private Sub RC_StartStream(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Label2.Caption = "Stream number = " & Val(StreamNumber)
End Sub


SpeechRecoContext EnginePrivate Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

EnginePrivate Event

The EnginePrivate event occurs when a speech recognition engine (SR) raises a private event.

A private event is a custom event defined by the SR engine. This event allows engines to define a specialized event beyond the standard suite of events. Engines are not required support this event. The SAPI 5 Microsoft engines do not use the EnginePrivate event. If using another manufacturer's engine, check their documentation for possible implementation of this event.

SpeechRecoContext.EnginePrivate(
     StreamNumber As Long,
     StreamPosition As Variant,
     EngineData As Variant
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the position within the stream.
EngineData
Specifies the private EngineData. This is a Variant data type and is specific to the manufacturer's design. Check the manufacturer's documentation for complete details.

Example

No sample code is available. The event is unique to manufacturer's engines and will vary among engines. The SAPI 5 Microsoft engines do not use the EnginePrivate event.


SpeechRecoContext FalseRecognition Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

FalseRecognition Event

The FalseRecognition event occurs when the speech recognition (SR) engine produces a false recognition.

A false recognition is the result of a recognition attempt in which either the word or phrase does not exist in the grammar, or that the speech does not adequately meet the confidence score for the application. Although applicable to dictation grammars, it is more common with command and control instances, because the available words are significantly restricted.

The recognition result returned with a FalseRecognition is still valid and contains all the information a Recognition event does, including the text. Although the text is not necessarily representative of the intended speech, it represents the best estimate of that speech. If using alternates (automatically chosen alternate phrase selections for a recognition), the first alternate returned will likely be the same as the FalseRecognition result.

SpeechRecoContext.FalseRecognition(
     StreamNumber As Long,
     StreamPosition As Variant,
     Result As ISpeechRecoResult
)

Parameters

StreamNumber
Specifies the StreamNumber.
StreamPosition
Specifies the StreamPosition.
Result
An ISpeechRecoResult object containing the recognition results.

Remarks

There are three possible results from a recognition attempt:

  1. The first, a Recognition event is the result of a successful recognition. This event indicates that the word or phrase was matched to elements in an open grammar, and that the match had a sufficiently high confidence rating.
  2. The second possible result is a FalseRecognition event. This event indicates that speech was detected but it either did not match words in an open grammar, or the match did not merit a high enough confidence rating. The recognition result returned with a FalseRecognition is still valid and contains all the information of a Recognition event, including the text.
  3. The third possible result is RecognitionForOtherContext event. This event indicates a successful recognition result, but a different recognition context was used to match words. SAPI attempts to match the word or phrase in the current recognition context. However, if no match is possible (perhaps the recognition context is currently inactive, the rule is inactive, or the word or phrase is simply not included in the grammar), SAPI then attempts to find a match in other recognition contexts. If a match is found in another application whose grammar is available, the Recognition event is sent to that application instead and the current application receives a RecognitionForOtherContext event.

Example

The following Visual Basic form code demonstrates the use of the FalseRecognition event. The application displays the text of a successful recognition.

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar. The grammar file sol.xml also needs to be created.

The sol.xml file has only one phrase that can be recognized. To use this application speak the phrase "new game" and it should be successfully recognized and displayed in Labell. Any other word or phrase should not be recognized and will display in Label2.

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.CmdLoadFromFile "sol.xml", SLODynamic
    myGrammar.CmdSetRuleIdState 0, SGDSActive
End Sub

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label1.Caption = Result.PhraseInfo.GetText
    Label2.Caption = ""
End Sub

Private Sub RC_FalseRecognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label2.Caption = Result.PhraseInfo.GetText
    Label1.Caption = ""
End Sub


SpeechRecoContext Hypothesis Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

Hypothesis Event

The Hypothesis event occurs when the SR engine produces a hypothesis.

A hypothesis is an interim recognition result. Each time the engine attempts a recognition it generates an interim results and Hypothesis events are sent out. A hypothesis may or may not be close to the final version of the recognition. In fact, a hypothesis may not bear any likeness to the final result due to the sound quality, idiomatic phrasing, or uncommon word or phrase usage.

The member Result is a valid recognition result and may be used in the same way as a Recognition event. However, the values are interim and could change for the next Hypothesis event.

SpeechRecoContext.Hypothesis(
     StreamNumber As Long,
     StreamPosition As Variant,
     Result As ISpeechRecoResult
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the position within the stream.
Result
An ISpeechRecoResult object containing the recognition results.

Example

The following Visual Basic form code demonstrates the use of the Hypothesis event. The application displays all the hypotheses for the current recognition attempt and then displays the final recognition.

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar. The PhraseStart event clears the display each time so the current hypothesis is displayed. For longer recognitions, a larger Label1 may be used or changed to a scrolling text box.

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive
End Sub

Private Sub RC_Hypothesis(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label1.Caption = Label1.Caption & Result.PhraseInfo.GetText & vbCrLf
End Sub

Private Sub RC_PhraseStart(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Label1.Caption = ""
End Sub

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label2.Caption = Result.PhraseInfo.GetText
End Sub


SpeechRecoContext Interference Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

Interference Event

The Interference event occurs when the speech recognition (SR) engine encounters interference in the input audio stream.

Interference may be caused by several factors of which six common ones are listed in the enumeration SpeechInterference. The Interference event indicates that the engine detected a condition which could prevent the optimal recognition process. Interference does not prevent the completion of the recognition. However, applications receiving this event may experience a lower quality recognition (the final text does not accurately reflect the spoken text) as the sound quality prevented a successful recognition.

SpeechRecoContext.Interference(
     StreamNumber As Long,
     StreamPosition As Variant,
     Interference As SpeechInterference
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the position within the stream.
Interference
A SpeechInterference constant that specifies the type of interference.

Example

The following Visual Basic form code demonstrates the use of the Interference event. The application displays the text of a successful recognition and also one of two common interferences results.

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar. The interference may be intentional caused by either making a sudden loud noise (such as a sharp increase of your voice or by clapping your hands near the microphone) or talking very quickly.

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive
End Sub

Private Sub RC_Interference(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal Interference As SpeechLib.SpeechInterference)
    Select Case Interference
        Case SITooFast
            RC.Voice.Speak "Too fast. Speak more slowly."
        Case SITooLoud
            RC.Voice.Speak "Too loud. Speak softly."
            Label2.Caption = "SITooLoud detected at stream position: " & StreamPosition
    End Select
End Sub

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label1.Caption = Result.PhraseInfo.GetText
End Sub


SpeechRecoContext PhraseStart Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

PhraseStart Event

The PhraseStart event occurs when the speech recognition (SR) engine identifies the start of a phrase.

SpeechRecoContext.PhraseStart(
     StreamNumber As Long,
     StreamPosition As Variant
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the position within the stream.

Remarks

For speech processing, the SR engine must perform the following sequence: Stream start, sound start and phrase start. A stream start indicates a valid stream is ready for audio input. The stream persists unless the recognition context is disabled or the associated grammar is deactivated. The sound start indicates a sound level has been detected. However, it is possible the SR engine could stop that recognition attempt if the input sound were questionable. For example, if the sound were a constant level or if above or below pre-determined sound levels. If the sound level is acceptable and variable, a phrase start is initiated and it is assumed to be the beginning of a recognition attempt.

Example

The following Visual Basic form code demonstrates the use of the PhraseStart event but also StartStream, SoundStart, SoundEnd, Hypothesis, and Recognition since they can be related. The application displays all the hypotheses for the current recognition attempt in one window and the other events in a second window.

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar. The SoundStart event clears the displays each time. For longer recognitions, a larger Label2 may be used or change it to a scrolling text box.

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive
End Sub

Private Sub RC_Hypothesis(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label2.Caption = Label2.Caption & Result.PhraseInfo.GetText & vbCrLf
End Sub

Private Sub RC_PhraseStart(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Label1.Caption = Label1.Caption & "      Phrase start detected at position : " & StreamPosition & vbCrLf
    Label2.Caption = ""
End Sub

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label1.Caption = Label1.Caption & Result.PhraseInfo.GetText
End Sub

Private Sub RC_SoundEnd(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
Label1.Caption = Label1.Caption & "   Sound end" & vbCrLf
End Sub

Private Sub RC_SoundStart(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Label1.Caption = "   Sound begin" & vbCrLf
End Sub

Private Sub RC_StartStream(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Label1.Caption = "Stream Number: " & StreamNumber & vbCrLf
    Label2.Caption = ""
End Sub


SpeechRecoContext PropertyNumberChange Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

PropertyNumberChange Event

The PropertyNumberChange event occurs when the speech recognition engine detects a change in a property number value.

See ISpeechRecognizer.GetPropertyNumber for complete details and code sample.

SpeechRecoContext.PropertyNumberChange(
     StreamNumber As Long,
     StreamPosition As Variant,
     PropertyName As String,
     NewNumberValue As Long
)

Parameters

StreamNumber
The stream number.
StreamPosition
The stream position.
PropertyName
Specifies the value of property Name.
NewNumberValue
The new numeric value of the property.

Remarks

For a complete list of SAPI 5 supported properties see the SAPI 5 SR Properties White Paper.

Example

See ISpeechRecognizer.GetPropertyNumber for a complete code sample.


SpeechRecoContext PropertyStringChange Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

PropertyStringChange Event

The PropertyStringChange event occurs when the speech recognition (SR) engine detects a change in a property String value.

The SAPI 5 SR engine does not support any properties with associated string values. However, other manufacturer's engines could. See ISpeechRecognizer.GetPropertyNumber for a related and similar feature.

SpeechRecoContext.PropertyStringChange(
     StreamNumber As Long,
     StreamPosition As Variant,
     PropertyName As String,
     NewStringValue As String
)

Parameters

StreamNumber
The stream number.
StreamPosition
The stream position.
PropertyName
Specifies the value of property Name.
NewNumberValue
The new String value of the property.

Example

See ISpeechRecognizer.GetPropertyNumber for a related code sample.


SpeechRecoContext Recognition Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

Recognition Event

The Recognition event occurs when the speech recognition (SR) engine produces a recognition.

This could be considered the most important event for speech recognition because it returns the result of a successful recognition. A successful recognition is recognized a word or phrase that is matched in an open grammar for that recognition context and whose quality of speech meets a minimum confidence score. If neither criteria is met, the engine returns a FalseRecognition event. Spoken content may not meet the confidence score for several reasons including background interference, inarticulate speech or an uncommon word or phrase.

The member Result contains the recognition result object and from that may derive much of the information about the speech.

SpeechRecoContext.Recognition(
     StreamNumber As Long,
     StreamPosition As Variant,
     RecognitionType As SpeechRecognitionType,
     Result As ISpeechRecoResult
)

Parameters

StreamNumber
Specifies the stream number owning the recognition.
StreamPosition
Specifies the position within the stream.
RecognitionType
A SpeechRecognitionType constant that specifies the RecognitionType or the recognition state of the engine.
Result
An ISpeechRecoResult object containing the recognition results.

Remarks

There are three possible results from a recognition attempt:

  1. The first, a Recognition event is the result of a successful recognition. This event indicates that the word or phrase was matched to elements in an open grammar, and that the match had a sufficiently high confidence rating.
  2. The second possible result is a FalseRecognition event. This event indicates that speech was detected but it either did not match words in an open grammar, or the match did not merit a high enough confidence rating. The recognition result returned with a FalseRecognition is still valid and contains all the information of a Recognition event, including the text.
  3. The third possible result is RecognitionForOtherContext event. This event indicates a successful recognition result, but a different recognition context was used to match words. SAPI attempts to match the word or phrase in the current recognition context. However, if no match is possible (perhaps the recognition context is currently inactive, the rule is inactive, or the word or phrase is simply not included in the grammar), SAPI then attempts to find a match in other recognition contexts. If a match is found in another application whose grammar is available, the Recognition event is sent to that application instead and the current application receives a RecognitionForOtherContext event.

Example

The following Visual Basic form code demonstrates the use of the Recognition event. The application displays the text of a successful recognition.

To run this code, create a form with the following control:

  • A label called Label1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar.

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext
    Set myGrammar = RC.CreateGrammar

    myGrammar.DictationSetState SGDSActive
End Sub

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label1.Caption = Result.PhraseInfo.GetText
End Sub


SpeechRecoContext RecognitionForOtherContext Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

RecognitionForOtherContext Event

The RecognitionForOtherContext event occurs when the recognition context encounters a recognition result that belongs to another recognition context.

A RecognitionForOtherContext event indicates a successful recognition but that another application currently running claims it. This is a useful event if multiple shared instances are running at the same time. If the owning application cannot use or claim the recognition, the recognition event is sent to another context that can claim it. In that case, the recognition context claiming it receives the Recognition event and all other contexts receive a RecognitionForOtherContext event.

This event is more applicable to command and control grammars than to dictation. For example, the current recognition context returns a recognition result such as "file." If that recognition context does not have the word "file" in its active grammar, the speech recognition engine searches all the other open and active grammars, even if they belong to other applications. If another context has the word "file" available, the recognition event is sent there instead.

If other recognition contexts should not receive recognition events, because the window or application is not the current one for example, change state of those contexts using ISpeechRecoContext.State.

SpeechRecoContext.RecognitionForOtherContext(
     StreamNumber As Long,
     StreamPosition As Variant
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the position within the stream.

Remarks

There are three possible results from a recognition attempt:

  1. The first, a Recognition event is the result of a successful recognition. This event indicates that the word or phrase was matched to elements in an open grammar, and that the match had a sufficiently high confidence rating.
  2. The second possible result is a FalseRecognition event. This event indicates that speech was detected but it either did not match words in an open grammar, or the match did not merit a high enough confidence rating. The recognition result returned with a FalseRecognition is still valid and contains all the information of a Recognition event, including the text.
  3. The third possible result is RecognitionForOtherContext event. This event indicates a successful recognition result, but a different recognition context was used to match words. SAPI attempts to match the word or phrase in the current recognition context. However, if no match is possible (perhaps the recognition context is currently inactive, the rule is inactive, or the word or phrase is simply not included in the grammar), SAPI then attempts to find a match in other recognition contexts. If a match is found in another application whose grammar is available, the Recognition event is sent to that application instead and the current application receives a RecognitionForOtherContext event.

Example

The following Visual Basic form code demonstrates the use of the RecognitionForOtherContext event. The application displays the text of a successful recognition or indicates that the recognition belongs to another application.

The setup for this scenario is somewhat complex. To duplicate two applications running command and control instances, the following code must be compiled into two different applications. Create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar. Create the grammar file sol.xml. The second application should open sol2.xml. This will be the only modification.

The xml files have only one phrase each that can be recognized. Run both applications. Now speak, "new game." The first application gets the recognition while the second application displays "For another context." Now speak "file game" and the situation reverses. These applications will assign and display commands properly regardless of the front-most application.

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.CmdLoadFromFile "sol.xml", SLODynamic
    myGrammar.CmdSetRuleIdState 0, SGDSActive
End Sub

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label1.Caption = Result.PhraseInfo.GetText
    Label4.Caption = ""
End Sub

Private Sub RC_RecognitionForOtherContext(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Label4.Caption = "For another context"
    Label1.Caption = ""
End Sub


SpeechRecoContext RecognizerStateChange Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

RecognizerStateChange Event

The RecognizerStateChange event occurs when the SR engine changes state.

SpeechRecoContext.RecognizerStateChange(
     StreamNumber As Long,
     StreamPosition As Variant,
     NewState As SpeechRecognizerState
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the position within the stream.
NewState
A SpeechRecognizerState constant specifying the new state of the speech recognition (SR) engine.

Example

The following Visual Basic form code demonstrates the use of the RecognizerStateChange event. The application displays the recognition text but also has a button to control the SR engine's state (also called the recognizer). Click this button to toggle the recognizer state between Active and Inactive. The application also beeps after a state change.

To run this code, create a form with the following controls:

  • A command button called Command1
  • A label called Label1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar.

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Command1_Click()
    If RC.Recognizer.State = SRSActive Then
        RC.Recognizer.State = SRSInactive
        Command1.Caption = "SRSInactive"
    Else
        RC.Recognizer.State = SRSActive
        Command1.Caption = "SRSActive"
    End If
End Sub

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive

    Command1.Caption = "SRSActive"
End Sub

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label1.Caption = Result.PhraseInfo.GetText
End Sub

Private Sub RC_RecognizerStateChange(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal NewState As SpeechLib.SpeechRecognizerState)
    Beep
End Sub


SpeechRecoContext RequestUI Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

RequestUI Event

The RequestUI event occurs when the speech recognition (SR) engine requests additional information from the user.

Though not required, SR engines may employ a process improvement procedure and request additional information from the user. For example, if the recognition attempts are consistently poor or if the engine detects consistent background interference, the SR engine could request that the application use the training or microphone wizard. This event is a suggestion by the SR engine to run the particular UI. The application may choose to initiate the UI or may ignore the request.

SpeechRecoContext.RequestUI(
     StreamNumber As Long,
     StreamPosition As Variant,
     UIType As String
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the position within the stream.
UIType
Specifies the UIType. The UIType is a String corresponding to the UI requested.

Remarks

See ISpeechRecognizer.DisplayUI and ISpeechRecognizer.IsUISupported for additional information.

Example

The following Visual Basic code shows a typical RequestUI event. Since the SR engine initiates the call, reproducing the event is difficult. However, if the application receives this event, the code displays the user training wizard. It is the same training wizard that is available through the Speech properties in Control Panel.

Private Sub RC_RequestUI(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal UIType As String)
    If UIType = SpeechUserTraining Then
        RC.Recognizer.DisplayUI Form1.hWnd, "My User Training", SpeechUserTraining, vbNullString
    End If
End Sub


SpeechRecoContext SoundEnd Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

SoundEnd Event

The SoundEnd event occurs when the speech recognition (SR) engine encounters an end of sound in the audio input stream.

SoundStart indicates a sound level significant enough to be a voice. When that sound stops, a SoundEnd event is generated. A recognition attempt occurs only after a SoundEnd event; hence, long continuous speaking periods may take an equally long time to process.

Light background noise will not register as an input sound. Likewise a loud noise will be considered the start of an input sound. If the sound is constant, a time-out occurs sending a SoundEnd event.

SpeechRecoContext.SoundEnd(
     StreamNumber As Long,
     StreamPosition As Variant
)

Parameters

StreamNumber
Specifies the StreamNumber.
StreamPosition
Specifies the StreamPosition.

Example

The following Visual Basic form code demonstrates the use of the SoundStart and SoundEnd events. The application displays a stream number and notifications that a sound has begun or ended. It also displays a successful recognition result.

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar.

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive
End Sub

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label1.Caption = Result.PhraseInfo.GetText
End Sub

Private Sub RC_SoundEnd(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Label2.Caption = "Sound end at position: " & StreamPosition
End Sub

Private Sub RC_SoundStart(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Label2.Caption = "Sound start"
End Sub


SpeechRecoContext SoundStart Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

SoundStart Event

The SoundStart event occurs when the SR engine encounters the start of sound in the audio input stream.

SoundStart indicates a sound level significant enough to be a voice. When that sound stops, a SoundEnd event is generated. A recognition attempt occurs only after a SoundEnd event; hence, long continuous speaking periods may take an equally long time to process.

Light background noise will not register as an input sound. Likewise a loud noise will be considered the start of an input sound. If the sound is constant, a time-out occurs sending a SoundEnd event.

SpeechRecoContext.SoundStart(
     StreamNumber As Long,
     StreamPosition As Variant
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the position within the stream. If downsampling an audio stream, StreamPosition will be the byte position within the converted stream.

Remarks

For speech processing, the SR engine must perform the following sequence: Stream start, sound start and phrase start. A stream start indicates a valid stream is ready for audio input. The stream persists unless the recognition context is disabled or the associated grammar is deactivated. The sound start indicates a sound level has been detected. However, it is possible the SR engine could stop that recognition attempt if the input sound were questionable. For example, if the sound were a constant level or if above or below pre-determined sound levels. If the sound level is acceptable and variable, a phrase start is initiated and it is assumed to be the beginning of a recognition attempt.

Example

The following Visual Basic form code demonstrates the use of the SoundStart and SoundEnd events. The application displays a stream number and notifications that a sound has begun or ended. It also displays a successful recognition

To run this code, create a form with the following controls:

  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar.

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive
End Sub

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label1.Caption = Result.PhraseInfo.GetText
End Sub

Private Sub RC_SoundEnd(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Label2.Caption = "Sound end at position: " & StreamPosition
End Sub

Private Sub RC_SoundStart(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Label2.Caption = "Sound start"
End Sub


SpeechRecoContext StartStream Event (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoContext Events

StartStream Event

The StartStream event occurs when the speech recognition (SR) engine encounters the start of an audio input stream.

The stream number of each new stream will be incremented from the last stream number, so that each value is unique to the application's lifespan. Stream numbers may be used to track input sources. In the case of recognizing wav files in a batch environment, for instance, stream numbers may be used to uniquely identify the source. In other cases, a StreamStart event can indicate the beginning of a new recognition attempt.

SpeechRecoContext.StartStream(
     StreamNumber As Long,
     StreamPosition As Variant
)

Parameters

StreamNumber
Specifies the stream number.
StreamPosition
Specifies the position within the stream.

Remarks

For speech processing, the SR engine must perform the following sequence: Stream start, sound start and phrase start. A stream start indicates a valid stream is ready for audio input. The stream persists unless the recognition context is disabled or the associated grammar is deactivated. The sound start indicates a sound level has been detected. However, it is possible the SR engine could stop that recognition attempt if the input sound were questionable. For example, if the sound were a constant level or if above or below pre-determined sound levels. If the sound level is acceptable and variable, a phrase start is initiated and it is assumed to be the beginning of a recognition attempt.

Example

The following Visual Basic form code demonstrates the use of the StartStream and EndStream events. The application displays the status of the stream and a stream number. It also displays a successful recognition if a stream is active.

To run this code, create a form with the following controls:

  • A command button called Command1
  • Two labels called Label1 and Label2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar.

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar
Public fRecoEnabled As Boolean

Private Sub Command1_Click()
    If fRecoEnabled = True Then
        myGrammar.DictationSetState SGDSInactive
        fRecoEnabled = False
    Else
        myGrammar.DictationSetState SGDSActive
        fRecoEnabled = True
    End If
End Sub

Private Sub Form_Load()
    Set RC = New SpSharedRecoContext
    Set myGrammar = RC.CreateGrammar

    myGrammar.DictationSetState SGDSActive
    fRecoEnabled = True

    Command1.Caption = "Start Recognition"
End Sub

Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult)
    Label1.Caption = Result.PhraseInfo.GetText
End Sub

Private Sub RC_EndStream(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal StreamReleased As Boolean)
    Label2.Caption = "Stream stopped at position: " & StreamPosition
End Sub

Private Sub RC_StartStream(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Label2.Caption = "Stream number = " & Val(StreamNumber)
End Sub


ISpeechRecognizer Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpeechRecognizer

The ISpeechRecognizer automation interface represents a speech recognition engine.

A recognizer is a speech recognition (SR) engine. Engines are generally categorized by two major characteristics. The first is the language of the engine. The language is provided by the manufacturer and may not be changed. A computer may have several types of engines installed at the same time. However, the use of the engine is limited and is dependent of the recognition type. The second major characteristic is the recognition type, that is, whether the instance of the engine is created as in-process (also known as InProc) or shared. See Recognition Types for more information.

A default SR engine is selected using Speech properties in Control Panel. This is provided as a convenience to users and the default engine will be used if no other type is explicitly specific. In many cases, users requirements can be met by a single engine. However, applications are not restricted to the default engine and may use other engines as needed. In contrast, an active engine is one that is instantiated and being used by at least one recognition context.

More than one instance of an engine may used. Each application may have its own instance of a recognizer and in some situations, each recognition context may have its won engine instance. Application using InProc recognizers must have their own instance. If greater granularity is needed for recognition, it is recommended to use different recognition contexts rather than using multiple recognizers.

The following code snippet declares a shared recognition context and an implicit shared recognizer.

Public WithEvents RC As SpSharedRecoContext
Set RC = New SpSharedRecoContext

However, there are cases when a recognizer may be needed prior to declaring a recognition context. To do so, declare the recognizer in the standard fashion.

Dim SharedRecognizer As SpSharedRecognizer
Set SharedRecognizer = CreateObject("SAPI.SpSharedRecognizer")

Recognition Types

A recognition engine can be created with one of two types: Inproc and shared. The first, InProc, is within the same process as the application. An InProc recognizer restricts access to only that one application. For example, an InProc recognizer would prohibit other applications from using the system microphone. While other applications could run their own instance of an InProc recognizer, no resource could be common among them. An InProc engine may be used, for example when recognizing from a wav file. In fact, a shared engine may not use wav files for input.

The second type of recognizer is the shared recognizer. It is run is as a separate process from the application. As a result, other applications may use the engine's resources at the same time. For instance, the same system microphone will be used by all open applications. In turn, the resulting recognition from the engine may be used by any of the applications. In fact, shared engines go so far as to actually inform applications when a recognition result is not applicable to them.

For shared engines, a recognizer instance is created automatically when a recognition context is created. In this case, the type of recognizer will be the same as the type of recognition context. That is, a shared recognition context will create a shared recognizer of the same type as the active engine. However, all applications using a shared engine must create instances of that engine type. One application may not use one shared engine and a second application use another engine type.

InProc engines are similarly created in that an InProc engine instance is created when an InProc recognition context is created. InProc engine instances may be created separately. Each application may have only one InProc engine instance active at time. However, while an application can only have one InProc engine instance at a time, different applications, even if open at the same time, may each have a different engine active. For example, one application may be using an InProc English engine and another application may be recognizing from a Chinese engine.

Regardless, recognizers and recognition contexts must be the same type. If a recognizer is created as a shared resource, resulting recognition contexts associated with that recognizer must also be shared. The same is true for InProc recognizers and recognition contexts. See Recognition Event for an example. In addition, the recognition context is declared and created without having to declare the recognizer explicitly.

Automation Interface Elements

The ISpeechRecognizer automation interface contains the following elements:

Properties | Description
AllowAudioInputFormatChangesOnNextSet Property | Specifies whether the recognizer can change audio input formats on subsequent audio streams.
AudioInput Property | Gets and sets the recognizer's audio input device.
AudioInputStream Property | Gets and sets the recognizer's audio input stream.
IsShared Property | Indicates whether a recognition engine is shared or InProc.
Profile Property | Specifies the recognizer's current recognition profile.
Recognizer Property | Specifies characteristics about the active recognizer.
State Property | Returns the current state of the recognition engine.
Status Property | Returns an object representing the status of the recognizer.
Methods | Description
CreateRecoContext Method | Creates a recognition context object from the recognizer.
DisplayUI Method | Initiates the display of the specified UI.
EmulateRecognition Method | Emulates recognition from a textual source rather than from a spoken source.
GetAudioInputs Method | Returns a selection of the available audio input devices.
GetFormat Method | Returns the current input audio format.
GetProfiles Method | Returns a selection of the available user speech profiles.
GetPropertyNumber Method | Returns a numeric value specified by the named key.
GetPropertyString Method | Returns the string value corresponding to the specified key name.
GetRecognizers Method | Returns a selection of SpeechRecognizer objects in the speech configuration database.
IsUISupported Method | Determines if the specified UI is supported.
SetPropertyNumber Method | Sets a numeric property corresponding to the specified name.
SetPropertyString Method | Sets a text property corresponding to the specified name.


SpeechRecognizer AllowAudioInputFormatChangesOnNextSet Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: ISpeechRecognizer
Type: Hidden

AllowAudioInputFormatChangesOnNextSet Property

The AllowAudioInputFormatChangesOnNextSet property specifies whether the recognizer can change audio input formats on subsequent audio streams.

When this property is True, recognizer's input stream format is reset to match the speech recognition engine's preferred format. When this property is False, no changes to the audio format takes place. The default value of this property is True.

The format will not actually be changed until the next time the input is set. Calls to ISpeechRecognizer.AudioInput and ISpeechRecognizer.AudioInputStream set the input.

Syntax

Set: | SpeechRecognizer.AllowAudioInputFormatChangesOnNextSet = Boolean
Get: | Boolean = SpeechRecognizer.AllowAudioInputFormatChangesOnNextSet

Parts

SpeechRecognizer
The owning object.
Boolean
Set: A Boolean variable that sets the property.
Get: A Boolean variable that gets the property.

Example

The following Visual Basic form code demonstrates hot to retrieve and set the AllowAudioInputFormatChangesOnNextSet property. To run this code, paste it into the Declarations section of a form that contains no controls.

Option Explicit

Dim R As SpeechLib.SpSharedRecognizer
Dim T As SpeechLib.SpObjectToken

Private Sub Form_Load()

    Dim fAllowFormatChanges As Boolean

    On Error GoTo EH

    Set R = New SpSharedRecognizer
    fAllowFormatChanges = R.AllowAudioInputFormatChangesOnNextSet
    MsgBox "Default setting: " & fAllowFormatChanges

    R.AllowAudioInputFormatChangesOnNextSet = False
    fAllowFormatChanges = R.AllowAudioInputFormatChangesOnNextSet
    MsgBox "New setting: " & fAllowFormatChanges

    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer AudioInput Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

AudioInput Property

The AudioInput property gets and sets the recognizer's audio input device.

Syntax

Set: | SpeechRecognizer.AudioInput = SpObjectToken
Get: | SpObjectToken = SpeechRecognizer.AudioInput

Parts

SpeechRecognizer
The owning object.
SpObjectToken
Set: An SpObjectToken object that sets the property. If this parameter is Nothing, the default audio input device will be used.
Get: An SpObjectToken object that sets the property.

Example

The following Visual Basic form code demonstrates the use of the AudioInput property. The code displays the default audio input device. It then sets the recognizer's AudioInput property to Nothing and shows the results. Finally, the procedure lists the names of all available audio input devices.

To run this code, paste it into the Declarations section of a form that contains no controls.

Option Explicit

Dim R As SpeechLib.SpSharedRecognizer
Dim T As SpeechLib.SpObjectToken

Private Sub Form_Load()
    On Error GoTo EH

    Set R = New SpSharedRecognizer

    Debug.Print "New SpSharedRecognizer"
    Debug.Print "   AudioInput: " & R.AudioInput.GetDescription
    Debug.Print

    Set R.AudioInput = Nothing

    Debug.Print "Set to Nothing"
    Debug.Print "   AudioInput: " & R.AudioInput.GetDescription
    Debug.Print

    Debug.Print "Show all available inputs"
    For Each T In R.GetAudioInputs
        Debug.Print "   AudioInput: " & T.GetDescription
    Next

    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer AudioInputStream Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

AudioInputStream Property

The AudioInputStream property gets and sets the recognizer's audio input stream.

Using the AudioInputStream enables an application to use file streams or other stream objects for input rather than audio devices.

AudioInputStream is used with InProc recognizers only. Attempting to use it in a shared environment will result in an SPERR_NOT_SUPPORTED_FOR_SHARED_RECOGNIZER error.

Syntax

Set: | SpeechRecognizer.AudioInputStream = ISpeechBaseStream
Get: | ISpeechBaseStream = SpeechRecognizer.AudioInputStream

Parts

SpeechRecognizer
The owning object.
ISpeechBaseStream
Set: An ISpeechBaseStream variable that sets the property. If no value is stated, the default of Nothing will be passed in.
Get: An ISpeechBaseStream variable that gets the property.

Example

The following Visual Basic form code demonstrates the use of AudioInputStream. The application gets a wav file and uses that as the input source.

To run this code, create a form without any controls. The file is found in the SAPI 5.1 SDK and is a small, one word file. The location is assumed to be on the C: drive, although the string may be changed to accommodate other locations.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Const NL = vbNewLine
    Dim Buffer As Variant
    Dim FileName As String
    Dim FileStream As ISpeechFileStream
    Dim InProcRecoContext As SpInProcRecoContext
    Dim InProcRecognizer As SpInprocRecognizer

    Dim NumBytes As Variant
    Dim T As String

    Set InProcRecognizer = CreateObject("SAPI.SpInprocRecognizer")
    Set InProcRecoContext = InProcRecognizer.CreateRecoContext

    FileName = "C:\Program Files\Microsoft Speech SDK 5.4\Samples\"
    FileName = FileName & "CPP\Engines\TTS\MkVoice\selected.wav"
    Set FileStream = CreateObject("SAPI.SpFileStream")
    FileStream.Open FileName

    Set InProcRecognizer.AudioInputStream = FileStream
    NumBytes = InProcRecognizer.AudioInputStream.Read(Buffer, 100)
    T = "The first 100 bytes of recognizer's audio input stream are--"
    T = T & NL & NL & Buffer
    MsgBox T, vbInformation
    End

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer CreateRecoContext Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

CreateRecoContext Method

The CreateRecoContext method creates a recognition context object from the recognizer.

SpeechRecognizer.CreateRecoContext() As ISpeechRecoContext

Parameters

None.

Return Value

The CreateRecoContext method returns an ISpeechRecoContext object.

Example

The following Visual Basic form code demonstrates the use of CreateRecoContext.

To run this code, create a form without any controls. Copy this code and paste it into the Declarations section of the form.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Dim myContext As ISpeechRecoContext
    Dim SharedRecognizer As SpSharedRecognizer

    Set SharedRecognizer = New SpSharedRecognizer
    Set myContext = SharedRecognizer.CreateRecoContext
    MsgBox myContext.State, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer DisplayUI Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

DisplayUI Method

The DisplayUI method initiates the display of the specified UI.

The speech recognition (SR) and text-to-speech (TTS) engines are capable of displaying and running various user interfaces (UI). These displays assist with different aspects of the speech environment:

  • User training
  • Microphone training wizards
  • Adding and removing words
  • Setting controls for the engine

Many of these UIs are available using Speech properties in Control Panel. In addition, engines are capable of requesting specific UIs be run to improve a situation. For example, the SR could request more user training if the recognitions are consistently poor.

Engines are not required to support UIs and not all engines will have the same UIs. Consult the manufacturer's engine documentation for specific details. An application may call ISpeechRecognizer.IsUISupported before attempting to invoke a particular UI to see if the engine supports it. Invoking unsupported UIs will cause a run-time error. If the UI is available, use ISpeechRecognizer.DisplayUI to invoke the display.

SpeechRecognizer.DisplayUI(
     hWndParent As Long,
     Title As String,
     TypeOfUI As String,
     [ExtraData As Variant = Nothing]
)

Parameters

hWndParent
Specifies the window handle of the owning window.
Title
Specifies the caption used for the UI window.
TypeOfUI
A String specifying the name of the UI to display.
ExtraData
[Optional] Specifies the ExtraData. This information is unique to the application and may be used to provide additional or more specific information to the UI. By default, the Nothing value is used and indicates the UI does not use any additional information provided by this method.

Return Value

None.

Remarks

See ISpeechRecognizer.IsUISupported and ISpeechRecoContext.RequestUI for additional information.

Example

The following Visual Basic form code demonstrates the use of the DisplayUI event. The application runs the training wizard, the same one available using Speech properties in Control Panel.

To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

Option Explicit

Dim RC As SpSharedRecoContext

Private Sub Command1_Click()
    On Error GoTo EH

    Const Title = "My App's Additional Training"
    Dim SpRecog As ISpeechRecognizer
    Set SpRecog = RC.Recognizer

    SpRecog.DisplayUI Form1.hWnd, Title, SpeechUserTraining, ""

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Dim myGrammar As ISpeechRecoGrammar
    Set RC = New SpSharedRecoContext
    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer EmulateRecognition Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

EmulateRecognition Method

The EmulateRecognition method emulates recognition from a textual source rather than from a spoken source.

Using EmulateRecognition, applications can accept input from either speech or a textual source. All the events are fired back to the application exactly as if a normal recognition had taken place. The result phrase will have the semantic properties set in the same way as a spoken result. A recognition event will be produced only if the text actually parses through the active rules (if dictation is active, any text will parse).

Since the recognition attempt will not use an audio data, certain events such Interference, Hypothesis, and AudioLevel cannot occur.

SpeechRecognizer.EmulateRecognition(
     TextElements As Variant,
     [ElementDisplayAttributes As Variant = SDA_No_Trailing_Space],
     [LanguageId As Long = 0]
)

Parameters

TextElements
Specifies the elements of the phrase to to recognize. It must be one of two cases.
  • If TextElements is a BSTR string then it is assumed that the elements in TextElements are assumed to be space delimited and DisplayAttributes parameter is ignored.
  • If TextElements is an array of BSTR words then this parameter specifically lists each element in the phrase. ElementDisplayAttributes can be optionally specified as appropriate to the phrase's need.
In either case, additional information may be specified for each element by using the following syntax on each TextElement: "/display_text/lexical_form/pronunciation;". This syntax can be used in both the BSTR and the array of BSTRs case.
ElementDisplayAttributes
[Optional] Specifies the SpeechDisplayAttributes value for each word element. This value is specific to the language and usually determined by the speech recognition engine. By default the value is SDA_No_Trailing_Space and is considered standard for English languages. This parameter is only valid if an array of BSTRs for the TextElements parameter is specified. It must be one of three cases.
  • If ElementDisplayAttributes is a NULL pointer, VT_NULL, or VT_EMPTY then SDA_No_Trailing_Space is assumed (which is the default).
  • If it is a BSTR then it can be "" (empty string), " " (space), or " " (double space) and SAPI matches the SpeechDisplayAttribute uses it for all text elements. If an integer value (VT_I1 to VT_I4) is specified, then this value is the SpeechDisplayAttribute value and will is used for each element in the words array.
  • If it is an array of integer values (VT_I1 to VT_I4) SAPI uses those values for the SpeechDisplayAttribute.
LanguageId
[Optional] Specifies the LanguageId. This is the same as the Win32 Language Identifier (LANGID). By default the value is zero, indicating the system default is used.

Return Value

None.

Remarks

Use this method (simulating speech) to test applications that use speech recognition. Also the restrictions in the parameters TextElements and ElementDisplayAttributes accommodate languages not using spaces to separate words.

Example

The following Visual Basic form code demonstrates the use of EmulateRecognition. The application displays the successful recognition result of dictation. It also emulates speech by clicking the button.

To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates and activates a dictation grammar. Click Command1 to start emulated speech and display results.

Option Explicit

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    On Error GoTo EH

    Set RC = New SpSharedRecoContext
    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()
    On Error GoTo EH

    RC.Recognizer.EmulateRecognition ("We the people")

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RC_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    On Error GoTo EH
    MsgBox Result.PhraseInfo.GetText, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer GetAudioInputs method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

GetAudioInputs Method

The GetAudioInputs method returns a selection of the available audio input devices.

Audio input devices (sound cards, for example) are stored in the speech configuration database as a series of tokens, with each token representing one audio input device. GetAudioInputs retrieves all available audio tokens. The returned list is an ISpeechObjectTokens object. Additional or more detailed information about the tokens is available in methods associated with ISpeechObjectTokens.

The token search may be further refined using the RequiredAttributes and OptionalAttributes search attributes. Only tokens matching the specified RequiredAttributes search attributes are returned. Of those tokens matching the RequiredAttributes key, OptionalAttributes lists devices in the order matching OptionalAttributes. If no search attributes are offered, all tokens are returned. If no audio devices match the criteria, GetAudioInputs returns an empty selection, that is, an ISpeechObjectTokens collection with an ISpeechObjectTokens::Count property of zero.

See Object Tokens and Registry Settings White Paper for a list of SAPI 5-defined attributes.

SpeechRecognizer.GetAudioInputs(
     [RequiredAttributes As String = ""],
     [OptionalAttributes As String = ""]
) As ISpeechObjectTokens

Parameters

RequiredAttributes
[Optional] Specifies the RequiredAttributes. To be returned by GetAudioInputs, audio input tokens must contain all of the specific required attributes. If no profiles match the selection, the selection returned will not contain any elements. By default, no attributes are required and so returns all the tokens discovered.
OptionalAttributes
[Optional] Specifies the OptionalAttributes. Returned tokens containing the RequiredAttributes are sorted by OptionalAttributes. If OptionalAttributes is specified, the tokens are listed with the OptionalAttributes first. By default, no attribute is specified and the list returned from the speech configuration database is in the order that attributes were discovered.

Return Value

An ISpeechObjectTokens collection containing the selected audio input tokens.

Remarks

The format of selection criteria may either be Value or "Attribute = Value". Values may be excluded by "Attribute != Value".

Example

This code sample demonstrates the GetAudioInputs method. After creating an instance for a recognizer, GetAudioInputs polls the computer for available audio input tokens and displays the results.

To run this code, create a form without any controls. Paste this code into the Declarations section of the form.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Const NL = vbNewLine
    Dim i As Long
    Dim SharedRecognizer As SpSharedRecognizer
    Dim T As String
    Dim theRecognizers As ISpeechObjectTokens
    Dim tokenObject As SpObjectToken

    Set SharedRecognizer = CreateObject("SAPI.SpSharedRecognizer")
    Set theRecognizers = SharedRecognizer.GetAudioInputs

    For i = 0 To theRecognizers.Count - 1
        Set tokenObject = theRecognizers.Item(i)
        T = T & tokenObject.GetDescription & NL
    Next i

    T = "Available audio input devices--" & NL & NL & T
    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer GetFormat Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

GetFormat Method

The GetFormat method returns the current input audio format.

The sound format may be different at different times or at different points during processing. For example, the audio format at the time the input reaches the sound device (the audio card for instance) may differ from the audio format by the time it reaches the speech recognition (SR) engine. GetFormat specifies which location should be polled and returns the audio format for that location.

SpeechRecognizer.GetFormat(
     Type As SpeechFormatType
) As SpAudioFormat

Parameters

Type
Request for the audio format at entering the sound device or SR engine.

Return Value

The GetFormat method returns an SpAudioFormat variable.

Example

This code example demonstrates the GetFormat method. After a successful recognition, two GetFormat calls poll SAPI for the audio formats of the sound device and the SR engine and display the results in a message box.

To run this code, create a form without any controls. Paste this code into the Declarations section of the form.

Option Explicit

Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Form_Load()
    On Error GoTo EH

    Set RC = New SpSharedRecoContext
    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive
    RC.Recognizer.EmulateRecognition ("We the people")

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RC_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    On Error GoTo EH

    Const NL = vbNewLine
    Dim audioFormat As SpAudioFormat
    Dim T As String

    T = "Text recognized: " & Result.PhraseInfo.GetText & NL

    Set audioFormat = RC.Recognizer.GetFormat(SFTInput)
    T = T & "Audio input type: " & audioFormat.Type & NL

    Set audioFormat = RC.Recognizer.GetFormat(SFTSREngine)
    T = T & "SR engine input type: " & audioFormat.Type
    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer GetProfiles method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

GetProfiles Method

The GetProfiles method returns a selection of the available user speech profiles.

Profiles are stored in the speech configuration database as a series of tokens, with each token representing one profile. GetProfiles retrieves all available profile tokens. The returned list is an ISpeechObjectTokens object. Additional or more detailed information about the tokens is available in methods associated with ISpeechObjectTokens.

The token search may be further refined using the RequiredAttributes and OptionalAttributes search attributes. Only tokens matching the specified RequiredAttributes search attributes are returned. Of those tokens matching the RequiredAttributes key, OptionalAttributes lists devices in the order matching OptionalAttributes. If no search attributes are offered, all tokens are returned. If no audio devices match the criteria, GetAudioInputs returns an empty selection, that is, an ISpeechObjectTokens collection with an ISpeechObjectTokens::Count property of zero.

See Object Tokens and Registry Settings White Paper for a list of SAPI 5-defined attributes.

SpeechRecognizer.GetProfiles(
     [RequiredAttributes As String = ""],
     [OptionalAttributes As String = ""]
) As ISpeechObjectTokens

Parameters

RequiredAttributes
[Optional] Specifies the RequiredAttributes. To be returned by GetProfiles, profile tokens must contain all of the specific required attributes. If no profiles match the selection, the selection returned will not contain any elements. By default, no attributes are required and so returns all the tokens discovered.
OptionalAttributes
[Optional] Specifies the OptionalAttributes. Returned tokens containing the RequiredAttributes are sorted by OptionalAttributes. If OptionalAttributes is specified, the tokens are listed with the OptionalAttributes first. By default, no attribute is specified and the list returned from the speech configuration database is in the order that attributes were discovered.

Return Value

An ISpeechObjectTokens object.

Remarks

The format of selection criteria may either be Value or "Attribute = Value". Values may be excluded by "Attribute != Value".

See ISpeechRecognizer.Profile for related details.

Example

This code sample demonstrates the GetProfiles and Profile method. After creating an instance for a recognizer, GetProfiles polls the computer for available profile tokens. The results are displayed. The first one listed is the current profile. Clicking the button will change the current profile to the first different profile found.

To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

It is possible for your computer to have only one profile. To fully demonstrate this method, additional profiles should be added. Add new profiles through the Speech properties of Control Panel.

Option Explicit

Public SharedRecognizer As SpSharedRecognizer
Public theRecognizers As ISpeechObjectTokens

Private Sub Command1_Click()
    On Error GoTo EH

    Dim currentProfile As SpObjectToken
    Dim i As Integer
    Dim T As String
    Dim TokenObject As ISpeechObjectToken
    Set currentProfile = SharedRecognizer.Profile

    For i = 0 To theRecognizers.Count - 1
        Set TokenObject = theRecognizers.Item(i)

        If tokenObject.Id <> currentProfile.Id Then
            Set SharedRecognizer.Profile = TokenObject
            T = "New Profile installed: "
            T = T & SharedRecognizer.Profile.GetDescription
            Exit For
        Else
            T = "No new profile has been installed."
        End If
    Next i

    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Const NL = vbNewLine
    Dim i, idPosition As Long
    Dim T As String
    Dim TokenObject As SpObjectToken

    Set SharedRecognizer = CreateObject("SAPI.SpSharedRecognizer")
    Set theRecognizers = SharedRecognizer.GetProfiles

    For i = 0 To theRecognizers.Count - 1
        Set TokenObject = theRecognizers.Item(i)
        T = T & TokenObject.GetDescription & "--" & NL & NL
        idPosition = InStrRev(TokenObject.Id, "\")
        T = T & Mid(TokenObject.Id, idPosition + 1) & NL
    Next i

    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer GetPropertyNumber method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer
Type: Hidden

GetPropertyNumber Method

The GetPropertyNumber method returns a numeric value specified by the named key.

The speech recognition (SR) engine maintains several changeable values for setting the characteristics of the SR process. These controls, or properties, are listed in pairs with the control name and an associated value. For example, the SAPI 5 SR engine defines a property allocating CPU usage for the SR engine. This property is named ResourceUsage, and has a range of 0 to 100 percent. The default value is 50. This number is the percentage of the CPU time allocated for SR processing. This value may be changed to increase or decrease the processing time for SR features.

To get the current value, call ISpeechRecognizer.GetPropertyNumber. To set a new value, call ISpeechRecognizer.SetPropertyNumber. In addition, a PropertyNumberChange event is sent after the change is made. This event is broadcast to all applications set to receive it. Since multiple applications, or even recognition contexts within the same application can use the same SR engine, the applications may need to react to the new settings appropriately. Applications should restrict making changes unless there is a compelling reason. Changes to the engine properties will take effect at the next synchronization point. The changes persist in the engine until properties are changed again.

Persisting the changes on a permanent basis is an engine design issue. There is no requirement to do so and each engine manufacturer may implement changing characteristics differently. See the manufacturer's engine documentation for specific details. The SAPI 5 engine changes are not permanent beyond the life span of the recognizer object. That is, when all the applications using the same recognizer object (essentially an SR engine) quit, the values will return to the default state.

If properties need to be changed in a SAPI 5 engine, use Speech properties in Control Panel. For instance, the AdaptationOn property controlling background and continuous adaptation of speech recognition is the same property as Background Adaptation in Settings for the Recognition Profile on the Speech Recognition tab.

Properties are not required of SR engines and each manufacturer's engine may be different. Consult the manufacturer's documentation for specific information.

SpeechRecognizer.GetPropertyNumber(
     Name As String,
     Value As Long
) As Boolean

Parameters

Name
Specifies the string name of the property.
Value
Specifies the value associated with the property Name. This value is passed back upon successful completion of the call. If the return value is False, Value will not be updated.

Return Value

A Boolean variable of True if the property is supported, or False if not supported.

Remarks

For a complete list of SAPI 5 supported properties, see the SAPI 5 SR Properties White Paper.

Example

The following Visual Basic form code demonstrates the use of the SetPropertyNumber method, GetPropertyNumber method, and PropertyNumberChange event.

To run this code, create a form with the following controls:

  • Two command buttons called Command1 and Command2

Paste this code into the Declarations section of the form.

Clicking Command1 displays the current value of the property. The second button increments the value by one and the new value is displayed as a result of the PropertyNumberChange event. The original or starting value will be the same as the Accuracy vs. Recognition Response Time slider in the Recognition Profile Settings in the Speech properties of Control Panel.

Option Explicit

Const THE_PROPERTY = "ResourceUsage"
Public WithEvents RC As SpSharedRecoContext
Public myGrammar As ISpeechRecoGrammar

Private Sub Command1_Click()
    On Error GoTo EH

    Dim lActualValue As Long
    Dim fSupported As Boolean
    Dim T As String

    fSupported = RC.Recognizer.GetPropertyNumber(THE_PROPERTY, lActualValue)
    T = "Property's current value: " & lActualValue
    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH

    Dim lActualValue As Long
    Dim fSupported As Boolean

    With RC.Recognizer
        fSupported = .GetPropertyNumber(THE_PROPERTY, lActualValue)
        fSupported = .SetPropertyNumber(THE_PROPERTY, lActualValue + 1)
    End With

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH
    Set RC = New SpSharedRecoContext

    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RC_PropertyNumberChange _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal PropertyName As String, _
    ByVal NewNumberValue As Long)

    On Error GoTo EH
    MsgBox "Property's value has been incremented by 1.", vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer GetPropertyString method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer
Type: Hidden

GetPropertyString Method

The GetPropertyString method returns the string value corresponding to the specified key name.

The SAPI 5 speech recognition (SR) engine does not support any properties with associated string values. However, other manufacturer's engines could. See ISpeechRecognizer.GetPropertyNumber for a related and similar feature.

SpeechRecognizer.GetPropertyString(
     Name As String,
     Value As String
) As Boolean

Parameters

Name
Specifies the string name of the property.
Value
Specifies the String value associated with the property Name. This value is passed back upon successful completion of the call. If the return value is False, Value will not be updated.

Return Value

A Boolean variable of True if the property is supported, or False if not supported.

Example

See ISpeechRecognizer.GetPropertyNumber for a related code sample.


SpeechRecognizer GetRecognizers Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

GetRecognizers Method

The GetRecognizers method returns a selection of SpeechRecognizer objects in the speech configuration database.

Recognizers are stored in the speech configuration database as a series of tokens, with each token representing one recognizer (also called a speech recognition engine). GetRecognizers retrieves all available recognizer tokens and returns the in a list as an ISpeechObjectTokens object. Additional or more detailed information about the tokens is available in methods associated with ISpeechObjectTokens. If no recognizers match the criteria, GetRecognizers returns an empty selection, that is, an ISpeechObjectTokens collection with an ISpeechObjectTokens::Count property of zero.

The recognizer token search may be further refined by using the RequiredAttributes and OptionalAttributes search attributes. Only token matching the specified search attributes are returned. If no search attributes are offered, all tokens are returned.

See Object Tokens and Registry Settings White Paper for a list of SAPI 5-defined attributes.

ISpeechRecognizer.GetRecognizers(
     [RequiredAttributes As String = ""],
     [OptionalAttributes As String = ""]
) As ISpeechObjectTokens

Parameters

RequiredAttributes
[Optional] Specifies the RequiredAttributes. To be returned by GetRecognizers, recognizer tokens must contain all of the specific required attributes. If no recognizers match the selection, the selection returned will not contain any elements. By default no attributes are required and the method returns all the token discovered.
OptionalAttributes
[Optional] Specifies the OptionalAttributes. Returned tokens containing the RequiredAttributes are sorted by OptionalAttributes. If OptionalAttributes is specified, the tokens are listed with the OptionalAttributes first. By default, no attribute is specified and the list returned from the speech configuration database is in the order that attributes were discovered.

Return Value

A ISpeechObjectTokens collection containing tokens for the selected recognizers.

Remarks

The format of selection criteria may either be Value or "Attribute = Value". Values may be excluded by "Attribute != Value".

Example

This code example demonstrates the GetRecognizers method. After creating an instance for a recognizer, GetRecognizers polls the computer for available recognizer tokens, which represent individual engines. The results are displayed. Then the computer is repolled for recognizer tokens that are able to support telephony.

To run this code, create a form without any controls. Paste this code into the Declarations section of the form.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Const NL = vbNewLine
    Dim i As Long
    Dim recoObject As SpObjectToken
    Dim SharedRecognizer As SpSharedRecognizer
    Dim T As String
    Dim theRecognizers As ISpeechObjectTokens

    Set SharedRecognizer = CreateObject("SAPI.SpSharedRecognizer")
    Set theRecognizers = SharedRecognizer.GetRecognizers

    For i = 0 To theRecognizers.Count - 1
        Set recoObject = theRecognizers.Item(i)
        T = T & recoObject.GetDescription & NL
    Next i

    MsgBox T, vbInformation
    T = ""

    Set theRecognizers = SharedRecognizer.GetRecognizers("Telephony")

    For i = 0 To theRecognizers.Count - 1
        Set recoObject = theRecognizers.Item(i)
        T = T & recoObject.GetDescription & NL
    Next i

    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer IsShared Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

IsShared Property

The IsShared property indicates whether a recognition engine is shared or in process (InProc).

Syntax

Set: | (This property is read-only)
Get: | Boolean = SpeechRecognizer.IsShared

Parts

SpeechRecognizer
The owning object.
Boolean
Set: (This property is read-only)
Get: A Boolean variable ISpeechRecognizer the property. True indicates the recognizer is shared; False indicates that it is an InProc recognizer.

Example

The following Visual Basic form code demonstrates the use of IsShared. Paste this code into the Declarations section of the form.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Dim RC1 As SpSharedRecoContext
    Dim RC2 As SpInProcRecoContext
    Dim T As String

    Set RC1 = New SpSharedRecoContext
    Set RC2 = New SpInProcRecoContext

    If RC1.Recognizer.IsShared = True Then
        T = "Recognizer #1 is shared." & vbNewLine
    End If

    If RC2.Recognizer.IsShared = False Then
        T = T & "Recognizer #2 is Inproc."
    End If

    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer IsUISupported Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

IsUISupported Method

The IsUISupported method determines if the specified UI is supported.

The speech recognition (SR) and text-to-speech (TTS) engines are capable of displaying and running various user interfaces (UI). These displays assist with different aspects of the speech environment such as user training, microphone wizards, adding and removing words, or setting controls for the engine. Many of these UIs are available using Speech properties in Control Panel. In addition, the engines are capable of requesting that specific UIs are run to improve a situation. For example, the SR could request more user training if the recognitions are consistently poor.

Engines are not required to support UI and not all engines will have the same UI. Consult the manufacturer's engine documentation for specific details. An application may call ISpeechRecognizer.IsUISupported before attempting to invoke a particular UI to see if the engine supports it. Invoking unsupported UIs will cause a run-time error. If the UI is available, use ISpeechRecognizer.DisplayUI to invoke the display.

SpeechRecognizer.IsUISupported(
     TypeOfUI As String,
     [ExtraData As Variant = Nothing]
) As Boolean

Parameters

TypeOfUI
A String specifying the name of the UI to display.
ExtraData
[Optional] Specifies the ExtraData. This information is unique to the application and may be used to provide additional or more specific information to the UI. By default the Nothing value is used and indicates the UI does not use any additional information provided by this method.

Return Value

The IsUISupported method returns a Boolean variable.

Remarks

See ISpeechRecognizer.DisplayUI and ISpeechRecoContext.RequestUI for additional information.

Example

The following Visual Basic form code demonstrates the use of the IsUISupported method. The application attempts to run two UIs. The first is the training wizard (the same one available using Speech properties in Control Panel) and the second UI is a nonexistent one called MyApp.

To run this code, create a form without any controls. Paste this code into the Declarations section of the form.

Option Explicit

Dim RC As SpSharedRecoContext
Private Sub Command1_Click()

    RunUI SpeechUserTraining
    RunUI "MyApp"

End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Set RC = New SpSharedRecoContext

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Function RunUI(theUI As String)
    On Error GoTo EH

    Const Title = "My App's Additional Training"
    Dim T As String

    If RC.Recognizer.IsUISupported(theUI) = True Then
        RC.Recognizer.DisplayUI Form1.hWnd, Title, theUI, ""
        T = theUI & " UI is supported."
    Else
        T = theUI & " UI is not supported."
    End If

    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Function

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer Profile Property (Microsoft Speech Platform)

Microsoft Speech Platform

Interface: ISpeechRecognizer

Profile Property

The Profile property specifies the speech recognition engine's current recognition profile.

A recognition profile represents a single user and training sessions on the system. The user can manually create, delete, and set the current profile using Speech properties in Control Panel.

A profile should not be set while the engine is active. Doing so while a recognition engine is active can cause unexpected results, depending on how and when the speech recognition engine reads the profile information.

The newly-installed profile is not a permanent change but is valid only for the life span of the recognizer. To set it as the default, use SpObjectTokenCategory.Default.

Syntax

Set: | SpeechRecognizer.Profile = SpObjectToken
Get: | SpObjectToken = SpeechRecognizer.Profile

Parts

SpeechRecognizer
The owning object.
SpObjectToken
Set: An SpObjectToken variable that sets the profile. If no value is stated, the default of Nothing will be passed in.
Get: An SpObjectToken variable that gets the current profile.

Example

See ISpeechRecognizer.GetProfiles for a complete example.


SpeechRecognizer Recognizer Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

Recognizer Property

The Recognizer property specifies characteristics about the active recognizer.

Recognizers and the attributes associated with them are stored in the speech configuration database as a series of tokens, with each token representing one attribute. Recognizer retrieves an object (SpObjectToken) which is capable of accessing the attributes for the recognizer. Additional or more detailed information about the tokens is available in methods associated with SpObjectToken.

See Object Tokens and Registry Settings White Paper for a list of SAPI 5-defined engine attributes.

Syntax

Set: | SpeechRecognizer.Recognizer = SpObjectToken
Get: | SpObjectToken = SpeechRecognizer.Recognizer

Parts

SpeechRecognizer
The owning object.
SpObjectToken
Set: An SpObjectToken variable that sets the property.
Get: An SpObjectToken variable that gets the property.

Example

This code example demonstrates the Recognizer property. After creating an instance for a recognizer, the Recognizer property can retrieve attribute information about the active recognizer. The engine ID is displayed. Also two attributes are attempted to be displayed. The first is "VendorPreferred", an attribute that exists for the SAPI 5 SR engine. The other is "MyEngineAttribute", which should not be present. Tokens not found will cause a run-time error and as a result, require error handling code.

To run this code, create a form with no controls. Paste this code into the Declarations section of the form.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Const NL = vbNewLine
    Dim objectToken As SpObjectToken
    Dim RC As SpSharedRecoContext
    Dim T As String
    Dim TokenName As String
    Dim Value As String

    Set RC = New SpSharedRecoContext
    Set objectToken = RC.Recognizer.Recognizer

    T = "Id: " & RC.Recognizer.Recognizer.Id & NL
    TokenName = "VendorPreferred"
    Value = objectToken.GetAttribute(TokenName)

    If Len(Value) = 0 Then
        T = T & TokenName & " attribute's value: Zero-length string" & NL
    End If

    TokenName = "MyEngineAttribute"
    On Error Resume Next
    T = TokenName & " : " & objectToken.GetAttribute(TokenName)

    If Err.Number Then
        Err.Clear
        T = T & "There is no attribute named 'MyEngineAttribute'."
    End If

    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer SetPropertyNumber method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer
Type: Hidden

SetPropertyNumber Method

The SetPropertyNumber method sets a numeric property corresponding to the specified name.

See ISpeechRecognizer.GetPropertyNumber for complete details and code sample.

SpeechRecognizer.SetPropertyNumber(
     Name As String,
     Value As Long
) As Boolean

Parameters

Name
Specifies the string name of the property.
Value
Specifies the new value of property Name. If the return value is False, Name will not be changed.

Return Value

A Boolean variable of True if the property is supported, or False if not supported.

Remarks

For a complete list of SAPI 5 supported properties see the SAPI 5 SR Properties White Paper.

Example

See ISpeechRecognizer.GetPropertyNumber for a complete code sample.


SpeechRecognizer SetPropertyString method (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer
Type: Hidden

SetPropertyString Method

The SetPropertyString method sets a text property corresponding to the specified name.

The SAPI 5 speech recognition (SR) engine does not support any properties with associated string values. However, other manufacturer's engines could. See ISpeechRecognizer.GetPropertyNumber for a related and similar feature.

SpeechRecognizer.SetPropertyString(
     Name As String,
     Value As String
) As Boolean

Parameters

Name
Specifies the string name of the property.
Value
Specifies the new String value of property Name. If the return value is False, Name will not be changed.

Return Value

A Boolean variable of True if the property is supported, or False if not supported.

Example

See ISpeechRecognizer.GetPropertyNumber for a related code sample.


SpeechRecognizer State Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

State Property

The State property returns the current state of the recognition engine.

The recognition engine may be in one of several states of audio processing. If active, the engine receives audio data and processes it. Likewise, if inactive, neither audio data nor additional processing takes place. See the enumeration SpeechRecognizerState for complete details of the states.

Syntax

Set: | SpeechRecognizer.State = SpeechRecognizerState
Get: | SpeechRecognizerState = SpeechRecognizer.State

Parts

SpeechRecognizer
The owning object.
SpeechRecognizerState
Set: A SpeechRecognizerState variable that sets the property.
Get: A SpeechRecognizerState variable that gets the property.

Example

This code example demonstrates the State property. After creating an instance for a recognizer, the code retrieves and then changes the processing state of the recognizer.

To run this code, create a form with no controls. Paste this code into the Declarations section of the form.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Dim RC As SpSharedRecoContext
    Dim T As String

    Set RC = New SpSharedRecoContext

    With RC.Recognizer
        If .State = SRSActive Then
            .State = SRSInactive
            T = "Recognition engine's state has been" & vbNewLine
            T = T & "changed from SRSActive to SRSInactive."
        End If
    End With

    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpeechRecognizer Status Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecognizer

Status Property

The Status property returns an object representing the status of the recognizer.

This method provides information for static features about the speech recognition (SR) engine such as the languages it supports. It also provides information for dynamic features such as current stream position the engine has recognized up to, and if the stream is actively being sent to the engine.

Syntax

Set: | (This property is read-only)
Get: | ISpeechRecognizerStatus = SpeechRecognizer.Status

Parts

SpeechRecognizer
The owning object.
ISpeechRecognizerStatus
Set: (This property is read-only)
Get: An ISpeechRecognizerStatus that gets the property.

Example

This code example demonstrates the Status property. After creating an instance for a recognizer, the code retrieves information about the recognizer's status: the class ID that created the engine, the supported languages, (in decimal format), and the current device position.

To run this code, create a form with no controls. Paste this code into the Declarations section of the form.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Const NL = vbNewLine
    Dim i As Integer
    Dim myGrammar As ISpeechRecoGrammar
    Dim RC As SpSharedRecoContext
    Dim recoStatus As ISpeechRecognizerStatus
    Dim T As String

    Set RC = New SpSharedRecoContext
    Set myGrammar = RC.CreateGrammar
    myGrammar.DictationSetState SGDSActive

    Set recoStatus = RC.Recognizer.Status

    T = "Engine ID: " & recoStatus.ClsidEngine & NL

    ' Display supported languages--
    For i = 0 To UBound(recoStatus.SupportedLanguages)
        T = T & "Supported Language ID: "
        T = T & recoStatus.SupportedLanguages(i) & NL
    Next i

    ' Display audio position.
    T = T & "Audio Position: "
    T = T & recoStatus.AudioStatus.CurrentDevicePosition

    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpLexicon Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpLexicon

The SpLexicon automation object provides access to lexicons. Lexicons contain information about words that can be recognized or spoken.

SAPI defines two types of lexicons. The first is the application lexicon. Application lexicons are the words that all applications can use. They are installed by speech-enabled applications and are read-only. As a result, the application lexicons may vary slightly among computers. The second type is the user lexicon. User lexicons store words specific to a speech user.

An SpLexicon object includes the user lexicon and all application lexicons available on the computer. Calls to SpLexicon methods may return data from several different lexicons.

The SpUnCompressedLexicon object represents a single application lexicon.

Automation Interface Elements

The SpLexicon automation object contains the following elements:

Properties | Description
GenerationId Property | Gets the generation ID of the current application lexicon.
Methods | Description
AddPronunciation Method | Adds a pronunciation, specified in phone symbols, to the current user lexicon.
AddPronunciationByPhoneIds Method | Adds a pronunciation, specified in phone IDs, to the current user lexicon.
GetGenerationChange Method | Gets a list of words in the current user lexicon that have changed since the specified generation.
GetPronunciations Method | Gets the pronunciations and parts of speech for a word from the user and application lexicons.
GetWords Method | Gets a list of all words in the current user and application lexicons.
RemovePronunciation Method | Removes a word and/or its pronunciations, specified in phone symbols, from the user lexicon.
RemovePronunciationByPhoneIds Method | Removes a word and/or its pronunciations, specified in phone IDs, from the user lexicon.


SpLexicon AddPronunciation Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpLexicon

AddPronunciation Method

The AddPronunciation method adds a pronunciation, specified in phone symbols, to the current user lexicon.

SpLexicon.AddPronunciation(
     bstrWord As String,
     LangId As Long,
     [PartOfSpeech As SpeechPartOfSpeech = SPSUnknown],
     [bstrPronunciation As String = ""]
)

Parameters

bstrWord
The word to add.
LangId
The language Id of the word.
PartOfSpeech
[Optional] The PartOfSpeech. Default value is SPSUnknown.
bstrPronunciation
[Optional] The pronunciation, in phones.

Return Value

None.


SpLexicon AddPronunciationByPhoneIds method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpLexicon
Type: Hidden

AddPronunciationByPhoneIds Method

The AddPronunciationByPhoneIds method adds a pronunciation, specified in phone IDs, to the current user lexicon.

SpLexicon.AddPronunciationByPhoneIds(
     bstrWord As String,
     LangId As Long,
     [PartOfSpeech As SpeechPartOfSpeech = SPSUnknown],
     [PhoneIds As Variant = Nothing]
)

Parameters

bstrWord
The word to add.
LangId
The language Id of the word.
PartOfSpeech
[Optional] The PartOfSpeech. Default value is SPSUnknown.
PhoneIds
[Optional] The pronunciation, in phone IDs. By default the Nothing value is used.

Return Value

None.


SpLexicon GenerationId Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpLexicon
Type: Hidden

GenerationId Property

The GenerationId property gets the generation ID of the current user lexicon.

The GenerationId functions acts as a version number, making it possible to roll back, cancel or undo additions to the lexicon.

Syntax

Set: | (This property is read-only)
Get: | Long = SpLexicon.GenerationId

Parts

SpLexicon
The owning object.
Long
Set: (This property is read-only)
Get: A Long variable returning the generation ID.


SpLexicon GetGenerationChange Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpLexicon

GetGenerationChange Method

The GetGenerationChange method gets a list of words in the current user lexicon that have changed since the specified generation.

SpLexicon.GetGenerationChange(
     GenerationID As Long
) As ISpeechLexiconWords

Parameters

GenerationID
Specifies the GenerationID.

Return Value

The GetGenerationChange method returns an ISpeechLexiconWords variable.


SpLexicon GetPronunciations Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpLexicon

GetPronunciations Method

The GetPronunciations method gets the pronunciations and parts of speech for a word from the user and application lexicons.

An ISpeechLexiconPronunciation object contains a word's pronunciations, part of speech and phone ids. Because a word may have more than one pronunciation and more than one part of speech, the GetPronunciations method returns a collection of these objects.

SpLexicon.GetPronunciations(
     bstrWord As String,
     [LangId As Long = 0],
     [TypeFlags As SpeechLexiconType = SLTUser | SLTApp]
) As ISpeechLexiconPronunciations

Parameters

bstrWord
The target lexicon word.
LangId
[Optional] The language Id. By default the value is zero which indicates the system LangId is used.
TypeFlags
[Optional] TypeFlags.

Return Value

An ISpeechLexiconPronunciations object, which is a collection of one or more ISpeechLexiconPronunciation objects.


SpLexicon GetWords Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpLexicon

GetWords Method

The GetWords method gets a list of all words in the current user and application lexicons.

SpLexicon.GetWords(
     [Flags As SpeechLexiconType = SLTUser | SLTApp],
     [GenerationID As Long = 0]
) As ISpeechLexiconWords

Parameters

Flags
[Optional] If Flags is SLTUser, user lexicon words are returned; SLTApp returns application lexicon words. By default both types of words are returned.
GenerationID
[Optional] The GenerationID. By default the value is zero.

Return Value

An ISpeechLexiconWords object, which is a collection of one or more ISpeechLexiconWord objects.

Remarks

It frequently requires several calls to GetWords to retrieve all of the words in a lexicon. From one call of GetWords to another, it is possible for the lexicon to be updated, which causes different values for GenerationID. To maintain consistency in the retrieved lexicon words, a caller of this method should use only the value of GenerationID that is passed out after the first call to GetWords.


SpLexicon RemovePronunciation Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpLexicon

RemovePronunciation Method

The RemovePronunciation method removes a word and/or its pronunciations, specified in phone symbols, from the current user lexicon.

SpLexicon.RemovePronunciation(
     bstrWord As String,
     LangId As Long,
     [PartOfSpeech As SpeechPartOfSpeech = SPSUnknown],
     [bstrPronunciation As String = ""]
)

Parameters

bstrWord
The lexicon word to be removed.
LangId
The language Id.
PartOfSpeech
[Optional] The PartOfSpeech. Default value is SPSUnknown.
bstrPronunciation
[Optional] The pronunciation, in phones, to be removed. If this parameter is not specified, all pronunciations of the word will be removed.

Return Value

None.


SpLexicon RemovePronunciationByPhoneIds method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpLexicon
Type: Hidden

RemovePronunciationByPhoneIds Method

The RemovePronunciationByPhoneIds method removes a word and/or its pronunciations, specified in phone IDs, from the current user lexicon.

SpLexicon.RemovePronunciationByPhoneIds(
     bstrWord As String,
     LangId As Long,
     [PartOfSpeech As SpeechPartOfSpeech = SPSUnknown],
     [PhoneIds As Variant = Nothing]
)

Parameters

bstrWord
The lexicon word to be removed.
LangId
The language Id.
PartOfSpeech
[Optional] The PartOfSpeech. Default value is SPSUnknown.
PhoneIds
[Optional] The pronunciation, in phone ids, to be removed. If this parameter is not specified, all pronunciations of a lexicon word will be removed.

Return Value

None.


SpMemoryStream Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpMemoryStream

The SpMemoryStream automation object supports audio stream operations in memory.

The Format property and the Read, Write and Seek methods are inherited from the ISpeechBaseStream interface.

Automation Interface Elements

The SpMemoryStream automation object has the following elements:

Properties | Description
Format Property | Gets and sets the cached wave format of the stream as an SpAudioFormat object.
Methods | Description
GetData Method | Gets the contents of the stream.
Read Method | Reads data from an audio stream.
Seek Method | Returns the current read position of the audio stream in bytes.
SetData Method | Sets the contents of the stream.
Write Method | Writes data to the audio stream.


SpMemoryStream GetData method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpMemoryStream

GetData Method

The GetData method gets the entire contents of the stream.

The GetData method does not change the stream's Seek pointer.

SpMemoryStream.GetData() As Variant

Parameters

None.

Return Value

A Variant variable containing the stream data.


SpMemoryStream SetData method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpMemoryStream

SetData Method

The SetData method sets the contents of the stream.

The SetData method writes stream data into the memory stream, and sets the Seek pointer to zero, so that the next SetData call to the stream will overwrite the data just written.

SpMemoryStream.SetData(
     Data As Variant
)

Parameters

Data
Specifies the Data.

Return Value

None.


SpMMAudioIn Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpMMAudioIn

The SpMMAudioIn automation object supports audio implementation for the standard Windows wave-in multimedia layer.

Automation Interfaces

The SpMMAudioIn automation object contains the following elements:

Properties | Description
BufferInfo Property | Returns the audio buffer information as an ISpeechAudioBufferInfo object.
BufferNotifySize Property | Gets and sets the audio stream buffer size information.
DefaultFormat Property | Returns the default audio format as an SpAudioFormat object.
DeviceId Property | Gets and sets the multimedia device ID that is used by the audio object.
EventHandle Property | Returns a Win32 event handle that applications can use to wait for status changes in the I/O stream.
Format Property | Gets and sets the cached wave format of the stream as an SpAudioFormat object.
LineId Property | Gets and sets the current line identifier associated with the multimedia device.
MMHandle Property | Returns the handle of the multimedia audio device stream.
Status Property | Returns the audio status as an ISpeechAudioStatus object.
Volume Property | Gets and sets the volume level.
Methods | Description
Read Method | Reads data from the audio stream.
Seek Method | Returns the current read position of the audio stream in bytes.
SetState Method | Sets the audio state with a SpeechAudioState constant.
Write Method | Writes data to the audio stream.


SpMMAudioIn DeviceId property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpMMAudioIn

DeviceId Property

The DeviceId property gets and sets the multimedia device ID that is used by the audio object.

Syntax

Set: | SpMMAudioIn.DeviceId = Long
Get: | Long = SpMMAudioIn.DeviceId

Parts

SpMMAudioIn
The owning object.
Long
Set: A Long variable that sets the device ID.
Get: A Long variable that gets the device ID.

Example

See Speech Telephony Application Guide for examples with SpMMAudioIn.DeviceId property.


SpMMAudioIn LineId property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpMMAudioIn

LineId Property

The LineId property gets and sets the current line identifier associated with the multimedia device.

Syntax

Set: | SpMMAudioIn.LineId = Long
Get: | Long = SpMMAudioIn.LineId

Parts

SpMMAudioIn
The owning object.
Long
Set: A Long variable that sets the line ID.
Get: A Long variable that gets the line ID.


SpMMAudioIn MMHandle property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpMMAudioIn
Type: Hidden

MMHandle Property

The MMHandle property returns the handle of the multimedia audio device stream.

Syntax

Set: | Not available.
Get: | Long = SpMMAudioIn.MMHandle

Parts

SpMMAudioIn
The owning object.
Long
Set: (This property is read-only).
Get: A Long variable that gets the device handle.


SpMMAudioOut Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpMMAudioOut

The SpMMAudioOut automation object supports audio implementation for the standard Windows wave-out multimedia layer.

Automation Interfaces

The SpMMAudioOut automation object has the following elements:

Properties | Description
BufferInfo Property | Returns the audio buffer information as an ISpeechAudioBufferInfo object.
BufferNotifySize Property | Gets and sets the audio stream buffer size information.
DefaultFormat Property | Returns the default audio format as an SpAudioFormat object.
DeviceId Property | Gets and sets the multimedia device ID being used by the audio object.
EventHandle Property | Returns a Win32 event handle that applications can use to wait for status changes in the I/O stream.
Format Property | Gets and sets the cached wave format of the stream as an SpAudioFormat object.
LineId Property | Gets and sets the current line identifier associated with the multimedia device.
MMHandle Property | Returns the handle of the multimedia audio device stream.
Status Property | Returns the audio status as an ISpeechAudioStatus object.
Volume Property | Gets and sets the volume level.
Methods | Description
Read Method | Reads data from the audio stream.
Seek Method | Returns the current read position of the audio stream in bytes.
SetState Method | Sets the audio state with a SpeechAudioState constant.
Write Method | Writes data to the audio stream.


SpMMAudioOut DeviceId property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpMMAudioOut

DeviceId Property

The DeviceId property gets and sets the multimedia device ID being used by the audio object.

Syntax

Set: | SpMMAudioOut.DeviceId = Long
Get: | Long = SpMMAudioOut.DeviceId

Parts

SpMMAudioOut
The owning object.
Long
Set: A Long variable that sets the device ID.
Get: A Long variable that gets the device ID.

Example

See Speech Telephony Application Guide for examples with SpMMAudioOut.DeviceId property.


SpMMAudioOut LineId property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpMMAudioOut

LineId Property

The LineId property gets and sets the current line identifier associated with the multimedia device.

Syntax

Set: | SpMMAudioOut.LineId = Long
Get: | Long = SpMMAudioOut.LineId

Parts

SpMMAudioOut
The owning object.
Long
Set: A Long variable that sets the line ID.
Get: A Long variable that gets the line ID.


SpMMAudioOut MMHandle property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpMMAudioOut
Type: Hidden

MMHandle Property

The MMHandle property returns the handle of the multimedia audio device stream.

Syntax

Set: | Not available.
Get: | Long = SpMMAudioOut.MMHandle

Parts

SpMMAudioOut
The owning object.
Long
Set: (This property is read-only).
Get: A Long variable that gets the device handle.


SpObjectToken Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpObjectToken

The SpObjectToken automation object represents an available resource of a type used by SAPI. The default interface for this object is ISpeechObjectTokens.

The Speech configuration database contains folders representing the resources on a computer that are used by SAPI 5.1 or later speech recognition (SR) and text-to-speech (TTS). These folders are organized into resource categories, such as voices, lexicons, and audio input devices. The SpObjectTokenCategory object provides access to a category of resources, and the SpObjectToken object provides access to a single resource.

Several Speech Automation objects support methods that return collections of resources from a specific category of available resources. Examples are SpVoice.GetAudioOutputs, SpVoice.GetVoices and SpSharedRecognizer.GetProfiles, as well as the SpObjectToken object's MatchesAttributes method. Each of these operations returns an ISpeechObjectTokens object variable containing a collection of SpObjectToken objects.

The read-only Id property of an SpObjectToken object is the path to the folder of the resource with which it is associated. The read-only DataKey property is a data key object providing read and write access to this folder. An SpObjectToken created with the New keyword has an empty Id property, and is therefore not associated with a resource. Before it can be used, a new SpObjectToken must be associated with a resource by means of its SetId method.

The SpObjectToken object also provides the ability to create and access storage files associated with a resource. The paths of data storage files created by an engine or by applications for a specific resource are stored in its object token.

See the SpObjectToken Example for a complete example and additional details.

Automation Interface Elements

The SpObjectToken automation interface contains the following elements:

Properties | Description
Category Property | Returns the category of the object token as an SpObjectTokenCategory object.
DataKey Property | Returns the data key of the object token as an ISpeechDataKey object.
Id Property | Returns the ID of the token.
Methods | Description
CreateInstance Method | Creates an instance of the object represented by the token.
DisplayUI Method | Displays the specified UI.
GetAttribute Method | Returns the value of the specified attribute.
GetDescription Method | Returns the name of the resource represented by the object token.
GetStorageFileName Method | Creates a storage file for data associated with the object token.
IsUISupported Method | Determines if the specified UI is supported.
MatchesAttributes Method | Indicates whether the token matches specified attributes.
Remove Method | Removes the token from the speech configuration database.
RemoveStorageFileName Method | Removes a storage file associated with the object token.
SetId Method | Associates a new object token with a resource by setting its ID property.


SpObjectToken Category Property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectToken

Category Property

The Category property returns the category of the object token as an SpObjectTokenCategory object.

If the object token has not been initialized, an attempt to reference this property will generate an SPERR_UNINITIALIZED error.

Syntax

Set: | (This property is read-only)
Get: | SpObjectTokenCategory = SpObjectToken.Category

Parts

SpObjectToken
The owning object.
SpObjectTokenCategory
Set: (This property is read-only)
Get: An SpObjectTokenCategory object returning the category.

Example

The following Visual Basic form code demonstrates the use of the SpObjectToken's Category and Id properties and its GetDescription method. It also demonstrates the handling of uninitialized object tokens. To run this code, create a form with the following controls:

  • A list box called List1
  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object and a recognizer object. The Command1_Click procedure creates several object tokens and sends them to a subroutine which displays information about them in the list box. The first token sent is a newly-created token with no Category. The subroutine code generates an error when it tries to get the Category property of this token. The other tokens passed to the subroutine are properly initialized; for each of these tokens the subroutine displays the token's description, ID, and category ID.

Option Explicit

Const SPERR_UNINITIALIZED = &H80045001
Dim T As SpeechLib.SpObjectToken
Dim C As SpeechLib.SpObjectTokenCategory
Dim V As SpeechLib.SpVoice
Dim R As SpeechLib.SpSharedRecognizer

Private Sub Form_Load()
    On Error GoTo EH

    ' Voice object furnishes Voice and AudioOutput tokens.
    ' Recognizer object furnishes Recognizer and AudioInput tokens.
    Set V = New SpVoice
    Set R = New SpSharedRecognizer

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()
    On Error GoTo EH

    List1.Clear

    ' Create new token -- uninitialized:
    Set T = New SpObjectToken
    Call TokenInfo("new token", T)

    ' Voice object furnishes Voice and AudioOutput tokens:
    Set T = V.GetVoices().Item(0)
    Call TokenInfo("voice token", T)

    Set T = V.GetAudioOutputs().Item(0)
    Call TokenInfo("audioout token", T)

    ' Recognizer object furnishes recognizer and AudioInput tokens:
    Set T = R.GetRecognizers().Item(0)
    Call TokenInfo("recognizer token", T)

    Set T = R.GetAudioInputs().Item(0)
    Call TokenInfo("audioin token", T)

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub TokenInfo(text, token As SpObjectToken)
    On Error GoTo TokenInfo

    List1.AddItem text
    Set C = token.Category

TokenInfo:
    Select Case Err.Number
        Case 0
            List1.AddItem "  Token.GetDescription:"
            List1.AddItem "    " & token.GetDescription
            List1.AddItem "  Token.Category.Id:"
            List1.AddItem "    " & token.Category.Id
            List1.AddItem "  Token.Id:"
            List1.AddItem "    " & token.Id

        Case SPERR_UNINITIALIZED
            List1.AddItem "   SPERR_UNINITIALIZED"
    End Select

    List1.AddItem ""

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpObjectToken CreateInstance method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectToken

CreateInstance Method

The CreateInstance method creates an instance of the object represented by the token.

SpObjectToken.CreateInstance(
     [pUnkOuter As IUnknown = Nothing],
     [ClsContext As SpeechTokenContext = STCALL]
) As IUnknown

Parameters

pUnkOuter
[Optional] Specifies the pUnkOuter. By default, the Nothing value is used.
ClsContext
[Optional] Specifies the ClsContext. By default STCALL is used.

Return Value

An IUnknown object, representing the object instantiated.

Example

For an example of the use of the CreateInstance method, see the code example in the SpAudioFormat Type section.


SpObjectToken DataKey Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpObjectToken
Type: Hidden

DataKey Property

The DataKey property returns the data key of the object token as an ISpeechDataKey object.

A data key object provides read and write access to the contents of a particular folder in the Speech configuration database. The data key of an object token accesses the folder referenced by its Id property.

Syntax

Set: | (This property is read-only)
Get: | ISpeechDataKey = SpObjectToken.DataKey

Parts

SpObjectToken
The owning object.
ISpeechDataKey
Set: (This property is read-only)
Get: An ISpeechDataKey object returning the data key.

Example

Use of the RemoveStorageFileName method is demonstrated in the code example for the GetStorageFileName method.


SpObjectToken DisplayUI Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectToken
Type: Hidden

DisplayUI Method

The DisplayUI method displays the specified UI.

SpObjectToken.DisplayUI(
     hWnd As Long,
     Title As String,
     TypeOfUI As String,
     [ExtraData As Variant = Nothing],
     [Object As IUnknown = Nothing]
)

Parameters

hWnd
Specifies the hWnd.
Title
Specifies the Title.
TypeOfUI
Specifies the TypeOfUI.
ExtraData
[Optional] Specifies the ExtraData. By default, the Nothing value is used.
Object
[Optional] Specifies the Object. By default, the Nothing value is used.

Return Value

None.

Example

For an example of the use of the DisplayUI method, see the example in the Recognizer DisplayUI section.


SpObjectToken GetAttribute Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectToken

GetAttribute Method

The GetAttribute method returns the value of the specified attribute.

The String returned contains the value for the Attribute. If the Attribute is present but does not contain additional information, the String will be Empty. If the Attribute is not present, SPERR_NOT_FOUND is returned. Not all engines support all attributes and it is possible to customize attributes for each engine.

SpObjectToken.GetAttribute(
     AttributeName As String
) As String

Parameters

AttributeName
Specifies the AttributeName.

Return Value

The GetAttribute method returns a String variable.

Remarks

In Visual Basic, attempting to access a nonexistent Attribute will cause a run-time error. Therefore, it is recommended to include an On Error statement trapping such cases.

Example

This code example demonstrates the GetAttribute method. After creating an instance of a recognizer, the Recognizer property retrieves an SpObjectToken object whose GetAttribute method is called. The engine ID is displayed. Also two attributes are attempted to be displayed. The first is "VendorPreferred", an attribute that exists for the SAPI 5 SR engine. The other is "MyEngineAttribute", which should not be present. Attributes not found will cause a run-time error and as a result, require error handling code.

To run this code, create a form with no controls. Paste this code into the Declarations section of the form.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Const NL = vbNewLine
    Dim objectToken As SpObjectToken
    Dim RC As SpSharedRecoContext
    Dim T As String
    Dim TokenName As String
    Dim Value As String

    Set RC = New SpSharedRecoContext
    Set objectToken = RC.Recognizer.Recognizer

    T = "Id: " & RC.Recognizer.Recognizer.Id & NL
    TokenName = "VendorPreferred"
    Value = objectToken.GetAttribute(TokenName)

    If Len(Value) = 0 Then
        T = T & TokenName & " attribute's value: Zero-length string" & NL
    End If

    TokenName = "MyEngineAttribute"
    On Error Resume Next
    T = TokenName & " : " & objectToken.GetAttribute(TokenName)

    If Err.Number Then
        Err.Clear
        T = T & "There is no attribute named 'MyEngineAttribute'."
    End If

    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpObjectToken GetDescription Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectToken

GetDescription Method

The GetDescription method returns the name of the resource represented by the object token.

SpObjectToken.GetDescription(
     [Locale As Long = 0]
) As String

Parameters

Locale
[Optional] Specifies the Locale. By default, zero is used.

Return Value

The GetDescription method returns a String variable.

Example

Use of the GetDescription method is demonstrated in the code example in the Category section.


SpObjectToken GetStorageFileName method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectToken
Type: Hidden

GetStorageFileName Method

The GetStorageFileName method creates a storage file for data associated with the object token.

SpObjectToken.GetStorageFileName(
     ObjectStorageCLSID As String,
     KeyName As String,
     FileName As String,
     Folder As SpeechTokenShellFolder
) As String

Parameters

ObjectStorageCLSID
Globally unique identifier (GUID) of the calling object. The method searches the registry for an entry key name of ObjectStorageCLSID, and then a corresponding Files subkey. If the registry entry is not present, one is created.
KeyName
The name of the attribute file for the registry entry of clsidCaller. This attribute stores the location of the resource file.
FileName
A specifier that is either "" or a path/file name for storage file.
  • If this starts with "X:\" or "\\" it is assumed to be a full path; otherwise it is assumed to be relative to special folders given in the nFolder parameter.
  • If it ends with a "\", or is NULL, a unique file name will be created. The file name will be something like: "SP_7454901D23334AAF87707147726EC235.dat". "SP_" and ".dat" are the default prefix name and file extension name. The numbers in between are generated guid number to make sure the file name is unique.
  • If the name contains a %d the %d is replaced by a number to give a unique file name. The default file extension is .dat, the user can specify anything else. Intermediate directories are created.
  • If a relative file is used, the value stored in the registry includes the nFolder value as %nFolder% before the rest of the path.
Folder
One or more SpeechTokenShellFolder constants specifying the Folder.

Return Value

A String variable containing the path of the storage file.

Example

The following Visual Basic form code demonstrates the GetStorageFileName and RemoveStorageFileName methods. To run this code, create a form with no controls and paste the code into the Declarations section of the form.

The operations performed in this example can best be viewed with REGEDIT.EXE. For a discussion of Registry issues, please see the ISpeechDataKey interface.

The Example code does the following:

  • Creates a new SpObjectToken object and sets its ID property to a new subfolder called Demo within the Voices\Tokens folder. The True parameter of the SetId call forces the creation of this folder, if it does not already exist.
  • Creates a data key object that references the new Demo folder and uses the data key to write a value into the folder.
  • Calls the GetStorageFileName method. After this call, the Demo folder contains a subfolder called {CDD1141B-82FB-405c-99BE-69A793A92D87}. This is the CLSID used as a parameter of the GetStorageFileName method. Within this is a folder called Files, which contains the storage file path in a value called Demo.
  • Calls the RemoveStorageFileName method to delete the storage file and remove the Demo value from the Files folder.
  • Uses the ISpeechDataKey.Remove method to delete the {CDD1141B-82FB-405c-99BE-69A793A92D87} folder and Demo folders.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Dim C As SpeechLib.SpObjectTokenCategory
    Dim ID As String
    Dim K As SpeechLib.ISpeechDataKey           '
    Dim SF As String
    Dim T As SpeechLib.SpObjectToken
    Dim TestCLSID As String

    TestCLSID = "{CDD1141B-82FB-405c-99BE-69A793A92D87}"

    ' Create new category object, set it to Voices category:
    Set C = New SpObjectTokenCategory
    C.SetId SpeechCategoryVoices

    ' Create new token object, and set its ID
    ' to the path of a folder which does not exist
    ' ("True" parameter creates the folder):
    Set T = New SpObjectToken
    ID = SpeechCategoryVoices & "\Tokens\Demo"
    T.SetId ID, , True

    ' Set data key object to demo voice's
    ' folder and write a CLSID value:
    Set K = T.DataKey
    K.SetStringValue "CLSID", TestCLSID

    ' Create storage file for token.
    SF = T.GetStorageFileName(TestCLSID, "Demo", _
        vbNullString, STSF_FlagCreate + STSF_AppData)
    MsgBox SF, vbInformation

    ' Remove storage file.
    Call T.RemoveStorageFileName(TestCLSID, "Demo", True)

    ' Remove "{CDD1141B-82FB-405c-99BE-69A793A92D87}"
    ' folder and "Demo" folder
    T.Remove TestCLSID
    T.Remove ""

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpObjectToken Id Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpObjectToken

Id Property

The Id property returns the ID of the token.

The ID of the object is the path to its folder within the Speech configuration database.

Syntax

Set: | (This property is read-only)
Get: | String = SpObjectToken.Id

Parts

SpObjectToken
The owning object.
String
Set: (This property is read-only)
Get: A String variable returning the ID.

Example

Use of the Id property is demonstrated in a code example in the Category section.


SpObjectToken IsUISupported Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectToken
Type: Hidden

IsUISupported Method

The IsUISupported method determines if the specified UI is supported.

SpObjectToken.IsUISupported(
     TypeOfUI As String,
     [ExtraData As Variant = Nothing],
     [Object As IUnknown = Nothing]
) As Boolean

Parameters

TypeOfUI
Specifies the TypeOfUI.
ExtraData
[Optional] Specifies the ExtraData. By default, the Nothing value is used.
Object
[Optional] Specifies the Object. By default, the Nothing value is used.

Return Value

The IsUISupported method returns a Boolean variable. If True, the specified UI is supported; if False, it is not supported.

Example

For an example of the use of the IsUISupported method, see the example in the Recognizer IsUISupported section.


SpObjectToken MatchesAttributes Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectToken

MatchesAttributes Method

The MatchesAttributes method indicates whether the token matches specified attributes.

SpObjectToken.MatchesAttributes(
     Attributes As String
) As Boolean

Parameters

Attributes
Specifies the Attributes.

Return Value

A Boolean variable. If True, the token matches the specified attributes; if False, it does not match.

Example

The following Visual Basic form code demonstrates the use of the MatchesAttibutes method. To run this code, create a form with the following controls:

  • A combo box control called Combo1
  • A command button called Command1
  • A list box called List1

Paste this code into the Declarations section of the form.

The Form_Load procedure initializes a new SpObjectTokenCategory object to the voices category, selects all voices into an ISpeechObjectTokens collection, and loads Combo1 with several attribute declarations. These attributes are intentionally irregular with regard to capitalization, spacing, and spelling.

The Command1 procedure contains a loop that performs a MatchesAttibutes call on each available voice. The name of each voice and the Boolean result of the MatchesAttibutes method is displayed in the list box.

Option Explicit

Dim C As SpeechLib.SpObjectTokenCategory
Dim E As SpeechLib.ISpeechObjectTokens
Dim T As SpeechLib.SpObjectToken

Private Sub Form_Load()
    On Error GoTo EH

    With Combo1
        .AddItem "vendor=microsoft"
        .AddItem "gender=female"
        .AddItem "Gender = Male"
        .AddItem "gender!=male"
        .AddItem "name=Microsoft sam"
        .AddItem "Name != microsoft Sam"
        .AddItem "name=MICROSOFT SAM,gender=female"   'no possible matches
        .AddItem "gedner = male"          'no possible matches
        .ListIndex = 0
    End With

    Set C = New SpObjectTokenCategory   'create new token category object
    C.SetId SpeechCategoryVoices        'init ID of voices category
    Set E = C.EnumerateTokens()         'no parameters -- get all voices

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()
    On Error GoTo EH

    Dim Vname, Vmatch

    List1.Clear
    List1.AddItem "Test for voices matching """ & Combo1.Text & """"
    List1.AddItem ""

    For Each T In E
        Vname = T.GetDescription
        Vmatch = T.MatchesAttributes(Combo1.Text)
        List1.AddItem "   " & Vname & "  " & Vmatch
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpObjectToken Remove Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectToken
Type: Hidden

Remove Method

The Remove method removes the token from the speech configuration database.

SpObjectToken.Remove(
     ObjectStorageCLSID As String
)

Parameters

ObjectStorageCLSID
Specifies the CLSID associated with the object token to remove. If ObjectStorageCLSID is an empty string ("") or vbNullString, the entire token is removed; otherwise, only the specified section is removed.

Return Value

None.

Example

Use of the RemoveStorageFileName method is demonstrated in the code example for the GetStorageFileName method.


SpObjectToken RemoveStorageFileName method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectToken
Type: Hidden

RemoveStorageFileName Method

The RemoveStorageFileName method removes a storage file associated with the object token.

SpObjectToken.RemoveStorageFileName(
     ObjectStorageCLSID As String,
     KeyName As String,
     DeleteFile As Boolean
)

Parameters

ObjectStorageCLSID
The globally unique identifier (GUID) of the calling object.
KeyName
The KeyName.
DeleteFile
If True, the storage file will be deleted after removal.

Return Value

None.

Example

Use of the RemoveStorageFileName method is demonstrated in the code example for the GetStorageFileName method.


SpObjectToken SetId Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectToken
Type: Hidden

SetId Method

The SetId method associates a new object token with a resource by setting its ID property.

The ID of an SpObjectToken object is the path to its folder within the Speech configuration database.

The Id property of an SpObjectToken can be set once. Subsequent SetId calls will return the error message, SPERR_ALREADY_INITIALIZED. Attempting to use an SpObjectToken object before setting its Id property will return SPERR_UNINITIALIZED.

SpObjectToken.SetId(
     Id As String,
     [CategoryID As String],
     [CreateIfNotExist As Boolean = False]
)

Parameters

Id
The ID of the token.
CategoryID
[Optional] The category ID of the token. By default the value is the empty string value of "".
CreateIfNotExist
[Optional] Specifies creating the token. If True, the folder is created if one does not already exist. By default the value is False, and no folder is created.

Return Value

None.

Example

Use of the RemoveStorageFileName method is demonstrated in the code example for the GetStorageFileName method.


SpObjectToken Example (Microsoft Speech Platform)

 Microsoft Speech Platform

SpObjectToken Example

The following code example demonstrates the use of the Count property and the Item method. The example works for all objects returned as the collection ISpeechObjectTokens. The Count property returns the number of items in the collection. The Item method returns an individual member at the given index.

To run this code, create a form with no controls and paste this code into the Declarations section of the form.

Note The Item method and Count property behave the same way for all collections in the SAPI Automation object library that have them as members.

Option Explicit

Private Sub Form_Load()
    On Error GoTo EH

    Dim theResources As ISpeechObjectTokens
    Dim SharedRecognizer As SpSharedRecognizer

    Set SharedRecognizer = New SpSharedRecognizer
    Set theResources = SharedRecognizer.GetRecognizers
    Call DisplayItems(theResources)

    Set theResources = SharedRecognizer.GetAudioInputs
    Call DisplayItems(theResources)

    Set theResources = SharedRecognizer.GetProfiles
    Call DisplayItems(theResources)

EH:
    If Err.Number Then ShowErrMsg
End Sub

Sub DisplayItems(ByRef Resources As ISpeechObjectTokens)
    On Error GoTo EH

    Dim i As Long
    Dim recoObject As SpObjectToken
    Dim T As String

    For i = 0 To Resources.Count - 1
        Set recoObject = Resources.Item(i)
        T = T & recoObject.GetDescription & vbCrLf
    Next i

    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpObjectTokenCategory Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpObjectTokenCategory

The SpObjectTokenCategory automation object represents a class of object tokens. Object tokens are associated with specific folders in the Speech configuration database, and these folders are organized into categories, such as Recognizers, AudioInputs and Voices. An SpObjectTokenCategory object represents a single category of object tokens, and provides access to all the tokens within that category.

Applications can derive the category of an initialized SpObjectToken object from its Category property, or they can create a new SpObjectTokenCategory object and use the SetId method to associate it with a particular category.

Automation Interface Elements

The SpObjectTokenCategory automation object has the following elements:

Properties | Description
Default Property | Gets and sets the ID of the default token in the category.
Id Property | Returns the name of the object token category.
Methods | Description
EnumerateTokens Method | Returns a selection of SpObjectToken objects.
GetDataKey Method | Returns the data key of the category in the speech configuration database.
SetId Method | Sets the ID of the category.


SpObjectTokenCategory Default Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpObjectTokenCategory

Default Property

The Default property gets and sets the ID of the default token in the category.

The ID of the object is the path to its folder within the Speech configuration database.

Each category of object tokens has a default token, which represents the default resource of that category. The Default property of the voice category, for example, is the ID of the default system voice.

Syntax

Set: | SpObjectTokenCategory.Default = String
Get: | String = SpObjectTokenCategory.Default

Parts

SpObjectTokenCategory
The owning object.
const
Set: A String variable that sets the property.
Get: A String variable that gets the property.

Example

Please see the code example for the SetId method. This code creates a new SpObjectTokenCategory object and associates it with the category of voices. The Default property then returns the ID of the default system voice.


SpObjectTokenCategory EnumerateTokens Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectTokenCategory

EnumerateTokens Method

The EnumerateTokens method returns a selection of SpObjectToken objects.

Selection criteria may be applied optionally.

SpObjectTokenCategory.EnumerateTokens(
     [RequiredAttributes As String = ""],
     [OptionalAttributes As String = ""]
) As ISpeechObjectTokens

Parameters

RequiredAttributes
[Optional] Specifies the RequiredAttributes. To be returned by EnumerateTokens, the searched tokens must contain all of the specific required attributes. If no profiles match the selection, the selection returned will not contain any elements. By default no attributes are required and so returns all the tokens discovered.
OptionalAttributes
[Optional] Specifies the OptionalAttributes. Returned tokens containing the RequiredAttributes are sorted by OptionalAttributes. If OptionalAttributes is specified, the tokens are listed with the OptionalAttributes first. By default no attribute is specified so the list returned is in the order discovered from the speech configuration database.

Return Value

The EnumerateTokens method returns an ISpeechObjectTokens variable.

Example

The following Visual Basic form code demonstrates a simple use of the EnumerateTokens method. To run this code, create a form with the following controls:

  • A list box called List1
  • Two command buttons called Command1 and Command2

Paste this code into the Declarations section of the form.

The Command1 procedure creates an SpVoice object and uses the voice's GetVoices method to get an ISpeechObjectTokens collection containing an object token for each voice on the computer. A For Each loop lists each voice token's Description property in the list box.

The Command2 procedure creates a new SpObjectTokenCategory object, uses the SetId method to associate it with the category of voices, and the EnumerateTokens method to get an ISpeechObjectTokens collection containing an object token for each voice on the computer. A For Each loop lists each voice token's Description property in the list box.

The list of voices displayed by the two command buttons will be identical.

Option Explicit

Dim V As SpeechLib.SpVoice                  'voice object
Dim T As SpeechLib.SpObjectToken            'object token
Dim E As SpeechLib.ISpeechObjectTokens      'an enumeration of object tokens
Dim C As SpeechLib.SpObjectTokenCategory    'a category of object tokens

Private Sub Command1_Click()
    On Error GoTo EH

    List1.Clear
    List1.AddItem "Enumerate voices with SpVoice.GetVoices"
    List1.AddItem ""

    Set V = New SpVoice                 'create new voice
    Set E = V.GetVoices()               'no parameters -- get all voices

    For Each T In E
        List1.AddItem "   " & T.GetDescription
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH
    List1.Clear
    List1.AddItem "Enumerate voices with SpObjectToken.EnumerateTokens"
    List1.AddItem ""

    Set C = New SpObjectTokenCategory   'create new token category object
    C.SetId SpeechCategoryVoices        'init ID of voices category
    Set E = C.EnumerateTokens()         'no parameters -- get all voices

    For Each T In E
        List1.AddItem "   " & T.GetDescription
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpObjectTokenCategory GetDataKey Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectTokenCategory
Type: Hidden

GetDataKey Method

The GetDataKey method returns the data key of the SpObjectTokenCategory object.

A data key object provides read and write access to the contents of a particular folder in the Speech configuration database. The data key of an SpObjectTokenCategory object accesses the folder referenced by its Id property.

SpObjectTokenCategory.GetDataKey(
     [Location As SpeechDataKeyLocation = SDKLDefaultLocation]
) As ISpeechDataKey

Parameters

Location
[Optional] Specifies the location in the speech configuration database. Default value is SDKLDefaultLocation.

Return Value

An ISpeechDataKey object.

Example

The following Visual Basic form code demonstrates the use of the GetDataKey method to enumerate the list of voices in the voices category. To run this code, create a form with the following controls:

  • A list box called List1
  • A command button called Command1

Paste this code into the Declarations section of the form.

The Command1 procedure creates a new SpObjectTokenCategory object and uses the SetId method to associate the object with the category of voices. It retrieves the data keys of the category and of the category's Tokens subfolder. It then uses the data key object's EnumKeys method to enumerate the tokens in the Tokens subfolder. The results displayed in the list will be identical to the lists of voices displayed by the code sample in the EnumerateTokens method.

Option Explicit

Dim C As SpeechLib.SpObjectTokenCategory    'a category of object tokens
Dim K As SpeechLib.ISpeechDataKey           'data key object
Dim E As String                             'gets names of subkeys
Dim ii As Integer

Private Sub Command1_Click()
    On Error GoTo EH

    List1.Clear
    List1.AddItem "Enumerate voice tokens with SpObjectTokenCategory.GetDataKey"
    List1.AddItem ""

    Set C = New SpObjectTokenCategory   'create new token category object
    C.SetId SpeechCategoryVoices        'init with ID of voices category

    Set K = C.GetDataKey                'set to key of voice category object
    Set K = K.OpenKey("Tokens")         'reset to key of its "Tokens" subfolder

    On Error Resume Next
    For ii = 0 To 9999                  'enumerate subkeys within "Tokens" subkey
        E = K.EnumKeys(ii)              'next subkey
        If Err.Number Then Exit For     'this will be used!
        List1.AddItem "   " & E
    Next
    Err.Clear

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpObjectTokenCategory Id Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpObjectTokenCategory

Id Property

The Id property returns the ID of the object token category.

The ID of the object is the path to its folder within the Speech configuration database.

Syntax

Set: | (This property is read-only)
Get: | String = SpObjectTokenCategory.Id

Parts

SpObjectTokenCategory
The owning object.
String
Set: (This property is read-only)
Get: A String variable that gets the property.

Example

Please see the code example for the SetId method. This code creates a new SpObjectTokenCategory object and associates it with the category of voices. The Id property then returns the ID of the voices category.


SpObjectTokenCategory SetId Method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpObjectTokenCategory

SetId Method

The SetId method sets the ID of the SpObjectTokenCategory object.

The ID of the object is the path to its folder within the Speech configuration database.

An SpObjectTokenCategory object is created with its Id property in an uninitialized state; attempting to reference the Id of a new SpObjectTokenCategory object will result in an SPERR_UNINITIALIZED error. An SpObjectTokenCategory object in this state is not associated with any of the seven SAPI object token categories.

The SpeechStringConstants module contains constants that specify the paths of SAPI's object token categories within the configuration database. The SetId method typically sets one of those constants as the category object's Id property. This has the effect of setting the object to one of the SAPI object token categories.

This table shows the SpeechStringConstants constant for each of the seven object token categories:

Object Token Category | SpeechStringConstants member
Voices | SpeechCategoryVoices
Recognizers | SpeechCategoryRecognizers
AppLexicons | SpeechCategoryAppLexicons
AudioInput | SpeechCategoryAudioIn
AudioOutput | SpeechCategoryAudioOut
PhoneConverters | SpeechCategoryPhoneConverters
Recoprofiles | SpeechCategoryRecoProfiles

SpObjectTokenCategory.SetId(
     Id As String,
     [CreateIfNotExist As Boolean = False]
)

Parameters

Id
Specifies the Id, usually with a member of SpeechStringConstants.
CreateIfNotExist
[Optional] Specifies creating the token. If True, an entry is created if one does not already exist. By default the value is False and no file is created.

Return Value

None.

Example

The following Visual Basic form code demonstrates the use of the SetId method. To run this code, create a form with the following controls:

  • A list box called List1
  • A command button called Command1

Paste this code into the Declarations section of the form.

The Command1 procedure creates a new SpObjectTokenCategory object, generates an error by attempting to reference the Id property of the uninitialized object, and then performs a SetId call which assigns the object to the category of TTS voices. The code then displays the token category's default token, which is the default TTS voice, and finally demonstrates the error which occurs from attempting to perform a second SetId on the SpObjectTokenCategory object.

Option Explicit

Dim C As SpeechLib.SpObjectTokenCategory

Const SPERR_UNINITIALIZED = &H80045001
Const SPERR_ALREADY_INITIALIZED = &H80045002

Private Sub Command1_Click()
    On Error Resume Next

    'Uninitialized object
    List1.AddItem "New SpObjectTokenCategory object:"
    Set C = New SpObjectTokenCategory
    If Err = 0 Then
        List1.AddItem "   SUCCEEDED"
    End If

    'Show the Id of a new object
    List1.AddItem "Id of New SpObjectTokenCategory object:"
    List1.AddItem C.Id
    If Err.Number = SPERR_UNINITIALIZED Then
        List1.AddItem "   SPERR_UNINITIALIZED"
        Err.Clear
    End If

    'Show the SpeechCategoryVoices constant
    List1.AddItem "SpeechCategoryVoices constant:"
    List1.AddItem "   " & SpeechCategoryVoices

    'Perform the SetId, which assigns it to the Voices category
    List1.AddItem "Perform SetId on New SpObjectTokenCategory object:"
    C.SetId SpeechCategoryVoices
    List1.AddItem "   " & C.Id

    'Show the default item of the new category
    List1.AddItem "Show SpObjectTokenCategory's default item:"
    List1.AddItem "   " & C.Default

    'Show error on second SetId
    List1.AddItem "Try a second SetId on SpObjectTokenCategory object:"
    C.SetId SpeechCategoryRecognizers
    If Err.Number = SPERR_ALREADY_INITIALIZED Then
        List1.AddItem "   SPERR_ALREADY_INITIALIZED"
        Err.Clear
    End If

End Sub


SpPhoneConverter Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpPhoneConverter

The SpPhoneConverter automation object supports conversion between phoneme symbols and phoneme IDs.

Each language supported by SAPI uses a set of phonemes which represent all the meaningful sounds in that language. Each phoneme has a symbolic representation of its sound, and a numeric ID; in most languages, phoneme IDs are assigned sequentially. Please see the American English Phoneme Representation page for further details.

The following table shows a few English words transcribed into phoneme symbols and phoneme ID's.

Words | Phoneme Symbols | Phoneme IDs
one | w, ah, n | 46, 12, 33
two | t, uw | 41, 44
three | th, r, iy | 42, 38, 28
four | f, ao, r | 24, 13, 38
five | f, ay, v | 24, 16, 45
six | s, ih, k, s | 39, 27, 30, 39

Automation Interface Elements

The SpPhoneConverter automation object has the following elements:

Properties | Description
LanguageId Property | Gets and sets the language id of the converter.
Methods | Description
IdToPhone Method | Converts an array of phoneme IDs to a string of phoneme symbols.
PhoneToId Method | Converts a string of phoneme symbols to an array of phoneme IDs.


SpPhoneConverter IdToPhone method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpPhoneConverter

IdToPhone Method

The IdToPhone method converts an array of phoneme IDs to a string of phoneme symbols.

If the IdToPhone method is called before setting the SpPhoneConverter's LanguageId property, an SPERR_UNINITIALIZED error will occur.

SpPhoneConverter.IdToPhone(
     IdArray As Variant
) As String

Parameters

IdArray
An array of phoneme IDs or a single phoneme ID.

Return Value

A String variable.

Example

The following Visual Basic form code demonstrates the use of the IdToPhone. The application assigns values to an array and then displays the resulting phoneme string.

To run this code, create a form with no controls. Paste this code into the Declarations section of the form.

Option Explicit

Dim objPhoneConverter As New SpPhoneConverter

Private Sub Form_Load()
    On Error GoTo EH

    Dim T As String

    ' US English.
    objPhoneConverter.LanguageId = 1033

    ' Get the phoneme symbols of the phoneme id 1.
    objPhoneConverter.IdToPhone (1)

    Dim ids(2) As Integer
    ids(0) = 1
    ids(1) = 2
    ids(2) = 3

    ' Get a string of phoneme symbols for the
    ' specified phoneme ids, separated by space.
    T = """" & objPhoneConverter.IdToPhone(ids) & """"
    MsgBox T, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpPhoneConverter LanguageId property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpPhoneConverter

LanguageId Property

The LanguageId property gets and sets the language ID of the converter.

Syntax

Set: | SpPhoneConverter.LanguageId = Long
Get: | Long = SpPhoneConverter.LanguageId

Parts

SpPhoneConverter
The owning object.
SpeechLanguageId
Set: A Long variable that sets the language ID.
Get: A Long variable that gets the language ID.


SpPhoneConverter PhoneToId method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpPhoneConverter

PhoneToId Method

The PhoneToId method converts a string of phoneme symbols to an array of phoneme IDs.

If the PhoneToId method is called before setting the SpPhoneConverter's LanguageId property, an SPERR_UNINITIALIZED error will occur.

SpPhoneConverter.PhoneToId(
     Phonemes As String
) As Variant

Parameters

Phonemes
A string of phoneme symbols.

Return Value

A Variant array.


SpPhraseInfoBuilder Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpPhraseInfoBuilder

The SpPhraseInfoBuilder automation object provides the ability to rebuild phrase information from audio data saved to memory.

Automation Interface Elements

The SpPhraseInfoBuilder automation object has the following element:

Methods | Description
RestorePhraseFromMemory Method | Recreates phrase information from a phrase that has been saved to memory.


SpPhraseInfoBuilder RestorePhraseFromMemory method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpPhraseInfoBuilder

RestorePhraseFromMemory Method

The RestorePhraseFromMemory method recreates phrase information from a phrase that has been saved to memory.

The ISpeechPhraseInfo.SaveToMemory method saves phrase information as a Variant variable. RestorePhraseFromMemory method uses this variable to recreate an object based on ISpeechPhraseInfo.

SpPhraseInfoBuilder.RestorePhraseFromMemory(
     PhraseInMemory As Variant
) As ISpeechPhraseInfo

Parameters

PhraseInMemory
A Variant variable containing a phrase saved to memory.

Return Value

A ISpeechPhraseInfo object returning the phrase information.

Example

The following Visual Basic form code demonstrates storing and retrieving the phrase portion of a recognition result.

To run this code, paste it into the Declarations section of a form that contains no controls. In addition to the usual reference to the Microsoft Speech Object Library, this code also needs a reference to the simpleaudio 1.0 Type Library.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition:
    Set RecoContext = Recognizer.CreateRecoContext
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Const NL = vbNewLine
    Dim PhraseBuilder As Object
    Dim PhraseInfo As ISpeechPhraseInfo
    Dim thePhrase As Variant
    Dim T As String

    On Error GoTo EH

    ' Store the phrase first.
    thePhrase = Result.PhraseInfo.SaveToMemory

    ' Retrieve the phrase from memory and display it:
    Set PhraseBuilder = CreateObject("SAPI.SpPhraseInfoBuilder")
    Set PhraseInfo = PhraseBuilder.RestorePhraseFromMemory(thePhrase)
    MsgBox PhraseInfo.GetText, vbInformation

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpTextSelectionInformation Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpTextSelectionInformation

The SpTextSelectionInformation automation object provides access to the text selection information pertaining to a word sequence buffer.

For an example of the use of the SpTextSelectionInformation object, see the SetWordSequenceData section of the ISpeechRecoGrammar interface.

Automation Interface Elements

The SpTextSelectionInformation automation object has the following elements:

Properties | Description
ActiveLength Property | Gets and sets the count of characters for the active range of the text selection buffer.
ActiveOffset Property | Gets and sets the offset of the active text selection buffer from the beginning of the word sequence data buffer.
SelectionLength Property | Gets and sets the count of characters in the selected text within the word sequence data buffer.
SelectionOffset Property | Gets and sets the offset of the selected text within the word sequence buffer.


SpTextSelectionInformation ActiveLength Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpTextSelectionInformation

ActiveLength Property

The ActiveLength property gets and sets the count of characters for the active range of the text selection buffer.

Syntax

Set: | SpTextSelectionInformation.ActiveLength = Long
Get: | Long = SpTextSelectionInformation.ActiveLength

Parts

SpTextSelectionInformation
The owning object.
Long
Set: A Long variable that sets the property.
Get: A Long variable that gets the property.

Example

For an example of the use of the ActiveLength property, see the ISpeechRecoGrammar.SetWordSequenceData section.


SpTextSelectionInformation ActiveOffset Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpTextSelectionInformation

ActiveOffset Property

The ActiveOffset property gets and sets the offset of the active text selection buffer from the beginning of the WordSequenceData buffer.

Syntax

Set: | SpTextSelectionInformation.ActiveOffset = Long
Get: | Long = SpTextSelectionInformation.ActiveOffset

Parts

SpTextSelectionInformation
The owning object.
Long
Set: A Long variable that sets the property.
Get: A Long variable that gets the property.

Example

For an example of the use of the ActiveOffset property, see the ISpeechRecoGrammar.SetWordSequenceData section.


SpTextSelectionInformation SelectionLength Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpTextSelectionInformation

SelectionLength Property

The SelectionLength property gets and sets the count of characters in the selected text within the word sequence data buffer.

Syntax

Set: | SpTextSelectionInformation.SelectionLength = Long
Get: | Long = SpTextSelectionInformation.SelectionLength

Parts

SpTextSelectionInformation
The owning object.
Long
Set: A Long variable that sets the property.
Get: A Long variable that gets the property.

Example

For an example of the use of the SelectionLength property, see the ISpeechRecoGrammar.SetWordSequenceData section.


SpTextSelectionInformation SelectionOffset Property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpTextSelectionInformation

SelectionOffset Property

The SelectionOffset property gets and sets the offset of the selected text within the word sequence buffer.

Syntax

Set: | SpTextSelectionInformation.SelectionOffset = Long
Get: | Long = SpTextSelectionInformation.SelectionOffset

Parts

SpTextSelectionInformation
The owning object.
Long
Set: A Long variable that sets the property.
Get: A Long variable that gets the property.

Example

For an example of the use of the SelectionOffset property, see the ISpeechRecoGrammar.SetWordSequenceData section.


SpUnCompressedLexicon Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpUnCompressedLexicon

The SpUnCompressedLexicon automation object provides access to lexicons, which contain information about words that can be recognized or spoken.

The SpUnCompressedLexicon object represents a single application lexicon.

Automation Interfaces

The SpUnCompressedLexicon automation object contains the following elements:

Properties | Description
GenerationId Property | Gets the generation ID of the current application lexicon.
Methods | Description
AddPronunciation Method | Adds a pronunciation, specified in phone symbols, to the current application lexicon.
AddPronunciationByPhoneIds Method | Adds a pronunciation, specified in phone IDs, to the current application lexicon.
GetGenerationChange Method | Gets a list of words in the current application lexicon that have changed since the specified generation.
GetPronunciations Method | Gets the pronunciations and parts of speech for a word from the user or application lexicons.
GetWords Method | Gets a list of all words in the user or application lexicons.
RemovePronunciation Method | Removes a word and/or its pronunciations, specified in phone symbols, from the current application lexicon.
RemovePronunciationByPhoneIds Method | Removes a word and/or its pronunciations, specified in phone IDs, from the current application lexicon.


SpUnCompressedLexicon AddPronunciation method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpUnCompressedLexicon

AddPronunciation Method

The AddPronunciation method adds a pronunciation, specified in phonemes, to the application lexicon.

SpUnCompressedLexicon.AddPronunciation(
     bstrWord As String,
     LangId As Long,
     [PartOfSpeech As SpeechPartOfSpeech = SPSUnknown],
     [bstrPronunciation As String]
)

Parameters

bstrWord
The word to add.
LangId
The language ID of the lexicon word.
PartOfSpeech
[Optional] Specifies the PartOfSpeech. Default value is SPSUnknown.
bstrPronunciation
[Optional] The pronunciation, in phonemes.

Return Value

None.


SpUnCompressedLexicon AddPronunciationByPhoneIds method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpUnCompressedLexicon
Type: Hidden

AddPronunciationByPhoneIds Method

The AddPronunciationByPhoneIds method adds a pronunciation, specified in phone ids, to the application lexicon.

SpUnCompressedLexicon.AddPronunciationByPhoneIds(
     bstrWord As String,
     LangId As Long,
     [PartOfSpeech As SpeechPartOfSpeech = SPSUnknown],
     [PhoneIds As Variant]
)

Parameters

bstrWord
The word to add.
LangId
The language Id of the word.
PartOfSpeech
[Optional] The PartOfSpeech. Default value is SPSUnknown.
PhoneIds
[Optional] The pronunciation, in phone ids.

Return Value

None.


SpUnCompressedLexicon GenerationId property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpUnCompressedLexicon
Type: Hidden

GenerationId Property

The GenerationId property gets the generation ID of the current application lexicon.

The GenerationId function acts as a version number, making it possible to roll back, cancel or undo additions to the lexicon.

Syntax

Set: | Not available.
Get: | Long = SpUnCompressedLexicon.GenerationId

Parts

SpUnCompressedLexicon
The owning object.
Long
Set: (This property is read-only).
Get: A Long variable returning the generation ID.


SpUnCompressedLexicon GetGenerationChange method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpUnCompressedLexicon
Type: Hidden

GetGenerationChange Method

The GetGenerationChange method gets a list of words in the current application lexicon that have changed since the specified generation.

SpUnCompressedLexicon.GetGenerationChange(
     GenerationID As Long
) As ISpeechLexiconWords

Parameters

GenerationId
Specifies the GenerationId.

Return Value

The GetGenerationChange method returns an ISpeechLexiconWords object.


SpUnCompressedLexicon GetPronunciations method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpUnCompressedLexicon

GetPronunciations Method

The GetPronunciations method gets the pronunciations and parts of speech for a word in the user or application lexicons.

An ISpeechLexiconPronunciation object contains a word's pronunciations, part of speech and phone IDs. Because a word may have more than one pronunciation and more than one part of speech, the GetPronunciations method returns a collection of these objects.

SpUnCompressedLexicon.GetPronunciations(
     bstrWord As String,
     [LangId As Long],
     [TypeFlags As SpeechLexiconType]
) As ISpeechLexiconPronunciations

Parameters

bstrWord
The target lexicon word.
LangId
[Optional] The language ID.
TypeFlags
[Optional] A SpeechLexiconType constant. If Flags is SLTUser, only user lexicon words are returned; if Flags is SLTApp, only application lexicon words are returned.

Return Value

An ISpeechLexiconPronunciations object, which is a collection of one or more ISpeechLexiconPronunciation objects.


SpUnCompressedLexicon GetWords method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpUnCompressedLexicon

GetWords Method

The GetWords method gets a list of all words in the current the user or application lexicon.

An ISpeechLexiconWord object contains a word's pronunciation and type. The GetWords method returns a collection of these objects.

SpUnCompressedLexicon.GetWords(
     [Flags As SpeechLexiconType],
     [GenerationId As Long]
) As ISpeechLexiconWords

Parameters

Flags
[Optional] A SpeechLexiconType constant. If Flags is SLTUser, only user lexicon words are returned; if Flags is SLTApp, only application lexicon words are returned.
GenerationID
[Optional] The GenerationId.

Return Value

An ISpeechLexiconWords object, which is a collection of one or more ISpeechLexiconWord objects.


SpUnCompressedLexicon RemovePronunciation method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpUnCompressedLexicon

RemovePronunciation Method

The RemovePronunciation method removes a word and/or its pronunciations, specified in phone symbols, from the current application lexicon.

SpUnCompressedLexicon.RemovePronunciation(
     bstrWord As String,
     LangId As Long,
     [PartOfSpeech As SpeechPartOfSpeech = SPSUnknown],
     [bstrPronunciation As String]
)

Parameters

bstrWord
The lexicon word to be removed.
LangId
The language ID.
PartOfSpeech
[Optional] The PartOfSpeech. Default value is SPSUnknown.
bstrPronunciation
[Optional] The pronunciation, in phones, to be removed. If this parameter is not specified, all pronunciations of the word will be removed.

Return Value

None.


SpUnCompressedLexicon RemovePronunciationByPhoneIds method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpUnCompressedLexicon
Type: Hidden

RemovePronunciationByPhoneIds Method

The RemovePronunciationByPhoneIds method removes a word and/or its pronunciations, specified in phone IDs, from the current application lexicon.

SpUnCompressedLexicon.RemovePronunciationByPhoneIds(
     bstrWord As String,
     LangId As Long,
     [PartOfSpeech As SpeechPartOfSpeech = SPSUnknown],
     [PhoneIds As Variant]
)

Parameters

bstrWord
The lexicon word to be removed.
LangId
The language ID.
PartOfSpeech
[Optional] The PartOfSpeech. Default value is SPSUnknown.
PhoneIds
[Optional][Optional] The pronunciation, in phone IDs, to be removed. If this parameter is not specified, all pronunciations of a lexicon word will be removed.

Return Value

None.


SpVoice Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpVoice

The SpVoice object brings the text-to-speech (TTS) engine capabilities to applications using SAPI automation. An application can create numerous SpVoice objects, each independent of and capable of interacting with the others. An SpVoice object, usually referred to simply as a voice, is created with default property settings so that it is ready to speak immediately.

Voice Characteristics and UI Support

The fundamental characteristics of the voice are the Voice property, which can be thought of as the person of the voice, the Rate property, and the Volume property. "Microsoft Mary" and "Microsoft Mike" are examples of Voices. Use the GetVoices method to determine what other voices are available to the voice object.

These properties can be modified with a User Interface (UI). The IsUISupported method determines if a specific UI is supported. Use the DisplayUI method to display a supported UI. The TTS tab of Speech properties in Control Panel, which enables users to modify the characteristics of the default system voice, is an example of a voice UI.

Speaking and Queueing

The Speak method places a text stream in the TTS engine's input queue and returns a stream number. It can be called synchronously or asynchronously. When called synchronously, the Speak method does not return until the text has been spoken; when called asynchronously, it returns immediately, and the voice speaks as a background process.

When synchronous speech is used in an application, the application's execution is blocked while the voice speaks, and the user is effectively locked out. This may be acceptable for simple applications, or those with no graphical user interface (GUI), but when sophisticated user interaction is intended, asynchronous speaking will generally be more appropriate.

Asynchronous speaking can place numerous text streams into the input queue. These streams are also referred to as speech requests. The stream number returned by an asynchronous Speak call is the stream's index in the voice queue. The WaitUntilDone method blocks execution until the voice finishes speaking, enabling an application to speak a text stream asynchronously and determine when it finishes. The hidden SpeakCompleteEvent method is similar to WaitUntilDone, except that it returns an event handle for the background speaking process, and does not block application execution.

The SpeakStream method operates like the Speak method, except that it speaks sound files instead of text.

Voice Output

An SpVoice object is created with its audio output set to the system default audio output. Use the GetAudioOutputs method to determine what other outputs are available to the voice, and use the AudioOutput property to set its audio output to one of them.

Use the AudioOutputStream property with other Speech automation objects to store audio output in memory (see SpMemoryStream) or in files (see SpFileStream).

Voice Events

As a voice speaks text, it can generate events when it detects certain conditions in the input stream. These events are contained in the SpeechVoiceEvents enumeration. Examples of these events are completion of phonemes, words, or sentences, as well as changes of voice or the presence of bookmarks. The range of conditions which can be reported by SpeechVoiceEvents is wide enough that most applications will use only a few of them. To prevent the TTS engine from generating events that will be ignored by the application, use the EventInterests property to specify the events of interest. Only these events will be raised.

The point in the input text stream at which a potential event has been completed is referred to as an event boundary. At each event boundary, the event type is compared with the current EventInterests. If the event type is of interest, an event of that type is raised. Voice events return the input stream number in order to associate them with the appropriate stream.

Voice Priorities and Alerts

Application error handling has traditionally interrupted a UI with message boxes or alert boxes describing error states. Because a TTS application might operate with no graphical UI at all, it is able to implement error handling with a TTS voice. This voice is referred to as an alert, because its purpose is identical to that of an alert box or message box. To create an alert voice, create a new SpVoice object and set its Priority property appropriately. The alert voice should also use a different Voice property from the normal voice, so that users can easily distinguish the two.

When a speaking voice detects a pending alert, it continues speaking until it arrives at a specific application-defined stopping point, such as a sentence or a word. This stopping point is called the alert boundary because it is an event boundary at which alerts can be processed. When the alert has finished speaking, the interrupted voice resumes. Get and set the alert boundary with the AlertBoundary property.

Status and Control

The Status method may return an ISpeechVoiceStatus object, which contains several types of information about the state of the voice. Some ISpeechVoiceStatus properties are equivalent to parameters returned by voice events; it may be advantageous for some applications to get these elements by calling Status occasionally, rather than by receiving events constantly.

Voice status and voice events are closely associated with the status of the audio output device. A voice speaking to a file stream produces no audio output, generates no events, and has no audio output status. As a result, the ISpeechVoiceStatus data returned by that voice will always show it to be inactive.

A speaking voice can be paused at the next alert boundary with the Pause method. A paused voice can be resumed with the Resume method. The Skip method causes the voice to skip forward or backward in the input stream.

Automation Interface Elements

The SpVoice automation object has the following elements:

Properties | Description
AlertBoundary Property | Gets and sets the alert boundary, which specifies how a speaking voice pauses itself for alerts.
AllowAudioOutputFormatChangesOnNextSet Property | Gets and sets the flag that specifies whether the voice is allowed to adjust its audio output format automatically.
AudioOutput Property | Gets and sets the current audio output object used by the voice.
AudioOutputStream Property | Gets and sets the current audio stream object used by the voice.
EventInterests Property | Gets and sets the types of events received by the voice.
Priority Property | Gets and sets the priority level of the voice.
Rate Property | Gets and sets the speaking rate of the voice.
Status Property | Returns the current speaking and event status of the voice in an ISpeechVoiceStatus object.
SynchronousSpeakTimeout Property | Gets and sets the interval, in milliseconds, after which the voice's synchronous Speak and SpeakStream calls will time out when its output device is unavailable.
Voice Property | Gets and sets the currently active member of the Voices collection.
Volume Property | Gets and sets the base volume (loudness) level of the voice.
Methods | Description
DisplayUI Method | Initiates the display of the specified UI.
GetAudioOutputs Method | Returns a selection of available audio output tokens.
GetVoices Method | Returns a selection of voices available to the voice.
IsUISupported Method | Determines if the specified UI is supported.
Pause Method | Pauses the voice at the nearest alert boundary and closes the output device, allowing it to be used by other voices.
Resume Method | Causes the voice to resume speaking when paused.
Skip Method | Causes the voice to skip forward or backward by the specified number of items within the current input text stream.
Speak Method | Initiates the speaking of a text string, text file or wave file by the voice.
SpeakCompleteEvent Method | Gets an event handle from the voice that will be signaled when the voice finishes speaking.
SpeakStream Method | Initiates the speaking of a text stream or sound file by the voice.
WaitUntilDone Method | Blocks the caller until either the voice has finished speaking or the specified time interval has elapsed.


SpVoice AlertBoundary property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

AlertBoundary Property

The AlertBoundary property gets and sets the alert boundary, which specifies how a speaking voice pauses for alerts.

Because a TTS application might operate without a graphical user interface (UI), it must be able to implement error handling with a TTS voice. The only capability needed for voice error messaging is the ability to interrupt another voice; this capability is assigned to a voice by setting the Priority property to SVPAlert. A voice with a priority setting of SVPAlert is referred to as an alert voice, or simply as an alert, because its purpose is identical to that of an alert box or message box.

When a speaking voice detects a pending alert interruption, it continues speaking until it arrives at a specific application-defined stopping point, such as a sentence or a word. This stopping point is called the alert boundary because it is the event boundary at which alerts can be processed.

The SpeechVoiceEvents enumeration contains the types of events that a voice object can receive. The AlertBoundary property consists of one of these constants. The default setting is SVEWordBoundary.

Syntax

Set: | SpVoice.AlertBoundary = SpeechVoiceEvents
Get: | SpeechVoiceEvents = SpVoice.AlertBoundary

Parts

SpVoice
The owning object.
SpeechVoiceEvents
Set: A SpeechVoiceEvents constant that sets the alert boundary.
Get: A SpeechVoiceEvents constant that gets the alert boundary.

Example

The following code demonstrates the use of the Priority, EventInterests and AlertBoundary properties. The code uses the GetVoices method to select a male voice and a female voice, and sets the Priority property of the female voice to SVPAlert, making it an alert voice. The Priority of the male voice remains SVPNormal.

The code sets the EventInterests of the normal voice to SVEBookmark, so that it can receive bookmark events, and then speak a text string containing bookmarks. The normal voice's Bookmark event uses the alert voice to speak the bookmark data. Because the alert voice interrupts the normal voice, the normal voice is essentially using its own events to interrupt itself.

Note that the interruption does not occur immediately; the alert voice must first enqueue its text stream, and then the normal voice must detect the pending alert and stop speaking at the next alert boundary. The normal voice might speak several words or phonemes past the bookmark before it pauses for the alert voice to speak.

In this example, the normal voice can be interrupted on a phoneme boundary, which may divide a word. Changing the AlertBoundary to word or sentence boundaries will noticeably change the interaction of the two voices.

Option Explicit

Dim WithEvents objHIM As SpeechLib.SpVoice  'Normal voice will receive events
Dim objHER As SpeechLib.SpVoice             'Alert voice will not

Private Sub Command1_Click()
    On Error GoTo EH

    Dim strSpeak As String

    'Create an Alert Priority voice - female
    Set objHER = New SpVoice
    objHER.Priority = SVPAlert
    Set objHER.Voice = objHER.GetVoices("gender=female").Item(0)

    'Create a Normal Priority voice - male
    Set objHIM = New SpVoice
    Set objHIM.Voice = objHIM.GetVoices("gender=male").Item(0)

    objHER.Speak "the priority of this voice is S V P alert"
    objHIM.Speak "the priority of this voice is S V P normal"

    objHIM.EventInterests = SVEBookmark     'Receive bookmark events only
    objHIM.AlertBoundary = SVEPhoneme       'Let alert voices interrupt words

    'Normal voice speaks text which generates events.

    strSpeak = "This is text  that contains bookmarks " _
                & "for the  purpose of generating events."

    objHIM.Speak strSpeak, SVSFIsXML + SVSFlagsAsync

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub objHIM_Bookmark _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal Bookmark As String, _
    ByVal BookmarkId As Long)

    On Error GoTo EH
    objHER.Speak Bookmark, SVSFlagsAsync

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpVoice AllowAudioOutputFormatChangesOnNextSet property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice
Type: Hidden

AllowAudioOutputFormatChangesOnNextSet Property

The AllowOutputFormatChangesOnNextSet property gets and sets the flag that specifies whether SAPI will adjust the format of a voice object's new audio output device automatically.

By default, when an application sets a voice object's AudioOutput property to an audio device, SAPI will change the format of that device to match the engine's preferred format. In cases where a specific audio format is required, such as telephony applications, the AllowOutputFormatChangesOnNextSet property can be used to prevent this format change.

When this property is true, SAPI adjusts the format of the audio output object to the engine's preferred format. When it is false, SAPI uses the audio output object's format. If the output is set to a stream object, SAPI will convert the output to the format of the stream.

Syntax

Set: | SpVoice.AllowAudioOutputFormatChangesOnNextSet = Boolean
Get: | Boolean = SpVoice.AllowAudioOutputFormatChangesOnNextSet

Parts

SpVoice
The owning object.
Boolean
Set: A Boolean variable that sets the property value.
Get: A Boolean variable that gets the property value.

Remarks

Using the same audio format for input and output source is useful for sound cards that do not support full-duplex audio (i.e., input format must match output format). If the input format quality is lower than the output format quality, the output format quality will be reduced to equal the input quality.

Example

The following Visual Basic form code demonstrates the use of the AllowAudioOutputFormatChangesOnNextSet property. To run this code, create a form with the following controls:

  • Two command buttons called Command1 and Command2.

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object, an audio output object, and a SpeechAudioFormatType variable. Both command button procedures set the format of the audio output object to SAFT22kHz8BitMono, then set the AudioOutputStream of the voice to the audio output object, and then test if the voice's audio format has been changed.

In the Command1 procedure, the AllowAudioOutputFormatChangesOnNextSet is set to True, and the voice's format is changed. In the Command2 procedure, this property is set to False, and the voice's format is not changed.

Option Explicit

Dim V As SpeechLib.SpVoice
Dim O As SpMMAudioOut
Dim S As ISpeechBaseStream

Dim f As SpeechLib.SpeechAudioFormatType    'This is an Enum

Private Sub Form_Load()
    On Error GoTo EH

    Set V = New SpVoice
    Set O = New SpMMAudioOut
    f = SAFT22kHz8BitMono       'The test audio output format

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()
    On Error GoTo EH

    V.AllowAudioOutputFormatChangesOnNextSet = True

    O.Format.Type = f               'AudioOut obj gets SAFT22kHz8BitMono format
    Set V.AudioOutputStream = O     'The "Next Set"
    V.Speak "Adjust my format"      'Speak
    Set S = V.AudioOutputStream     'Stream object gets voice's format

    If S.Format.Type = f Then
        MsgBox "format not adjusted"
    Else
        MsgBox "format adjusted"
    End If

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH

    V.AllowAudioOutputFormatChangesOnNextSet = False

    O.Format.Type = f               'AudioOut obj gets SAFT22kHz8BitMono format
    Set V.AudioOutputStream = O     'The "Next Set"
    V.Speak "Leave my format alone" 'Speak
    Set S = V.AudioOutputStream     'Stream object gets voice's format

    If S.Format.Type = f Then
        MsgBox "format not adjusted"
    Else
        MsgBox "format adjusted"
    End If

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpVoice AudioOutput property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

AudioOutput Property

The AudioOutput property gets and sets the current audio output object used by the voice.

The AudioOutput property can be set with the object token for a standard Windows multi-media device. To use other types of devices, please see the Speech Telephony Application Guide.

Syntax

Set: | SpVoice.AudioOutput = SpObjectToken
Get: | SpObjectToken = SpVoice.AudioOutput

Parts

SpVoice
The owning object.
SpObjectToken
Get: An SpObjectToken object that gets the current audio output.
Set: An SpObjectToken object that sets the audio output.

Remarks

When setting the value, if the object is Nothing then the default audio device will be used.

Example

The following Visual Basic form code demonstrates the use of the GetAudioOutputs method and the AudioOutput property. To run this code, create a form with the following controls:

  • A command button called Command1
  • A list box called List1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates an SpVoice object and calls a subroutine called ShowAudioOutputs. This subroutine uses the GetAudioOutputs method to select all available output devices, and adds each device to the list box. The string (CURRENT) is appended to the current audio device name.

Select a device in the list box, and then click Command1. The Command1_Click procedure resets the voice's AudioOutput property to the device selected in the list box, and calls the ShowAudioOutputs subroutine, which will display the device selected as the current audio output.

Note If the computer currently has only one audio output device, clicking Command1 will not change the entry in the list box.

Option Explicit

Private V As SpeechLib.SpVoice
Private T As SpeechLib.SpObjectToken

Private Sub Form_Load()
    On Error GoTo EH

    Set V = New SpVoice
    Call ShowAudioOutputs

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()
    On Error GoTo EH

    If List1.ListIndex > -1 Then
        Set V.AudioOutput = V.GetAudioOutputs().Item(List1.ListIndex)
        Call ShowAudioOutputs
    End If

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowAudioOutputs()
    On Error GoTo EH

    Dim strAudio As String
    Dim strCurrentAudio As String

    List1.Clear
    Set T = V.AudioOutput               'Token for current audio output
    strCurrentAudio = T.GetDescription  'Get description from token

    'Show all available outputs; highlight the one in use

    For Each T In V.GetAudioOutputs
        strAudio = T.GetDescription     'Get description from token
        If strAudio = strCurrentAudio Then
            strAudio = strAudio & " (CURRENT)"  'Show current device
        End If
        List1.AddItem strAudio          'Add description to list box
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpVoice AudioOutputStream property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

AudioOutputStream Property

The AudioOutputStream property gets and sets the current audio stream object used by the voice.

Setting the voice's AudioOutputStream property may cause its audio output format to be automatically changed to match the text-to-speech (TTS) engine's preferred audio output format. If the voice's AllowAudioOutputFormatChangesOnNextSet property is True, the format change takes place; if False, the format remains unchanged. In order to set the AudioOutputStream property of a voice to a specific format, its AllowOutputFormatChangesOnNextSet should be False.

Syntax

Set: | SpVoice.AudioOutputStream = ISpeechBaseStream
Get: | ISpeechBaseStream = SpVoice.AudioOutputStream

Parts

SpVoice
The owning object.
ISpeechBaseStream
Get: An ISpeechBaseStream object that gets the current audio output stream.
Set: An ISpeechBaseStream object that sets the audio output stream.

Remarks

Voice status and voice events are closely associated with the status of the audio output device. A voice speaking to a file stream produces no audio output, generates no events, and has no audio output status. As a result, the ISpeechVoiceStatus data returned by that voice will always indicate that it is inactive.

Example

The following Visual Basic form code demonstrates the use of the AudioOutputStream property. To run this code, create a form with the following controls:

  • A textbox called Text1
  • Two command buttons called Command1 and Command2

Paste this code into the Declarations section of the form.

The Command1_Click procedure sets the AudioOutputStream property of the voice to a file called AudioOutputStream.wav and speaks the contents of the text box into a wave file. It then sets the voice's AudioOutputStream property to Nothing, so that subsequent voice output will be directed to the audio system rather than to a file.

The Command2_Click procedure plays back the wave file that created by the Command1_Click procedure.

Option Explicit

Const strFName = "C:\AudioOutputStream.wav"
Dim objVOICE As SpeechLib.SpVoice
Dim objFSTRM As SpeechLib.SpFileStream

Private Sub Form_Load()
    On Error GoTo EH

    Set objVOICE = New SpVoice
    Set objFSTRM = New SpFileStream
    Command2.Enabled = False    'Force create file before playback
    Text1.Text = "The TTS voice will speak this text into a file."

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()
    On Error GoTo EH

    Const FName = "C:\ExCodeAudioOutputStream.wav"

    ' Build a local wav file path and open it as a stream.
    Call objFSTRM.Open(FName, SSFMCreateForWrite, False)

    ' Set voice AudioOutputStream to the stream and speak
    ' the contents of the text box into the new wave file:
    Set objVOICE.AudioOutputStream = objFSTRM
    objVOICE.Speak Text1.Text

    ' Close the stream and set voice back to speaking:
    Call objFSTRM.Close
    Set objVOICE.AudioOutputStream = Nothing

    Command2.Enabled = True

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH

    objVOICE.Speak Text1.Text, SVSFIsXML

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpVoice DisplayUI method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

DisplayUI Method

The DisplayUI method initiates the display of the specified UI.

The speech recognition (SR) and text-to-speech (TTS) engines are capable of displaying and running various user interfaces (UI). These displays assist with different aspects of the speech environment such as user training, microphone wizards, adding and removing words, or setting controls for the engine. Many of these UIs are available using Speech properties in Control Panel. In addition, the engines are capable of requesting that the user run specific UIs to improve recognition. For example, the SR engine could request more user training if recognition is consistently poor.

Engines are not required to support UI and not all engines will have the same UI. Consult the manufacturer's engine documentation for specific details. An application may call IsUISupported before attempting to invoke a particular UI to see if the engine supports it. Invoking unsupported UIs will cause a run-time error. If the UI is available, use DisplayUI to invoke the display.

SpVoice.DisplayUI(
     hWndParent As Long,
     Title As String,
     TypeOfUI As String,
     [ExtraData As Variant = Nothing]
)

Parameters

hWndParent
Specifies the window handle of the owning window.
Title
Specifies the caption used for the UI window.
TypeOfUI
A String specifying the name of the UI to display.
ExtraData
[Optional] Specifies the ExtraData. This information is unique to the application and may be used to provide additional or more specific information to the UI. By default, the Nothing value is used and indicates that the UI does not use any additional information provided by this method.

Return Value

None.

Remarks

See SPVoice.IsUISupported for additional information.

Example

The following Visual Basic form code demonstrates the use of the DisplayUI and IsUISupported methods. The code displays the Master Volume window, the same sound panel that is available using Speech properties in Control Panel.

To run this code, create a single form without any controls on it. Paste this code into the Declarations section of the form.

Option Explicit

Dim vox As SpeechLib.SpVoice

Private Sub Form_Load()
    On Error GoTo EH

    Set vox = New SpVoice
    RunUI SpeechAudioVolume

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Function RunUI(theUI As String)
    On Error GoTo EH

    Dim x As Boolean

    If vox.IsUISupported(theUI) = True Then
        ' Display Master Volume window.
        vox.DisplayUI Form1.hWnd, "", theUI, ""
        MsgBox theUI & " UI is supported"
    Else
        MsgBox theUI & " UI not supported"
    End If

EH:
    If Err.Number Then ShowErrMsg
End Function

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpVoice EventInterests property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

EventInterests Property

The EventInterests property gets and sets the types of events received by the SpVoice object.

When a text-to-speech (TTS) engine speaks a stream of text, it is constantly detecting certain conditions in the stream, such as the completion of phonemes, words and sentences. When it detects one of these conditions, the engine is able to generate a component object model (COM) event that will be received by the voice object that enqueued the stream.

When the engine detects a potential event condition in a stream, it checks the EventInterests property of the voice that enqueued the stream. If that event type is included in the voice object's event interests, the engine will generate an event of that type.

In Visual Basic, it is necessary to use the WithEvents keyword when dimensioning an SpVoice object intended to receive events. The default setting of the EventInterests property is 33278, or 0x081FE, which represents the sum of all SpeechVoiceEvents constants except SVEAudioLevel (a change in audio level).

Syntax

Set: | SpVoice.EventInterests = SpeechVoiceEvents
Get: | SpeechVoiceEvents = SpVoice.EventInterests

Parts

SpVoice
The owning object.
SpeechVoiceEvents
Set: One or more SpeechVoiceEvents setting the EventInterests.
Get: A number equivalent to the SpeechVoiceEvents in the EventInterests.

Remarks

The values assigned to SpeechVoiceEvents constants are single-bit values, like 1, 2, 4, 8, 16, etc. Use a logical Or function to add them to EventInterests, and a logical XOr function to remove them. It should be noted that a logical Xor function does not zero a bit value, but toggles the value. Because of this, it is necessary to ensure that the bit value is set before attempting to zero it with an Xor.

Recognition contexts support an EventInterests property, which uses a similar syntax to specify interest in speech recognition events.

Example

The following Visual Basic form code demonstrates the syntax of the EventInterests property. Interest in individual events is set and reset using logical Or and Xor statements.

To run this code, create a single form without any controls on it. Paste this code into the Declarations section of the form.

Option Explicit

Dim objVoice As SpeechLib.SpVoice

Private Sub Form_Load()
    On Error GoTo EH

    Set objVoice = New SpVoice
    Call EventInterests

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub EventInterests()
    On Error GoTo EH

    With objVoice

        ' Add the SVEPhoneme and SVEViseme constants to Event Interests
        ' (setting bit with logical 'Or' doesn't require testing):
        .EventInterests = .EventInterests Or SVEPhoneme
        MsgBox .EventInterests, vbInformation
        .EventInterests = .EventInterests Or SVEViseme
        MsgBox .EventInterests, vbInformation

        ' Remove the SVEViseme constant from Event Interests
        ' (zeroing bit with logical 'Xor' requires testing!)--
        If (.EventInterests And SVEViseme) = SVEViseme Then
            .EventInterests = .EventInterests Xor SVEViseme
            MsgBox .EventInterests, vbInformation
        End If

    End With

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpVoice GetAudioOutputs method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

GetAudioOutputs Method

The GetAudioOutputs method returns a selection of available audio output tokens.

See Object Tokens and Registry Settings White Paper for a list of SAPI 5-defined attributes.

SpVoice.GetAudioOutputs(
     [RequiredAttributes As String = ""],
     [OptionalAttributes As String = ""]
) As ISpeechObjectTokens

Parameters

RequiredAttributes
[Optional] Specifies the RequiredAttributes. To be returned by GetAudioOutputs, audio output tokens must contain all of the specific required attributes. If no tokens match the selection, the selection returned will not contain any elements. By default, no attributes are required and so the method returns all the tokens discovered.
OptionalAttributes
[Optional] Specifies the OptionalAttributes. Returned tokens containing the RequiredAttributes are sorted by OptionalAttributes. If OptionalAttributes is specified, the tokens are listed with the OptionalAttributes first. By default, no attribute is specified and the list returned from the speech configuration database is in the order that attributes were discovered.

Return Value

An ISpeechObjectTokens collection containing the selected outputs.

Remarks

The format of selection criteria may either be Value or "Attribute = Value". Values may be excluded by "Attribute != Value".

Example

The following Visual Basic form code demonstrates the use of the GetAudioOutputs method and the AudioOutput property. To run this code, create a form with the following controls:

  • A command button called Command1
  • A list box called List1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates an SpVoice object and calls a subroutine called ShowAudioOutputs. This subroutine uses the GetAudioOutputs method to select all available output devices and adds each device to the list box. The string (Current) is appended to the current audio device name.

Select a device in the list box and then click Command1. The Command1_Click procedure resets the voice's AudioOutput property to the device selected in the list box, and calls the ShowAudioOutputs subroutine, which will display the device selected as the current audio output.

Option Explicit

Private V As SpeechLib.SpVoice
Private T As SpeechLib.SpObjectToken

Private Sub Form_Load()
    On Error GoTo EH
    Set V = New SpVoice
    Call ShowAudioOutputs

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()
    On Error GoTo EH

    If List1.ListIndex > -1 Then
        Set V.AudioOutput = V.GetAudioOutputs().Item(List1.ListIndex)
        Call ShowAudioOutputs
    End If

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowAudioOutputs()
    On Error GoTo EH

    Dim strAudio As String
    Dim strCurrentAudio As String

    List1.Clear
    Set T = V.AudioOutput               'Token for current audio output
    strCurrentAudio = T.GetDescription  'Get description from token

    For Each T In V.GetAudioOutputs
        strAudio = T.GetDescription     'Get description from token
        If strAudio = strCurrentAudio Then
            strAudio = strAudio & " (Current)"  'Show current device
        End If
        List1.AddItem strAudio          'Add description to list box
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpVoice GetVoices method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

GetVoices Method

The GetVoices method returns a selection of voices available to the voice.

Selection criteria may be applied optionally. In the absence of selection criteria, all voices are returned in the selection, ordered alphabetically by the voice name. If no voices match the criteria, GetVoices returns an empty selection, that is, an ISpeechObjectTokens collection with a Count of zero.

See Object Tokens and Registry Settings White Paper for a list of SAPI 5-defined attributes.

SpVoice.GetVoices(
     [RequiredAttributes As String = ""],
     [OptionalAttributes As String = ""]
) As ISpeechObjectTokens

Parameters

RequiredAttributes
[Optional] Specifies the RequiredAttributes. All voices selected will match these specifications. If no voices match the selection, the selection returned will contain no voices. By default, no attributes are required and so the list returns all the tokens discovered.
OptionalAttributes
[Optional] Specifies the OptionalAttributes. Voices which match these specifications will be returned at the front of the selection. By default, no attribute is specified and the list returned from the speech configuration database is in the order that attributes were discovered.

Return Value

An ISpeechObjectTokens variable containing the collection of voice tokens selected.

Remarks

The format of selection criteria is "Attribute = Value" and "Attribute != Value." Voice attributes include "Gender," "Age," "Name," "Language," and "Vendor."

Example

The following Visual Basic form code demonstrates the use of the GetVoices method and the Voice property. To run this code, create a form with the following controls:

  • A command button called Command1
  • A list box called List1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object and displays the names of all available voices in the list box. Select a voice name in the list box and then click Command1. The Command1 procedure sets the voice object's Voice property to the selected name and causes the voice to speak its new name.

Option Explicit

Private V As SpeechLib.SpVoice
Private T As SpeechLib.ISpeechObjectToken

Private Sub Command1_Click()
    On Error GoTo EH

    If List1.ListIndex > -1 Then

        ' Set voice object to voice name selected in
        ' list box (new voice speaks its own name):
        Set V.Voice = V.GetVoices().Item(List1.ListIndex)
        V.Speak V.Voice.GetDescription

    Else
        MsgBox "Please select a voice from the list box."
    End If

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Dim strVoice As String

    Set V = New SpVoice

    'Get each token in the collection returned by GetVoices
    For Each T In V.GetVoices
        strVoice = T.GetDescription     'The token's name
        List1.AddItem strVoice          'Add to listbox
    Next

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpVoice IsUISupported method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

IsUISupported Method

The IsUISupported method determines whether the specified UI is supported.

The speech recognition (SR) and text-to-speech (TTS) engines are capable of displaying and running various user interfaces (UI). These displays assist with different aspects of the speech environment such as user training, microphone wizards, adding and removing words, or setting controls for the engine. Many of these UIs are available using Speech properties in Control Panel. In addition, the engines are capable of requesting that the user run specific UIs to improve recognition. For example, the SR could request more user training if recognition is consistently poor.

Engines are not required to support UI and not all engines will have the same UI. Consult the manufacturer's engine documentation for specific details. An application may call IsUISupported before attempting to invoke a particular UI to see if the engine supports it. Invoking unsupported UIs will cause a run-time error. If the UI is available, use DisplayUI to invoke the display.

SpVoice.IsUISupported(
     TypeOfUI As String,
     [ExtraData As Variant = Nothing]
) As Boolean

Parameters

TypeOfUI
A String specifying the name of the UI to display.
ExtraData
[Optional] Specifies the ExtraData. This information is unique to the application and may be used to provide additional or more specific information to the UI. By default, the Nothing value is used and indicates the UI does not use any additional information provided by this method.

Return Value

A Boolean variable indicating whether the specified UI is supported. It returns True if supported, or False if not supported.

Remarks

See SPVoice.DisplayUI for additional information.

Example

The following Visual Basic form code demonstrates the use of the DisplayUI and IsUISupported methods. The code displays the Master Volume window, the same sound panel that is available using Speech properties in Control Panel

To run this code, create a single form without any controls on it. Paste this code into the Declarations section of the form.

Option Explicit

Dim vox As SpeechLib.SpVoice

Private Sub Form_Load()
    On Error GoTo EH

    Set vox = New SpVoice
    RunUI SpeechAudioVolume

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Function RunUI(theUI As String)
    On Error GoTo EH

    Dim x As Boolean

    If vox.IsUISupported(theUI) = True Then
        ' Display Master Volume window.
        vox.DisplayUI Form1.hWnd, "", theUI, ""
        MsgBox theUI & " UI is supported"
    Else
        MsgBox theUI & " UI not supported"
    End If

EH:
    If Err.Number Then ShowErrMsg
End Function

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpVoice Pause method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

Pause Method

The Pause method pauses the voice at the nearest alert boundary and closes the output device, allowing it to be used by other voices.

SpVoice.Pause()

Parameters

None.

Return Value

None.

Example

The following Visual Basic form code demonstrates the use of the Pause and Resume methods. To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object. The first call of the Command1_Click procedure causes the voice to begin speaking a text stream. Subsequent Command1 clicks alternately pause and resume the voice. When the voice has finished speaking the stream, the EndStream event procedure causes the voice to speak it again.

The voice's AlertBoundary setting of SVEPhoneme means that the Pause method can interrupt the voice within word boundaries. The text stream spoken contains a number of long words in order to show this interruption of words more clearly.

Option Explicit

Private WithEvents V As SpeechLib.SpVoice

Private Sub Command1_Click()
    On Error GoTo EH

    Select Case Command1.Caption

        Case "Start"
            Call SpeakAgain
            Command1.Caption = "Pause"

        Case "Pause"
            V.Pause
            Command1.Caption = "Resume"

        Case "Resume"
            V.Resume
            Command1.Caption = "Pause"

    End Select

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Form_Load()
    On Error GoTo EH

    Set V = New SpVoice
    V.AlertBoundary = SVEPhoneme    'Let words be interrupted
    Command1.Caption = "Start"

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub V_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    Call SpeakAgain

End Sub

Private Sub SpeakAgain()
    On Error GoTo EH

    V.Speak "this phenomenal asynchronous stream contains multisyllabic " _
            & "pronunciations and circumlocutions.", SVSFlagsAsync

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpVoice Priority property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

Priority Property

The Priority property gets and sets the priority level of the voice.

The priority level defines the order in which the text-to-speech (TTS) engine processes a voice object's speech requests relative to requests from other voice objects. Higher priority levels are assigned to error-handling voices and the lowest priority level is assigned to normal voices. Because of their priority level, voice requests from error-handling voices are spoken ahead of normal priority voice requests; as a result, error-handling voices can appear to interrupt normal voices.

The voice priority levels are contained in the SpeechVoicePriority enumeration. An SpVoice object is created with normal priority. To create an alert or over voice, create a voice and set its Priority property appropriately.

Syntax

Set: | SpVoice.Priority = SpeechVoicePriority
Get: | SpeechVoicePriority = SpVoice.Priority

Parts

SpVoice
The owning object.
SpeechVoicePriority
Set: A SpeechVoicePriority constant that sets the priority level.
Get: A SpeechVoicePriority constant that returns the current priority level.

Remarks

A voice with a Priority setting of SVPAlert is referred to as an alert voice. Alert voices are designed to be the primary vehicle for TTS error-handling. Other SpVoice elements, such as the AlertBoundary property, support error-handling functionality in alert voices that is not available to other voices.

Example

The following Visual Basic form code demonstrates the use of the Priority property. To run this code, create a form with the following controls:

  • Two command buttons called Command1 and Command2

Paste this code into the Declarations section of the form.

The Form_Load procedure creates three voice objects and assigns different Voice and Priority settings to each. Each voice is named after its Priority setting.

In the Command1_Click event procedure, the normal voice begins speaking asynchronously. The alert voice waits a few seconds and then begins speaking. The normal voice is interrupted by the alert voice and resumes speaking when the alert voice has finished.

In the Command2_Click event procedure, the normal voice and the over voice begin speaking asynchronously. The alert voice waits a few seconds and then begins speaking. The normal voice is interrupted by the alert voice and resumes speaking when the alert voice has finished. The over voice speaks over, or mixes with, the other two voices.

Please see the AlertBoundary property for another code example using the Priority property.

Option Explicit

Dim Normal As SpeechLib.SpVoice
Dim Alert As SpeechLib.SpVoice
Dim Over As SpeechLib.SpVoice

Private Sub Form_Load()
    On Error GoTo EH

    Set Normal = New SpVoice
    Set Alert = New SpVoice
    Set Over = New SpVoice

    Alert.Priority = SVPAlert   'From SVPNormal to SVPAlert
    Over.Priority = SVPOver     'From SVPNormal to SVPOver

    'Presumes two male voices and one female voice
    Set Normal.Voice = Normal.GetVoices("gender = male").Item(0)    '1st male voice
    Set Alert.Voice = Alert.GetVoices("gender = male").Item(1)      '2nd male voice
    Set Over.Voice = Normal.GetVoices("gender = female").Item(0)    '1st female voice

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()
    On Error GoTo EH

    'Enqueue streams from normal voice
    Normal.Speak "a normal voice. a normal priority voice.", SVSFlagsAsync
    Normal.Speak "a normal voice. a normal priority voice.", SVSFlagsAsync

    Call Wait(3)    'Alert voice interrupts normal
    Alert.Speak "excuse me, alert voice!", SVSFlagsAsync

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command2_Click()
    On Error GoTo EH

    'Enqueue streams from Normal voice and Over voice
    Normal.Speak "a normal voice. a normal priority voice.", SVSFlagsAsync
    Normal.Speak "a normal voice. a normal priority voice.", SVSFlagsAsync

    Over.Speak "over voice speaking over the other voices.", SVSFlagsAsync
    Over.Speak "over voice speaking over the other voices.", SVSFlagsAsync
    Over.Speak "over voice speaking over the other voices.", SVSFlagsAsync

    Call Wait(3)    'Alert voice interrupts normal
    Alert.Speak "excuse me, alert voice!", SVSFlagsAsync

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Wait(ByVal Seconds As Integer)
    On Error GoTo EH

    Dim sglWait As Single
    sglWait = Timer() + Seconds
    Do
        DoEvents
    Loop Until Timer > sglWait

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpVoice Rate property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

Rate Property

The Rate property gets and sets the speaking rate of the voice.

Values for the Rate property range from -10 to 10, which represent the slowest and the fastest speaking rates, respectively.

At the beginning of each Speak or SpeakStream method, the voice sets its speaking rate according to the value of its Rate property, and speaks the entire stream at that rate. The Rate property can be changed at any time, but the actual speaking rate will not reflect the changed property value until it begins a new stream.

Syntax

Set: | SpVoice.Rate = Long
Get: | Long = SpVoice.Rate

Parts

SpVoice
The owning object.
Long
Set: A Long variable that sets the property value.
Get: A Long variable that gets the property value.

Example

The following Visual Basic form code demonstrates the use of the Rate and the Volume properties. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1
  • A vertical scroll bar called VScroll1
  • A horizontal scroll bar called HScroll1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object and associates the VScrollbar with the voice's Volume property and the HScrollbar with the voice's Rate property. Adjusting the scroll bars changes the settings of the Volume and Rate properties. The Command1_Click procedure speaks a phrase in order to demonstrate the effects of the changes.

Option Explicit

Private V As SpeechLib.SpVoice

Private Sub Form_Load()
    On Error GoTo EH

    Set V = New SpeechLib.SpVoice

    VScroll1.Min = 0
    VScroll1.Max = 100
    VScroll1.Value = V.Volume

    HScroll1.Min = -10
    HScroll1.Max = 10
    HScroll1.Value = V.Rate

    Text1.Text = "Vol: " & VScroll1.Value & ";  Rate: " & HScroll1.Value

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Command1_Click()
    On Error GoTo EH

    V.Speak "The quick brown fox jumped over the lazy dog.", SVSFlagsAsync

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub HScroll1_Change()

    V.Rate = HScroll1.Value
    Text1.Text = "Vol: " & VScroll1.Value & ";  Rate: " & HScroll1.Value

End Sub

Private Sub VScroll1_Change()

    V.Volume = VScroll1.Value
    Text1.Text = "Vol: " & VScroll1.Value & ";  Rate: " & HScroll1.Value

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


SpVoice Resume method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

Resume Method

The Resume method causes the voice to resume speaking when paused.

SpVoice.Resume()

Parameters

None.

Return Value

None.

Example

The following Visual Basic form code demonstrates the use of the Pause and Resume methods. To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object. The first call of the Command1_Click procedure causes the voice to begin speaking a text stream. Subsequent Command1 clicks alternately pause and resume the voice. When the voice has finished speaking the stream, the EndStream causes the voice to speak it again.

The voice's AlertBoundary setting of SVEPhoneme means that the Pause method can interrupt the voice within word boundaries. The text stream spoken contains a number of long words in order to show this interruption of words more clearly.

Option Explicit

Private WithEvents V As SpeechLib.SpVoice

Private Sub Command1_Click()

    Select Case Command1.Caption

    Case "Start"
        Call SpeakAgain
        Command1.Caption = "Pause"

    Case "Pause"
        V.Pause
        Command1.Caption = "Resume"

    Case "Resume"
        V.Resume
        Command1.Caption = "Pause"

    End Select

End Sub

Private Sub Form_Load()

    Set V = New SpVoice
    V.AlertBoundary = SVEPhoneme    'Let words be interrupted
    Command1.Caption = "Start"

End Sub

Private Sub V_EndStream(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Call SpeakAgain
End Sub

Private Sub SpeakAgain()
    V.Speak "this phenomenal asynchronous stream contains multisyllabic " _
            & "pronunciations and circumlocutions.", SVSFlagsAsync
End Sub


SpVoice Skip method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

Skip Method

The Skip method skips the voice forward or backward by the specified number of items within the current input text stream.

SpVoice.Skip(
     Type As String,
     NumItems As Long
) As Long

Parameters

Type
The type of items to be skipped. Currently, Sentence is the only type supported.
NumItems
The number of items to be skipped forward in the voice input stream. A negative value specifies skipping backward.

Return Value

A Long variable containing the number of items skipped.

Example

The following Visual Basic form code demonstrates the use of the Skip method. To run this code, create a form with the following controls:

  • A text box called Text1
  • Two command buttons called Command1 and Command2
  • An HScrollbar control called HScroll1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice, sets up the HScrollbar with a value of -2 in a range from -5 to 5, and puts a string of numbers in the textbox. Because the numbers are followed by periods and separated by spaces, SAPI considers each number to be a sentence. The scrollbar specifies the number of sentences that the voice object will skip.

Click Command1 to start the voice speaking the sentences in the textbox. Click Command2 to skip the voice forward or backward, depending on the value of the scrollbar control. Click the left side or the right side of the scrollbar to increase or decrease the number of sentences to be skipped by the Command2 button.

Option Explicit

Private WithEvents V As SpeechLib.SpVoice

Private Sub Command1_Click()
    V.Speak Text1.Text, SVSFlagsAsync
End Sub

Private Sub Command2_Click()
    V.Skip "Sentence", HScroll1.Value
End Sub

Private Sub Form_Load()

    Set V = New SpVoice

    HScroll1.Min = -5
    HScroll1.Max = 5
    HScroll1.Value = -2

    Text1.Text = "1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20."

End Sub

Private Sub HScroll1_Change()
    If HScroll1.Value > 0 Then
        Command2.Caption = " Skip forward " & HScroll1.Value & " sentences"
    Else
        Command2.Caption = " Skip backward " & Abs(HScroll1.Value) & " sentences"
    End If
End Sub

Private Sub V_Word(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, _
                   ByVal CharacterPosition As Long, ByVal Length As Long)
    Text1.SetFocus
    Text1.SelStart = CharacterPosition
    Text1.SelLength = Length
End Sub


SpVoice Speak method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

Speak Method

The Speak method initiates the speaking of a text string, a text file, an XML file, or a wave file by the voice.

The Speak method can be called synchronously or asynchronously. When called synchronously, the method does not return until the text has been spoken; when called asynchronously, it returns immediately, and the voice speaks as a background process.

When synchronous speech is used in an application, the application's execution is blocked while the voice speaks, and the user is effectively locked out. This may be acceptable for simple applications, or those with no graphical user interface (GUI), but when sophisticated user interaction is intended, asynchronous speaking will generally be more appropriate.

The WaitUntilDone and SpeakCompleteEvent methods can be used to block an application's forward progress while allowing user interaction with the mouse or keyboard.

SpVoice.Speak(
     Text As String,
     [Flags As SpeechVoiceSpeakFlags = SVSFDefault]
) As Long

Parameters

Text
The text to be spoken, or if the SVSFIsFilename flag is included in the Flags parameter, the path of the file to be spoken.
Flags
[Optional] Flags. Default value is SVSFDefault.

Return Value

A Long variable containing the stream number. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate events with the appropriate stream.

Remarks

The Speak method inserts a stream into the text-to-speech (TTS) engine's queue, and returns a stream number, assigned by the engine. This distinguishes the stream from other streams in the queue. This number is a temporary identifier which functions like an index into the TTS queue. The first stream spoken into an empty queue will always have a stream number of 1.

A voice object can enqueue numerous streams, and each of these streams can generate events. SpVoice events always return the stream number as a parameter. If an application saves the stream numbers of the streams it enqueues, events can be associated with the proper stream.

Example

The following code snippet demonstrates the Speak method with several commonly used flag settings.

Const cstrTextName = "c:\Speech Voice Speak.txt"

Dim V As SpeechLib.SpVoice
Set V = New SpVoice

'Build a simple text file for demonstration purposes
Open cstrTextName For Output As #1
Print #1, "The name of this file is " & cstrTextName
Close #1

'Speak literal text
V.Speak "This is some text", SVSFDefault

'Speak the text of the test file
V.Speak cstrTextName, SVSFIsFilename + SVSFlagsAsync

'Speak with/without punctuation
V.Speak "one, two, three!", SVSFlagsAsync
V.Speak "one, two, three!", SVSFNLPSpeakPunc + SVSFlagsAsync

'Speak text with/without XML tags
V.Speak "text with XML", SVSFIsXML + SVSFlagsAsync
V.Speak "text with XML", SVSFIsNotXML + SVSFlagsAsync

V.WaitUntilDone 10000


SpVoice SpeakCompleteEvent method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice
Type: Hidden

SpeakCompleteEvent Method

The SpeakCompleteEvent method gets an event handle from the voice that will be signaled when the voice finishes speaking.

The SpeakCompleteEvent method is similar to the WaitUntilDone method, but supports more sophisticated ways of waiting for the voice to finish speaking.

The WaitUntilDone method explicitly blocks program execution until the voice finishes. The SpeakCompleteEvent method does not block execution, but returns an event handle that can be used with API wait functions such as WaitForSingleObject.

Because these functions can wait for short periods of time, applications may be able to perform useful tasks while polling the event handle.

SpVoice.SpeakCompleteEvent() As Long

Parameters

None.

Return Value

A Long variable containing the event handle.

Example

The following code snippet demonstrates the use of the SpeakCompleteEvent method. The asynchronous Speak call returns immediately, and causes the voice to begin speaking as a background process. The SpeakCompleteEvent method returns the event handle of the speaking process. This handle is passed to WaitForSingleObject, which waits for a completion signal from the process. When the background speaking process signals its completion, the call to WaitForSingleObject returns, and the program continues.

Dim objVoice As SpeechLib.SpVoice
Dim lngHandle As Long
Dim lngRtn As Long
Const INFINITE = -1&

Set objVoice = New SpVoice
objVoice.Speak "please wait until this text has been spoken", SVSFlagsAsync

lngHandle = objVoice.SpeakCompleteEvent             'Get a handle on this stream
lngRtn = WaitForSingleObject(lngHandle, INFINITE)   'Wait for completion


SpVoice SpeakStream method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

SpeakStream Method

The Speakstream method initiates speaking of a sound file by the voice.

SpVoice.SpeakStream(
     Stream As ISpeechBaseStream,
     [Flags As SpeechVoiceSpeakFlags = SVSFDefault]
) As Long

Parameters

Stream
Specifies an ISpeechBaseStream object containing the stream.
Flags
[Optional] Specifies the Flags. Default value is SVSFDefault.

Return Value

A Long variable containing the stream number. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate events with the appropriate stream.

Example

The following code snippet demonstrates the use of the SpeakStream method. To run this code, create a form with the following control:

  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a male and a female voice. The Command1_Click procedure causes the female voice to speak text into a file, and the male voice to play that file using the SpeakStream method.

Option Explicit

Private M As SpeechLib.SpVoice      'M is a male voice
Private F As SpeechLib.SpVoice      'F is a female voice
Private S As SpeechLib.SpFileStream

Private Sub Command1_Click()

    'Build a local file path and open it as a stream
    Set S = New SpFileStream
    Call S.Open("C:\SpeakStream.wav", SSFMCreateForWrite, False)

    'Female voice speaks into the file stream and creates a WAV file
    Set F.AudioOutputStream = S
    F.Speak "cee : \ speak stream dot wave", SVSFNLPSpeakPunc
    S.Close

    'Male voice speaks female voice's stream
    Call S.Open("C:\SpeakStream.wav", , False)
    M.Speak "i will now demonstrate the speak stream method."
    M.SpeakStream S
    M.Speak "that sounded like " & F.Voice.GetDescription & ", but it was me."

End Sub

Private Sub Form_Load()

    'Create voices
    Set F = New SpVoice
    Set F.Voice = F.GetVoices("gender=female").Item(0)
    Set M = New SpVoice
    Set M.Voice = M.GetVoices("gender=male").Item(0)

End Sub


SpVoice Status property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

Status Property

The Status property returns the current speaking and event status of the voice in an ISpeechVoiceStatus object.

Syntax

Set: | (This property is read-only)
Get: | ISpeechVoiceStatus = SpVoice.Status

Parts

SpVoice
The owning object.
ISpeechVoiceStatus
Set: (This property is read-only)
Get: An ISpeechVoiceStatus object containing Status information.

Remarks

Properties of the ISpeechVoiceStatus object may also be accessed through an implicit status object by means of the syntax "propertyvalue = SpVoice.Status.propertyname." Please see the example below.

The Status method is designed for use with voices speaking to audio devices. Because the Status method is closely associated with audio device status, it will not return an active status for a voice speaking to an audio output stream.

Example

The following code snippet demonstrates two ways of using the Status method. The first uses an implicit status object; the second creates the status object explicitly.

Use of the voice Status method and the ISpeechVoiceStatus interface is demonstrated with more detail in the ISpeechVoiceStatus code example.

Dim objVOICE As SpeechLib.SpVoice
Dim objSTATUS As SpeechLib.ISpeechVoiceStatus

' Assume that objVOICE has been created, and
' has spoken some text asynchronously.

' ISpeechVoiceStatus object is implicit here
'
If objVOICE.Status.CurrentStreamNumber = 2 Then
    'Do something
End If

' ISpeechVoiceStatus object is explicit here
'
Set objSTATUS = objVOICE.Status
If objSTATUS.CurrentStreamNumber = 2 Then
    'Do something
End If


SpVoice SynchronousSpeakTimeout property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

SynchronousSpeakTimeout Property

The SynchronousSpeakTimeout property gets and sets the interval, in milliseconds, after which the voice's synchronous Speak and SpeakStream calls will time out when its output device is unavailable.

When a voice enqueues a text stream, the audio output device represented by its AudioOutput property may be in use. When the text stream is enqueued synchronously, the voice will wait for the amount of time specified in its SynchronousSpeakTimeout property. If the output device does not become available to the voice before the time has elapsed, the voice will time out, the synchronous speech request is cancelled, and the application receives an SPERR_DEVICE_BUSY error. This and other SAPI errors are detailed in Error Codes

There is no equivalent timeout for asynchronous speech. Because synchronous speech prevents applications from receiving events from mouse movements and keyboard input, unexpected voice streams from other applications could freeze an application attempting synchronous speech. The SynchronousSpeakTimeout is designed so that applications can recover from such situations.

Syntax

Set: | SpVoice.SynchronousSpeakTimeout = Long
Get: | Long = SpVoice.SynchronousSpeakTimeout

Parts

SpVoice
The owning object.
Long
Set: A Long variable that sets the property value.
Get: A Long variable that gets the property value.

Example

The following Visual Basic form code demonstrates the use of the SynchronousSpeakTimeout property. To run this code, create a form with the following controls:

  • A list box control called List1
  • A command button called Command1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates three voices. The Command1_Click procedure starts the first voice speaking, which makes the audio output device unavailable to the other voices. The SynchronousSpeakTimeout property of the second voice is set to one millisecond, ensuring that it will time out before the first voice finishes speaking. The third voice simply waits for the first voice to finish, and then speaks.

The voices use a subroutine to speak; this subroutine adds each speech request to the list box and tests for the error that occurs when a voice times out.

Option Explicit

Const SPERR_DEVICE_BUSY = &H80045006

Dim v1 As SpeechLib.SpVoice
Dim v2 As SpeechLib.SpVoice
Dim v3 As SpeechLib.SpVoice

Private Sub Command1_Click()

    List1.Clear

    'Voice 1 takes control of the audio
    Call SafeSpeak(v1, "This is voice number 1", SVSFlagsAsync)
    Call SafeSpeak(v1, "Voice 2 and voice 3 will wait for me", SVSFlagsAsync)
    v1.WaitUntilDone 100    'ensure that the voice 1 starts first

    'Voice 2 starts waiting until voice 1 is done,
    'but its timeout is very short -- 1 millisecond.
    'So it times out before voice 1 is done.
    v2.SynchronousSpeakTimeout = 1
    Call SafeSpeak(v2, "This is voice 2", SVSFDefault)
    Call SafeSpeak(v2, "This is voice 2 again", SVSFDefault)

    'Voice 3 simply waits until voice 1 is done.
    Call SafeSpeak(v3, "This is voice 3 now", SVSFDefault)

End Sub

Private Sub Form_Load()
    Set v1 = New SpVoice
    Set v2 = New SpVoice
    Set v3 = New SpVoice
End Sub

Private Sub SafeSpeak(who As SpVoice, ByVal txt, ByVal flags)
    On Error GoTo SafeSpeakExit
    DoEvents
    who.Speak txt, flags

SafeSpeakExit:
    Select Case Err.Number
    Case 0:                     List1.AddItem "queued:  " & txt
    Case SPERR_DEVICE_BUSY:     List1.AddItem "timeout: " & txt
    End Select
    Err.Clear
End Sub


SpVoice Voice property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

Voice Property

The Voice property gets and sets the currently active member of the Voices collection.

The Voice property can be thought of as the person of a voice object; examples of Voices are "Microsoft Mary" and "Microsoft Mike." Use the GetVoices method to determine what voices are available.

Syntax

Set: | SpVoice.Voice = SpObjectToken
Get: | SpObjectToken = SpVoice.Voice

Parts

SpVoice
The owning object.
SpObjectToken
Set: An SpObjectToken object that sets the voice property.
Get: An SpObjectToken object that gets the current voice.

Remarks

If there is not a voice currently in use, this property will return the token for the default voice.

Example

The following Visual Basic form code demonstrates the use of the GetVoices method and the Voice property. To run this code, create a form with the following controls:

  • A command button called Command1
  • A list box called List1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object, and displays the names of all available voices in the list box. Select a voice name in the list box and then click Command1; the Command1 procedure sets the voice object's Voice property to the selected name, and causes the voice to speak its new name.

Option Explicit

Private V As SpeechLib.SpVoice
Private T As SpeechLib.ISpeechObjectToken

Private Sub Command1_Click()

    If List1.ListIndex > -1 Then

        'Set voice object to voice name selected in list box
        'The new voice speaks its own name

        Set V.Voice = V.GetVoices().Item(List1.ListIndex)
        V.Speak V.Voice.GetDescription

    Else
        MsgBox "Please select a voice from the listbox"
    End If

End Sub

Private Sub Form_Load()
    Dim strVoice As String

    Set V = New SpVoice

    'Get each token in the collection returned by GetVoices
    For Each T In V.GetVoices
        strVoice = T.GetDescription     'The token's name
        List1.AddItem strVoice          'Add to listbox
    Next

End Sub


SpVoice Volume property (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

Volume Property

The Volume property gets and sets the base volume (loudness) level of the voice.

Values for the Volume property range from 0 to 100, representing the minimum and maximum volume levels, respectively.

At the beginning of each Speak or SpeakStream method, the voice sets the volume level according to the value of the Volume property, and speaks the entire stream at that level. The voice's Volume property can be changed at any time, but the actual volume level will not reflect the changed property value until it begins a new stream.

Syntax

Set: | SpVoice.Volume = Long
Get: | Long = SpVoice.Volume

Parts

SpVoice
The owning object.
Long
Set: A Long variable that sets the property value.
Get: A Long variable that gets the property value.

Example

The following Visual Basic form code demonstrates the use of the Rate and the Volume properties. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1
  • A VScrollbar called VScroll1
  • An HScrollbar called HScroll1

Paste this code into the Declarations section of the form.

The Form_Load procedure creates a voice object and associates the VScrollbar with the voice's Volume property and the HScrollbar with the voice's Rate property. Adjusting the scroll bars changes the settings of the Volume and Rate properties. The Command1_Click procedure speaks a phrase in order to demonstrate the effects of the changes.

Option Explicit

Private V As SpeechLib.SpVoice

Private Sub Command1_Click()
    V.Speak "The quick brown fox jumped over the lazy dog.", SVSFlagsAsync
End Sub

Private Sub Form_Load()

    Set V = New SpeechLib.SpVoice

    VScroll1.Min = 0
    VScroll1.Max = 100
    VScroll1.Value = V.Volume

    HScroll1.Min = -10
    HScroll1.Max = 10
    HScroll1.Value = V.Rate

    Text1.Text = "Vol: " & VScroll1.Value & ";  Rate: " & HScroll1.Value

End Sub

Private Sub HScroll1_Change()
    V.Rate = HScroll1.Value
    Text1.Text = "Vol: " & VScroll1.Value & ";  Rate: " & HScroll1.Value
End Sub

Private Sub VScroll1_Change()
    V.Volume = VScroll1.Value
    Text1.Text = "Vol: " & VScroll1.Value & ";  Rate: " & HScroll1.Value
End Sub


SpVoice WaitUntilDone method (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice

WaitUntilDone Method

The WaitUntilDone method blocks the caller until either the voice has finished speaking or the specified time interval has elapsed.

The purpose of this method is to block application execution while a voice is speaking asynchronously. The effect of performing a single WaitUntilDone call following a Speak or SpeakStream call is similar to performing those calls synchronously. But the WaitUntilDone method can be used in conjunction with the DoEvents statement to block an application's forward progress while allowing it to receive events. This is demonstrated in the example below.

SpVoice.WaitUntilDone(
     msTimeout As Long
) As Boolean

Parameters

msTimeout
Specifies the timeout in milliseconds. If -1, the time interval is ignored and the method simply waits for the voice to finish speaking.

Return Value

A Boolean variable indicating which case terminated the call. If True, the voice finished speaking; if False, the time interval elapsed.

Example

The following Visual Basic form code demonstrates the use of the WaitUntilDone method. To run this code, create a form with the following controls:

  • Three picture controls called Picture1, Picture2, and Picture3
  • Three command buttons called Command, Command2, and Command3

Paste this code into the Declarations section of the form.

The three picture controls have MouseMove event procedures which change their background colors when the mouse is moved over them. The Form_MouseMove event procedure resets the picture controls to a white background. Moving the mouse across the pictures will cause each to change color for as long as the mouse is over it.

The three command button procedures are similar. Each procedure disables all the command buttons, causes a text-to-speech (TTS) voice to speak a short phrase, and enables all command buttons when the voice finishes speaking. There is no significance to disabling and enabling the buttons except to show the duration of the speech.

Click the Command1 button to cause the voice to speak synchronously. Moving the mouse over the three picture controls will not cause them to change colors; the MouseMove events are blocked by the synchronous Speak call.

Click the Command2 button to cause the voice to speak asynchronously. The WaitUntilDone call prevents the Command2 procedure from ending before the voice is finished. Moving the mouse over the three picture controls will not cause them to change colors; the MouseMove events are blocked by the WaitUntilDone call.

Click the Command3 button to cause the voice to speak asynchronously. The WaitUntilDone method is called inside a loop which also contains a DoEvents statement. This loop prevents the Command3 procedure from ending before the voice is finished, and also allows MouseMove events to be received by the form. As a result, moving the mouse over the three picture controls causes them to change colors while the voice is speaking.

Option Explicit

Const INFINITE = -1&                'Tells WaitUntilDone to wait forever

Dim V As SpeechLib.SpVoice

Private Sub Command1_Click()
                                    'Speak synchronously
    Call EnableButtons(False)       'Disable buttons while voice speaks

    V.Speak "Please move the mouse over the picture controls" _
            & " while i speak synchronously."

    Call EnableButtons(True)        'Enable buttons when voice is done

End Sub

Private Sub Command2_Click()
                                    'Speak asynchronously
    Call EnableButtons(False)       'Disable buttons while voice speaks

    V.Speak "Please move the mouse over the picture controls" _
            & " while i speak with a single Wait Until Done", _
            SVSFlagsAsync

    V.WaitUntilDone (INFINITE)
    Call EnableButtons(True)        'Enable buttons when voice is done

End Sub

Private Sub Command3_Click()
                                    'Speak asynchronously

    Call EnableButtons(False)       'Disable buttons while voice speaks

    V.Speak "Please move the mouse over the picture controls" _
            & " while i speak with a smart loop.", _
            SVSFlagsAsync
    Do                              'Smart loop
        DoEvents                    'DoEvents lets events happen
    Loop Until V.WaitUntilDone(10)  'Loop until voice finishes

    Call EnableButtons(True)        'Enable buttons when voice is done

End Sub

Private Sub Form_Load()
    Set V = New SpVoice
    V.Speak "Please move the mouse over the picture controls" _
            & " before clicking the buttons", _
            SVSFlagsAsync
End Sub

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, _
                                                X As Single, Y As Single)
    Picture1.BackColor = vbWhite
    Picture2.BackColor = vbWhite
    Picture3.BackColor = vbWhite
End Sub

Private Sub Picture1_MouseMove(Button As Integer, Shift As Integer, _
                                                X As Single, Y As Single)
    Picture1.BackColor = vbRed
End Sub

Private Sub Picture2_MouseMove(Button As Integer, Shift As Integer, _
                                                X As Single, Y As Single)
    Picture2.BackColor = vbGreen
End Sub

Private Sub Picture3_MouseMove(Button As Integer, Shift As Integer, _
                                                X As Single, Y As Single)
    Picture3.BackColor = vbBlue
End Sub

Private Sub EnableButtons(TrueFalse As Boolean)
    Command1.Enabled = TrueFalse
    Command2.Enabled = TrueFalse
    Command3.Enabled = TrueFalse
End Sub


SpVoice (Events) Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpVoice (Events)

The SpVoice (Events) automation object defines the types of events that can be received by an SpVoice object from a text-to-speech (TTS) engine.

In order to understand voice events, it is necessary to distinguish between the TTS engine, which synthesizes speech from text, and the SpVoice object, which applications employ to communicate with the engine. The TTS engine is somewhat like a server, and the SpVoice object like a client. The voice object sends the engine a request to speak a string of text. The engine processes the request as soon as it can. The interval between a speech request and the production of the speech is unpredictable. SpVoice events overcome this difficulty by providing applications with real-time feedback from the engine as it speaks, making it possible to synchronize application functions with speech. For example, an application can use a voice object's Viseme event to drive animations that display mouth movements as the engine speaks.

The voice object initiates requests with the Speak and SpeakStream methods, which send text strings and audio files to the TTS engine. These methods can be called synchronously or asynchronously. Because a synchronous speech request suspends execution of the calling application while the engine speaks the stream, events from the speaking of the stream are received after the stream has been spoken. Applications which need to receive events as real-time feedback should use asynchronous Speak and SpeakStream calls.

Examples of voice events are the beginning and the end of a text stream, and the boundaries of visemes, phonemes, words, and sentences. The SpeechVoiceEvents enumeration defines a constant for each type of voice event. Use one or more SpeechVoiceEvents constants to set the EventInterests property of a voice object. Only the types of events specified by EventInterests property will be sent by the TTS engine. The default setting of this property specifies all voice event types except AudioLevel.

When using Visual Basic, you must use the "WithEvents" keyword to define an SpVoice object which receives events.

Events in file streams

When a voice object speaks into a filestream object, the TTS engine will embed event data in the file stream if all the following conditions are true:

  • The voice object is defined using the "WithEvents" keyword
  • The voice object's EventInterests property specifies at least one event type
  • The audio output contains event conditions of a type specified in the voice's EventInterests
  • The filestream object is opened for writing with its "DoEvents" parameter True

When TTS engine speaks a filestream object which contains embedded events, it will send events to the voice if all the following conditions are true:

  • The voice object is defined using the "WithEvents" keyword
  • The voice object's EventInterests property specifies at least one event type
  • The file stream contains an embedded event of a type specified in the voice's EventInterests
  • The filestream object is opened for reading with its "DoEvents" parameter True

When the TTS engine speaks a filestream object for a voice, if the voice's EventInterests specify StartStream and EndStream events, the engine will send it a StartStream and an EndStream event, even if these events are not embedded in the stream. If StartStream and EndStream events are embedded in that file stream, the engine will send the voice two StartStream events and two EndStream events.

Automation Interfaces

The SpVoice (Events) automation object has the following elements:

Events | Description
AudioLevel Event | Occurs when the TTS engine detects an audio level change while speaking a stream for the SpVoice object.
Bookmark Event | Occurs when the TTS engine detects a bookmark while speaking a stream for the SpVoice object.
EndStream Event | Occurs when the TTS engine reaches the end of a stream it is speaking for the SpVoice object.
EnginePrivate Event | Occurs when a private TTS engine detects a custom event condition boundary while speaking a stream for the SpVoice object.
Phoneme Event | Occurs when the TTS engine detects a phoneme boundary while speaking a stream for the SpVoice object.
Sentence Event | Occurs when the TTS engine detects a sentence boundary while speaking a stream for the SpVoice object.
StartStream Event | Occurs when the TTS engine begins speaking a stream for the SpVoice object.
Viseme Event | Occurs when the TTS engine detects a viseme boundary while speaking a stream for the SpVoice object.
VoiceChange Event | Occurs when the TTS engine detects a change of voice while speaking a stream for the SpVoice object.
Word Event | Occurs when the TTS engine detects a word boundary while speaking a stream for the SpVoice object.


SpVoice AudioLevel event (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice (Events)

AudioLevel Event

The AudioLevel event occurs when the text-to-speech (TTS) engine detects an audio level change while speaking a stream for the SpVoice object.

SpVoice.AudioLevel(
     StreamNumber As Long,
     StreamPosition As Variant,
     AudioLevel As Long
)

Parameters

StreamNumber
The stream number which generated the event. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate an event with the appropriate stream.
StreamPosition
The character position in the output stream at which the audio level change occurs.
AudioLevel
The new audio level.

Example

The following Visual Basic form code demonstrates the use of the AudioLevel event. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1
  • A list box called List1

Paste this code into the Declarations section of the form.

The Form_Load code creates an SpVoice object, adds AudioLevel to its event interests, and places sample text in Text1. The Command1_Click procedure speaks the text in Text1. The Word event code displays each word spoken. The AudioLevel event code converts each new audio level to a string of asterisks, effectively displaying the audio levels in a graph format.

Option Explicit

Public WithEvents vox As SpeechLib.SpVoice

Private Sub Command1_Click()
    List1.Clear
    vox.Speak Text1.Text, SVSFlagsAsync + SVSFIsXML
End Sub

Private Sub Form_Load()

    ' SVEAudioLevel not in default EventInterests -- must be added!

    Set vox = New SpVoice
    vox.EventInterests = vox.EventInterests Or SVEAudioLevel
    Text1.Text = "audio levels change often"

End Sub

Private Sub vox_AudioLevel(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, _
                           ByVal AudioLevel As Long)

    List1.AddItem String(AudioLevel, "*")   'AudioLevel value sets length of string

End Sub

Private Sub vox_Word(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, _
                     ByVal CharacterPosition As Long, ByVal Length As Long)

    List1.AddItem Mid(Text1.Text, CharacterPosition + 1, Length)

End Sub


SpVoice Bookmark event (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice (Events)

Bookmark Event

The Bookmark event occurs when the text-to-speech (TTS) engine detects a bookmark while speaking a stream for the SpVoice object.

It should be noted that Bookmark events may not be synchronized with the actual speaking of the words in text streams containing bookmarks. In some circumstances, TTS buffering considerations may cause a Bookmark event to be received sooner than the voice speaks the word preceding the bookmark in the text stream.

SpVoice.Bookmark(
     StreamNumber As Long,
     StreamPosition As Variant,
     Bookmark As String,
     BookmarkId As Long
)

Parameters

StreamNumber
The stream number which generated the event. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate an event with the appropriate stream.
StreamPosition
The character position in the output stream at which the bookmark occurs.
Bookmark
The string value of the Mark attribute within the bookmark.
BookmarkId
The string value of the leading (left-most) numeric characters in the Mark attribute within the bookmark.

Example

The following Visual Basic form code demonstrates the use of the Bookmark event. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1

Paste this code into the Declarations section of the form.

The Form_Load code creates an SpVoice object. The Command1_Click procedure enqueues a short sentence containing a bookmark. The Bookmark event code displays the values of the BookmarkId and Bookmark parameters in Text1.

Option Explicit

Public WithEvents vox As SpeechLib.SpVoice

Private Sub Command1_Click()

    Dim strTemp As String
    strTemp = "this is text <BOOKMARK mark='123456.789 abcdefg' /> with a bookmark."
    vox.Speak strTemp, SVSFlagsAsync + SVSFIsXML

End Sub

Private Sub Form_Load()
    Set vox = New SpVoice
End Sub

Private Sub vox_Bookmark(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, _
                         ByVal Bookmark As String, ByVal BookmarkId As Long)

    Text1.Text = "BookmarkId: """ & BookmarkId & """, Bookmark: """ & Bookmark & """"

End Sub


SpVoice EndStream event (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice (Events)

EndStream Event

The EndStream event occurs when the text-to-speech (TTS) engine reaches the end of a stream while speaking for the SpVoice object.

The StartStream and EndStream events can be used together to determine the duration of a stream being spoken.

SpVoice.EndStream(
     StreamNumber As Long,
     StreamPosition As Variant
)

Parameters

StreamNumber
The stream number which generated the event. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate an event with the appropriate stream.
StreamPosition
The ending character position in the output stream.

Example

The following Visual Basic form code demonstrates the use of the StartStream and EndStream events. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1

Paste this code into the Declarations section of the form.

The Form_Load procedure puts a text string in Text1 and creates a voice object. The command1_Click procedure calls the Speak method. This will cause the TTS engine to send the EStream event and EndStream events to the voice. The StartStream event code changes the color of the text in the text box to red; the EndStream event changes the color back to black.

The text color change in this example has no significance other than showing the duration of the text stream.

Option Explicit

Public WithEvents vox As SpeechLib.SpVoice

Private Sub Command1_Click()
    vox.Speak Text1.Text, SVSFlagsAsync
End Sub

Private Sub Form_Load()
    Set vox = New SpVoice
    Text1.Text = "This text turns red while being spoken."
End Sub

Private Sub vox_EndStream(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Text1.ForeColor = vbBlack
End Sub

Private Sub vox_StartStream(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Text1.ForeColor = vbRed
End Sub


SpVoice EnginePrivate event (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice (Events)

EnginePrivate Event

The EnginePrivate event occurs when a private text-to-speech (TTS) engine detects a custom event condition boundary while speaking a stream for the SpVoice object.

A private event is a custom event defined by the TTS engine. This event allows engines to define a specialized event beyond the standard suite of events and send custom events to SpVoice objects as though they were standard events. There is no requirement that engines support this event. The SAPI 5 Microsoft engines do not use the EnginePrivate event. If using another manufacturer's engine, check their documentation for possible implementation of this event.

SpVoice.EnginePrivate(
     StreamNumber As Long,
     StreamPosition As Long,
     EngineData As Variant
)

Parameters

StreamNumber
The stream number which generated the event. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate an event with the appropriate stream.
StreamPosition
The character position in the output stream at which the private event occurs.
EngineData
Data returned by the engine with the event. When using another manufacturer's TTS engine, consult its documentation for details.

Example

No sample code is available. The event is unique to manufacturer's engines and will vary among engines. The SAPI 5 Microsoft engines do not use the EnginePrivate event.


SpVoice Phoneme event (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice (Events)

Phoneme Event

The Phoneme event occurs when the text-to-speech (TTS) engine detects a phoneme boundary while speaking a stream for the SpVoice object.

SpVoice.Phoneme(
     StreamNumber As Long,
     StreamPosition As Variant,
     Duration As Long,
     NextPhoneId As Integer,
     Feature As SpeechVisemeFeature,
     CurrentPhoneId As Integer
)

Parameters

StreamNumber
The stream number which generated the event. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate an event with the appropriate stream.
StreamPosition
The character position in the output stream at which the phoneme begins.
Duration
The duration of the phoneme, in milliseconds.
NextPhoneId
The next phone ID.
Feature
The SpeechVisemeFeature, which may indicate emphasis or stress on the viseme.
CurrentPhoneId
The current phone ID.

Remarks

Depending on the language, a TTS engine may return a SAPI ID or a Universal Phone Set (UPS) ID when it encounters a phoneme. To determine which phone set (phonetic alphabet) that a synthesis engine is using to create pronunciations, use the ISpPhoneticAlphabetSelection::IsAlphabetUPS method.

When the engine synthesizes a phoneme comprised of more than one phoneme element, it raises an event for each element. For example, when a Japanese TTS engine speaks the phoneme "KYA," which is comprised of the phoneme elements "KI" and "XYA," it raises an SPEI_PHONEME event for each element. Because the element "KI" in this case modifies the sound of the element following it, rather than initiating a sound, the duration of its SPEI_PHONEME event is zero.

Example

The following Visual Basic form code demonstrates the Phoneme event. To run this code, create a form with the following controls:

  • A command button called Command1
  • Two text boxes called Text1 and Text2

Paste this code into the Declarations section of the form.

The Form_Load procedure puts a text string in Text1 and creates a voice object, leaving all its properties with their default settings. The command1_Click procedure calls the Speak method. This will cause the TTS engine to send the Phoneme event to the voice; the Phoneme event code will display the phoneme values in Text2.

Option Explicit

Public WithEvents vox As SpeechLib.SpVoice

Private Sub Command1_Click()

    vox.Speak Text1.Text, SVSFlagsAsync

End Sub

Private Sub Form_Load()

    Set vox = New SpVoice
    Text1.Text = "This is text in a text box."

End Sub

Private Sub vox_Phoneme(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal Duration As Long, ByVal NextPhoneId As Integer, ByVal Feature As SpeechLib.SpeechVisemeFeature, ByVal CurrentPhoneId As Integer)

    Text2.Text = Text2.Text & CurrentPhoneId & " "

End Sub


SpVoice Sentence event (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice (Events)

Sentence Event

The Sentence event when the text-to-speech (TTS) engine detects a sentence boundary while speaking a stream for the SpVoice object.

SpVoice.Sentence(
     StreamNumber As Long,
     StreamPosition As Variant,
     CharacterPosition As Long,
     Length As Long
)

Parameters

StreamNumber
The stream number which generated the event. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate an event with the appropriate stream.
StreamPosition
The character position in the output stream at which the sentence begins.
CharacterPosition
The character position in the input stream one character before the start of the sentence. In the case of the first sentence in a stream, this parameter is zero.
Length
The length of the sentence.

Example

The following Visual Basic form code demonstrates the use of the Sentence event. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1
  • Set the HideSelection property of Text1 to False

Paste this code into the Declarations section of the form.

The Form_Load procedure puts a text string in Text1 and creates a voice object. The command1_Click procedure calls the Speak method. This will cause the TTS engine to send the Sentence event to the voice. The Sentence event code uses the event parameters to highlight the sentence associated with the event.

Option Explicit

Public WithEvents vox As SpeechLib.SpVoice

Private Sub Command1_Click()

    vox.Speak Text1.Text, SVSFlagsAsync

End Sub

Private Sub Form_Load()

    Set vox = New SpVoice
    Text1.Text = "a short sentence. another sentence. one more."

End Sub

Private Sub vox_Sentence(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, _
                         ByVal CharacterPosition As Long, ByVal Length As Long)

    ' In order to show this selection,
    ' the Text1.HideSelection property must be False

    Text1.SelStart = CharacterPosition
    Text1.SelLength = Length

End Sub


SpVoice StartStream event (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice (Events)

StartStream Event

The StartStream event occurs when the text-to-speech (TTS) engine begins speaking a stream for the SpVoice object.

The StartStream and EndStream events can be used together to determine the duration of a stream being spoken.

SpVoice.StartStream(
     StreamNumber As Long,
     StreamPosition As Variant
)

Parameters

StreamNumber
The stream number which generated the event. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate an event with the appropriate stream.
StreamPosition
The character position in the output stream at which the stream begins.

Example

The following Visual Basic form code demonstrates the use of the StartStream and EndStream events. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1

Paste this code into the Declarations section of the form.

The Form_Load procedure puts a text string in Text1 and creates a voice object. The command1_Click procedure calls the Speak method. This will cause the TTS engine to send the StartStream and EndStream events to the voice. The StartStream event code changes the color of the text in the text box to red; the EndStream event changes the color back to black.

The text color change in this example has no significance other than showing the duration of the text stream.

Option Explicit

Public WithEvents vox As SpeechLib.SpVoice

Private Sub Command1_Click()
    vox.Speak Text1.Text, SVSFlagsAsync
End Sub

Private Sub Form_Load()
    Set vox = New SpVoice
    Text1.Text = "This text turns red while being spoken."
End Sub

Private Sub vox_EndStream(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Text1.ForeColor = vbBlack
End Sub

Private Sub vox_StartStream(ByVal StreamNumber As Long, ByVal StreamPosition As Variant)
    Text1.ForeColor = vbRed
End Sub


SpVoice Viseme event (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice (Events)

Viseme Event

The Viseme event occurs when the text-to-speech (TTS) engine detects a viseme boundary while speaking a stream for the SpVoice object.

SpVoice.Viseme(
     StreamNumber As Long,
     StreamPosition As Variant,
     Duration As Long,
     NextVisemeId As SpeechVisemeType,
     Feature As SpeechVisemeFeature,
     CurrentVisemeId As SpeechVisemeType
)

Parameters

StreamNumber
The stream number which generated the event. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate an event with the appropriate stream.
StreamPosition
The character position in the output stream at which the viseme begins.
Duration
The duration of the viseme state.
NextVisemeId
The next viseme ID.
Feature
The SpeechVisemeFeature, which may indicate emphasis or stress on the viseme.
CurrentVisemeId
The current viseme ID.

Example

The following Visual Basic form code demonstrates the Viseme event. To run this code, create a form with the following controls:

  • A command button called Command1
  • Two text boxes called Text1 and Text2

Paste this code into the Declarations section of the form.

The Form_Load procedure puts a text string in Text1 and creates a voice object. The command1_Click procedure calls the Speak method. This will cause the TTS engine to send the Viseme event to the voice. The Viseme event code will display the viseme values in Text2.

Option Explicit

Public WithEvents vox As SpeechLib.SpVoice

Private Sub Command1_Click()

    vox.Speak Text1.Text, SVSFlagsAsync

End Sub

Private Sub Form_Load()

    Set vox = New SpVoice
    Text1.Text = "This is text in a text box."

End Sub

Private Sub vox_Viseme(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal Duration As Long, ByVal NextVisemeId As SpeechLib.SpeechVisemeType, ByVal Feature As SpeechLib.SpeechVisemeFeature, ByVal CurrentVisemeId As SpeechLib.SpeechVisemeType)

    Text2.Text = Text2.Text & CurrentVisemeId & " "

End Sub


SpVoice VoiceChange event (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice (Events)

VoiceChange Event

The VoiceChange event occurs when the text-to-speech (TTS) engine detects a change of voice while speaking a stream for the SpVoice object.

SpVoice.VoiceChange(
     StreamNumber As Long,
     StreamPosition As Variant,
     VoiceObjectToken As SpObjectToken
)

Parameters

StreamNumber
The stream number which generated the event. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate an event with the appropriate stream.
StreamPosition
The character position in the output stream at which the change of voice occurs.
VoiceObjectToken
The ObjectToken of the new voice.

Example

The following Visual Basic form code demonstrates the use of the VoiceChange event. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1

Paste this code into the Declarations section of the form.

The Form_Load code creates an SpVoice object. The Command1_Click procedure sets the object's Voice property to three different voices, and enqueues a short sentence in each voice. Each time the TTS engine speaks with a new Voice property, a VoiceChange event is raised. The VoiceChange event code displays the name of the new voice in Text1.

Option Explicit

Public WithEvents vox As SpeechLib.SpVoice
Const cstrText = "my voice just changed."

Private Sub Command1_Click()

    Set vox.voice = vox.GetVoices("name = microsoft mary").Item(0)
    vox.Speak cstrText, SVSFlagsAsync

    Set vox.voice = vox.GetVoices("name = microsoft mike").Item(0)
    vox.Speak cstrText, SVSFlagsAsync

    Set vox.voice = vox.GetVoices("name = microsoft sam").Item(0)
    vox.Speak cstrText, SVSFlagsAsync

End Sub

Private Sub Form_Load()

    Set vox = New SpVoice

End Sub

Private Sub vox_VoiceChange(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, _
                            ByVal VoiceObjectToken As SpeechLib.ISpeechObjectToken)

    Text1.Text = VoiceObjectToken.GetDescription

End Sub


SpVoice Word event (Microsoft Speech Platform)

 Microsoft Speech Platform

Object: SpVoice (Events)

Word Event

The Word event occurs when the text-to-speech (TTS) engine detects a word boundary while speaking a stream for the SpVoice object.

SpVoice.Word(
     StreamNumber As Long,
     StreamPosition As Variant,
     CharacterPosition As Long,
     Length As Long
)

Parameters

StreamNumber
The stream number which generated the event. When a voice enqueues more than one stream by speaking asynchronously, the stream number is necessary to associate an event with the appropriate stream.
StreamPosition
The character position in the output stream at which the word begins.
CharacterPosition
The character position in the input stream one character before the start of the word. In the case of the first word in a stream, this parameter is zero.
Length
The length of the word in the input stream.

Example

The following Visual Basic form code demonstrates the use of the Word event. To run this code, create a form with the following controls:

  • A command button called Command1
  • A text box called Text1
  • Set the HideSelection property of Text1 to False

Paste this code into the Declarations section of the form.

The Form_Load procedure puts a text string in Text1 and creates a voice object. The command1_Click procedure calls the Speak method. This will cause the TTS engine to send the Word event to the voice; the Word event code will use the event parameters to highlight the word associated with the event.

Option Explicit

Public WithEvents vox As SpeechLib.SpVoice

Private Sub Command1_Click()

    vox.Speak Text1.Text, SVSFlagsAsync

End Sub

Private Sub Form_Load()

    Set vox = New SpVoice
    Text1.Text = "This is some text in a textbox."

End Sub

Private Sub vox_Word(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, _
                     ByVal CharacterPosition As Long, ByVal Length As Long)

    ' In order to show this selection,
    ' the Text1.HideSelection property must be False!

    Text1.SelStart = CharacterPosition
    Text1.SelLength = Length

End Sub


SpWaveFormatEx Interface (Microsoft Speech Platform)

 Microsoft Speech Platform

SpWaveFormatEx

The SpWaveFormatEx automation object represents the format of waveform-audio data.

The SpWaveFormatEx object gets and sets the audio format property of the SpAudioFormat object. Please see a code example in the SpAudioFormat GetWaveFormatEx section.

Automation Interface Elements

The SpWaveFormatEx automation object has the following elements:

Properties | Description
AvgBytesPerSec Property | Gets and sets the required average data-transfer rate for the format tag in bytes per second.
BitsPerSample Property | Gets and sets the bits per sample for the FormatTag format type.
BlockAlign Property | Gets and sets the block alignment in bytes.
Channels Property | Gets and sets the number of channels in the waveform-audio data.
ExtraData Property | Gets and sets extra format information.
FormatTag Property | Gets and sets the waveform-audio format type.
SamplesPerSec Property | Gets and sets the sample rate at which each channel should be played or recorded.


SpWaveFormatEx AvgBytesPerSec property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpWaveFormatEx

AvgBytesPerSec Property

The AvgBytesPerSec property gets and sets the required average data-transfer rate for the format tag in bytes per second.

If the FormatTag property is WAVE_FORMAT_PCM, AvgBytesPerSec should be equal to the product of SamplesPerSec and BlockAlign. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

Playback and record software can estimate buffer sizes using the AvgBytesPerSec member.

Syntax

Set: | SpWaveFormatEx.AvgBytesPerSec = Long
Get: | Long = SpWaveFormatEx.AvgBytesPerSec

Parts

SpWaveFormatEx
The owning object.
Long
Set: A Long variable that sets the property.
Get: A Long variable that gets the property.

Example

For an example of the use of the AvgBytesPerSec property, see the code example in the SpAudioFormat GetWaveFormatEx section.


SpWaveFormatEx BitsPerSample property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpWaveFormatEx

BitsPerSample Property

The BitsPerSample property gets and sets the bits per sample for the FormatTag format type.

If FormatTag is WAVE_FORMAT_PCM, BitsPerSample should be equal to 8 or 16. For non-PCM formats, this member must be set according to the manufacturer's specification of the format tag.

Note that some compression schemes cannot define a value for BitsPerSample, so this member can be zero.

Syntax

Set: | SpWaveFormatEx.BitsPerSample = Integer
Get: | Integer = SpWaveFormatEx.BitsPerSample

Parts

SpWaveFormatEx
The owning object.
Integer
Set: An Integer variable that sets the property.
Get: An Integer variable that gets the property.

Example

For an example of the use of the BitsPerSample property, see the code example in the SpAudioFormat GetWaveFormatEx section.


SpWaveFormatEx BlockAlign property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpWaveFormatEx

BlockAlign Property

The BlockAlign property gets and sets the block alignment in bytes.

Syntax

Set: | SpWaveFormatEx.BlockAlign = Integer
Get: | Integer = SpWaveFormatEx.BlockAlign

Parts

SpWaveFormatEx
The owning object.
Integer
Set: An Integer variable that sets the property.
Get: An Integer variable that gets the property.

Remarks

The block alignment is the minimum atomic unit of data for the FormatTag format type. If the FormatTag is WAVE_FORMAT_PCM, BlockAlign should be equal to the product of Channels and BitsPerSample divided by 8 (bits per byte). For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

Playback and record software handles audio data in blocks. The sizes of these blocks are multiples of the value of the BlockAlign property. Data written and read from a device must always start at the beginning of a block. For example, it is illegal to start playback of PCM data in the middle of a sample (that is, on a non-block-aligned boundary).

Example

For an example of the use of the BlockAlign property, see the code example in the SpAudioFormat GetWaveFormatEx section.


SpWaveFormatEx Channels property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpWaveFormatEx

Channels Property

The Channels property gets and sets the number of channels in the waveform-audio data.

Monaural data uses one channel and stereo data uses two channels.

Syntax

Set: | SpWaveFormatEx.Channels = Integer
Get: | Integer = SpWaveFormatEx.Channels

Parts

SpWaveFormatEx
The owning object.
Integer
Set: An Integer variable that sets the property.
Get: An Integer variable that gets the property.

Example

For an example of the use of the Channels property, see the code example in the SpAudioFormat GetWaveFormatEx section.


SpWaveFormatEx ExtraData property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpWaveFormatEx

ExtraData Property

The ExtraData property gets and sets extra format information.

This information can be used by non-PCM formats to store extra attributes for the FormatTag property. For WAVE_FORMAT_PCM formats, this parameter is ignored.

Syntax

Set: | SpWaveFormatEx.ExtraData = Variant
Get: | Variant = SpWaveFormatEx.ExtraData

Parts

SpWaveFormatEx
The owning object.
Variant
Set: A Variant variable that sets the property.
Get: A Variant variable that gets the property.

Example

For an example of the use of the ExtraData property, see the code example in the SpAudioFormat GetWaveFormatEx section.


SpWaveFormatEx FormatTag property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpWaveFormatEx

FormatTag Property

The FormatTag property gets and sets the waveform-audio format type.

Format tags are registered with Microsoft Corporation for many compression algorithms. A complete list of format tags is located in the Mmsystem.h header file.

Syntax

Set: | SpWaveFormatEx.FormatTag = Integer
Get: | Integer = SpWaveFormatEx.FormatTag

Parts

SpWaveFormatEx
The owning object.
Integer
Set: An Integer variable that sets the property.
Get: An Integer variable that gets the property.

Example

For an example of the use of the FormatTag property, see the code example in the SpAudioFormat GetWaveFormatEx section.


SpWaveFormatEx SamplesPerSec property (Microsoft Speech Platform)

Microsoft Speech Platform

Object: SpWaveFormatEx

SamplesPerSec Property

The SamplesPerSec property gets and sets the sample rate at which each channel should be played or recorded.

If FormatTag is WAVE_FORMAT_PCM, common values for SamplesPerSec are 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

Syntax

Set: | SpWaveFormatEx.SamplesPerSec = Long
Get: | Long = SpWaveFormatEx.SamplesPerSec

Parts

SpWaveFormatEx
The owning object.
Long
Set: A Long variable that sets the property.
Get: A Long variable that gets the property.

Example

For an example of the use of the SamplesPerSec property, see the code example in the SpAudioFormat GetWaveFormatEx section.


Legal Information (Speech SDK Tools)

[image]

Legal Information (Speech SDK Tools)
Send Feedback

This document is provided "as-is". Information and views expressed in this document, including URL and other Internet Web site references, may change without notice. You bear the risk of using it.

Some examples depicted herein are provided for illustration only and are fictitious. No real association or connection is intended or should be inferred.

This document does not provide you with any legal rights to any intellectual property in any Microsoft product. You may copy and use this document for your internal, reference purposes. You may modify this document for your internal, reference purposes.

© 2011 Microsoft. All rights reserved.

Microsoft, Active Directory, DirectX, Expression Blend, Internet Explorer, MS-DOS, MSN, Outlook, SharePoint, Silverlight, Visual Basic, Visual C#, Visual C++, Visual Studio, Win32, Windows, Windows Media, Windows Server, and Windows Vista are trademarks of the Microsoft group of companies. All other trademarks are property of their respective owners.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Legal Information (VoiceXML Support)

[image]

Legal Information (VoiceXML Support)
Send Feedback

This document is provided "as-is". Information and views expressed in this document, including URL and other Internet Web site references, may change without notice. You bear the risk of using it.

Some examples depicted herein are provided for illustration only and are fictitious. No real association or connection is intended or should be inferred.

This document does not provide you with any legal rights to any intellectual property in any Microsoft product. You may copy and use this document for your internal, reference purposes. You may modify this document for your internal, reference purposes.

© 2011 Microsoft. All rights reserved.

Microsoft, Active Directory, DirectX, Expression Blend, Internet Explorer, MS-DOS, MSN, Outlook, SharePoint, Silverlight, Visual Basic, Visual C#, Visual C++, Visual Studio, Win32, Windows, Windows Media, Windows Server, and Windows Vista are trademarks of the Microsoft group of companies. All other trademarks are property of their respective owners.

© 2011 Microsoft Corporation. All rights reserved. | For the latest news and documentation, visit Speech Technologies on MSDN.


Enumerations (Microsoft Speech Platform)

 Microsoft Speech Platform

Global Variables

The following variables and constants are of special importance to SAPI developers.

  • Other Global Constants


ISpEnginePronunciation (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpEnginePronunciation

New in SAPI 5.3

Provides methods that retrieve lists of information about a given word in a dictionary.

Methods in Vtable Order

ISpEnginePronunciation Methods | Description
Normalize | Returns the list of normalized forms for a word.
GetPronunciations | Returns all the pronunciations the engine knows about for a given word.


ISpEnginePronunciation::GetPronunciations (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpEnginePronunciation::GetPronunciations

ISpEnginePronunciation::GetPronunciations returns all of the pronunciations the engine knows about for a given word.

HRESULT GetPronunciations(
   LPCWSTR                    *pszWord,
   LPCWSTR                     pszLeftContext,
   LPCWSTR                     pszRightContext,
   LANGID                      LangID,
   SPWORDPRONUNCIATIONLIST    *pEnginePronunciationList
);

Parameters

pszWord
[in] The word or term for which a pronunciation is desired (for example, "record"). This is case sensitive.
pszLeftContext
[in] The left portion of a sentence or phrase in which pszWord is used. See the Remarks section below for more information.
pszRightContext
[in] The right portion of a sentence or phrase in which pszWord is used. See the Remarks section below for more information.
LangID
[in] The ID of the language. This parameter is useful if an engine supports multiple languages. To use the engine's default language, set the ID to 0.
pEnginePronunciationList
[out] Returns a list of pronunciations. The application must allocate the SPWORDPRONUNCIATIONLIST structure that pEnginePronunciationList points to. The engine will allocate the space for the pronunciation list itself and provide a pointer to it in pEnginePronunciationList->pvBuffer. The application is responsible for calling CoTaskMemFree() on pEnginePronunciationList->pvBuffer to release the allocation.

Return values

Value | Description
S_OK | Function completed successfully.
S_NEEDSNORMALIZATION | Indicates that the word in pszWord needs to be normalized before pronunciations can be provided. All values in pEnginePronunciationList will be set to 0.
S_NEEDSWORDBREAK | Indicates that pszWord contains multiple words. The application should call Normalize to break it into individual words and then call GetPronunciation again with the specific word of interest.
S_NOTSUPPORTED | Indicates that the engine will not provide pronunciation for the given input. All values in pEnginePronunciationList will be set to 0.

Remarks

The pszLeftContext and pszRightContextparameters are always case sensitive and either of them can be set to null, in which case the engine ignores the parameter. In addition, the engine may ignore any context string.

Some engines (generally TTS) select pronunciations based on the context in which a word is used. The following table lists two examples of selected pronounciations based on context:

pszWord | pszLeftContext | pszRightContext
"record" | null | "your message"
"record" | "the hottest temperature on" | null


ISpEnginePronunciation::Normalize (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpEnginePronunciation::Normalize

ISpEnginePronunciation::Normalize returns the list of normalized forms for a word. For an example call, see the Remarks section below.

HRESULT Normalize(
   LPCWSTR                *pszWord,
   LPCWSTR                 pszLeftContext,
   LPCWSTR                 pszRightContext,
   LANGID                  LangID,
   SPNORMALIZATIONLIST    *pNormalizationList
);

Parameters

pszWord
[in] The word or term for which normalization is desired (for example, "11.30"). This is case sensitive because the case may have a bearing on normalization. For example, "cat" is always "cat", but "CAT" may also be "C. A. T."; "lea" is always "lea", but may also be "Lea".
pszLeftContext
[in] The left portion of a sentence or phrase in which pszWord is used. See the Remarks section below for more information.
pszRightContext
[in] The right portion of a sentence or phrase in which pszWord is used. See the Remarks section below for more information.
LangID
[in] The ID of the language. This parameter is useful if an engine supports multiple languages. To use the engine's default language, set the ID to 0.
pNormalizationList
[out] Returns a list of alternative normalizations. The application must allocate the SPNORMALIZATIONLIST structure that pNormalizationList points to. The engine will allocate the space for the normalization list itself and provide a pointer to it in pNormalizationList>ppszzNormalizedList. The application is responsible for calling CoTaskMemFree on pNormalizationList>ppszzNormalizedList to release the allocation.

Return values

Value | Description
S_OK | Function completed successfully.
E_INVALIDARG | Indicates that the engine will not provide normalization for the given input and that pNormalizationList will be set to null.
S_LIMITREACHED | Indicates that the returned list is not exhaustive, but contains as many alternatives as the engine is willing to provide.

Remarks

For example, to normalize "XAML" in the string "Developers should use XAML to build Avalon applications", use a statement like the following:

pPron->Normalize("XAML", "Developers should use", "to build Avalon applications", 0, &pListOfNorms);

The pszLeftContext and pszRightContextparameters are always case sensitive and either of them can be set to null, in which case the engine ignores the parameter. In addition, the engine may ignore any context string.

Some engines (generally TTS) select normalizations based on the context in which a word is used. The following table lists one example of a selected normalization based on context:

pszWord | pszLeftContext | pszRightContext
"11.30" | "The time is" | null


ISpThreadTask (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpThreadTask

The ISpThreadTask interface simplifies thread-based operations. Clients can implement this virtual C++ interface to simplify the management of threads. SAPI provides coordination methods for starting, initializing, and stopping the thread. Clients simply implement three methods which will be called on the allocated thread.

When to Implement

Use SpThreadControl objects to allocate threads for an object.

This is not a COM interface.

Methods in Vtable Order

ISpThreadTask Methods | Description
InitThread | Method called on the allocated thread.
ThreadProc | Implements the processing of the thread.
WindowMessage | Implements the processing of window messages.


ISpThreadTask::InitThread (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpThreadTask::InitThread

ISpThreadTask::InitThread is called on the allocated thread.

This method is called on the newly allocated thread.

virtual HRESULT STDMETHODCALLTYPE InitThread(
   void   *pvTaskData,
   HWND    hwnd
) = 0;

Parameters

pvTaskData
[in] The same pointer is passed to ISpTaskManager::CreateThreadControl.
hwnd
[in] A window handle if, and only if, the caller to ISpThreadControl::StartThread specified that a window handle be created by passing a non-NULL HWND pointer to StartThread. Otherwise this parameter is NULL.

Return values

S_OK | Function completed successfully.
Other success | Success code will be returned to caller of the StartThread method and the thread will continue.
Failure code | Function failed. Failure code will be returned to caller of the StartThread method and the thread will not continue.

Remarks

The caller of StartThread method will be blocked until the InitThread method completes, and the HRESULT returned from this method will be returned from StartThread. If the return code from this method indicates failure, the thread will be terminated, and ThreadProc and WindowMessage will never be called.


ISpThreadTask::ThreadProc (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpThreadTask::ThreadProc

ISpThreadTask::ThreadProc implements the main processing loop of the thread. This method will be application specific.

virtual HRESULT STDMETHODCALLTYPE ThreadProc(
   void                 *pvTaskData,
   HANDLE                hExitThreadEvent,
   HANDLE                hNotifyEvent,
   HWND                  hwndWorker,
   volatile const BOOL  *pfContinueProcessing
) = 0;

Parameters

pvTaskData
[in] Pointer passed to ISpTaskManager::CreateThreadControl.
hExitThreadEvent
[in, out] An event handle which when signaled indicates that the thread process should exit.
hNotifyEvent
[in] A handle to an auto-reset event object that will be set if the ISpThreadControl::Notify method is called. This functionality is provided for any notification event the client determines, or it can optionally be ignored if it is not needed.
hwndWorker
[in] A window handle.
pfContinueProcessing
[in] Boolean flag indicating whether to continue processing. TRUE indicates the process should continue; FALSE otherwise. This mirrors the functionality of the hExitThreadEvent, but provides a lightweight mechanism for checking for a request to exit without calling a Win32 WaitForxxx object function.

Return values

S_OK | Function completed successfully.
S_FAILED | Function failed.


ISpThreadTask::WindowMessage (Microsoft Speech Platform)

 Microsoft Speech Platform

ISpThreadTask::WindowMessage

ISpThreadTask::WindowMessage implements the processing of window messages.

virtual LRESULT STDMETHODCALLTYPE WindowMessage(
   void    *pvTaskData,
   HWND     hWnd,
   UINT     Msg,
   WPARAM   wParam,
   LPARAM   lParam
) = 0;

Parameters

pvTaskData
[in] Pointer passed to ISpTaskManager::CreateThreadControl.
hWnd
[in] A window handle.
Msg
[in] The type of window message.
wParam
Message-specific information. This will change based on the Msg value.
lParam
Message-specific information. This will change based on the Msg value.

Return values

The return value is message specific.

Remarks

Not all applications will need a window and this method may be left unimplemented.


SAPI Object classes (Microsoft Speech Platform)

 Microsoft Speech Platform

Microsoft Speech Platform Native Object classes

This section covers the following topics:

  • SAPI Application Object Classes


Japanese Visemes (Microsoft Speech Platform)

Japanese Visemes Draft

Visemes for SAPI Supported Japanese Phonemes (Katakana)

Symbol | Phonetic | Unicode Value | Viseme | Remarks
 |  | 309C |  | Semi-voiced sound
 | a | 30A1 | 2 | Replaces last viseme value of preceding character
 | a | 30A2 | 2 |
 | i | 30A3 | 6 | Replaces last viseme value of preceding character
 | i | 30A4 | 6 |
 | u | 30A5 | 7 |
 | u | 30A6 | 7 |
 | e | 30A7 | 4 | Replaces last viseme value of preceding character
 | e | 30A8 | 4 |
 | o | 30A9 | 8 | Replaces last viseme value of preceding character
 | o | 30AA | 8 |
 | ka | 30AB | 20,2 |
 | ga | 30AC | 20,2 |
 | ki | 30AD | 20,6 |
 | gi | 30AE | 20,6 |
 | ku | 30AF | 20,7 |
 | gu | 30B0 | 20,7 |
 | ke | 30B1 | 20,4 |
 | ge | 30B2 | 20,4 |
 | ko | 30B3 | 20,8 |
 | go | 30B4 | 20,8 |
 | sa | 30B5 | 15,2 |
 | za | 30B6 | 15,2 |
 | shi | 30B7 | 15,6 |
 | ji | 30B8 | 16,6 |
 | su | 30B9 | 15,7 |
 | zu | 30BA | 15,7 |
 | se | 30BB | 15,4 |
 | ze | 30BC | 15,4 |
 | so | 30BD | 15,8 |
 | zo | 30BE | 15,8 |
 | ta | 30BF | 19,2 |
 | da | 30C0 | 19,2 |
 | chi | 30C1 | 16,6 |
 | di | 30C2 |  | Deprecated - use 30B8
 | q | 30C3 |  | Lengthens following viseme
 | tsu | 30C4 | 15,7 |
 | du | 30C5 |  | Deprecated - use 30BA
 | te | 30C6 | 19,4 |
 | de | 30C7 | 19,4 |
 | to | 30C8 | 19,8 |
 | do | 30C9 | 19,8 |
 | na | 30CA | 19,2 |
 | ni | 30CB | 19,6 |
 | nu | 30CC | 19,7 |
 | ne | 30CD | 19,4 |
 | no | 30CE | 19,8 |
 | ha | 30CF | 12,2 |
 | ba | 30D0 | 21,2 |
 | pa | 30D1 | 21,2 |
 | hi | 30D2 | 12,6 |
 | bi | 30D3 | 21,6 |
 | pi | 30D4 | 21,6 |
 | hu | 30D5 | 18,7 |
 | bu | 30D6 | 21,7 |
 | pu | 30D7 | 21,7 |
 | he | 30D8 | 12,4 |
 | be | 30D9 | 21,4 |
 | pe | 30DA | 21,4 |
 | ho | 30DB | 12,8 |
 | bo | 30DC | 21,8 |
 | po | 30DD | 21,8 |
 | ma | 30DE | 21,2 |
 | mi | 30DF | 21,6 |
 | mu | 30E0 | 21,7 |
 | me | 30E1 | 21,4 |
 | mo | 30E2 | 21,8 |
 | ya | 30E3 | 6,2 | Replaces last viseme value of preceding character
 | ya | 30E4 | 6,2 |
 | yu | 30E5 | 6,7 | Replaces last viseme value of preceding character
 | yu | 30E6 | 6,7 |
 | yo | 30E7 | 6,7 | Replaces last viseme value of preceding character
 | yo | 30E8 | 6,7 |
 | ra | 30E9 | 14,2 |
 | ri | 30EA | 14,6 |
 | ru | 30EB | 14,7 |
 | re | 30EC | 14,4 |
 | ro | 30ED | 14,8 |
 | wa | 30EE | 7,2 | Replaces last viseme value of preceding character
 | wa | 30EF | 7,2 |
 | wi | 30F0 |  | Deprecated - use 30A4
 | we | 30F1 |  | Deprecated - use 30A8
 | wo | 30F2 | 7,8 |
 | nn | 30F3 | 19 |
 | vu | 30F4 | 18,7 |
 | ka | 30F5 | 20,2 |
 | ke | 30F6 | 20,4 |
 | va | 30F7 | 18,2 |
 | vi | 30F8 | 18,6 |
 | ve | 30F9 | 18,4 |
 | vo | 30FA | 18,8 |
 |  | 30FB |  | Middle dot
 |  | 30FC |  | Prolonged sound (lengthen previous viseme)
 |  | 30FD |  | Iteration (repeat previous character)
 |  | 30FE |  | Voiced iteration (output voiced form of previous character)


ISpeechPhraseElement Code Example (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechPhraseInfo

ISpeechPhraseInfo Code Example

The following Visual Basic form code demonstrates the properties and methods of the ISpeechPhraseInfo object. The ISpeechPhraseInfo object is contained in the ISpeechRecoResult object returned by a RecoContext's Recognition event.

To run this code, paste it into the Declarations section of a form that contains no controls. In addition to the usual reference to the Microsoft Speech Object Library, this code also needs a reference to the simpleaudio 1.0 Type Library.

The Form_Load procedure creates and sets up two SpAudioPlug objects (one for output and one for input), a SpVoice object, a SpInProcRecoContext object, and an ISpeechRecoGrammar object. The SpVoice object's EndStream event procedure and the SpInProcRecoContext object's Recognition event procedure are declared. Finally, the ISpeechRecoGrammar object's DictationLoad and DictationSetState methods are called.

Once the preceding objects have been correctly set up, the code passes the phrase "One of the world's seven wonders" to the SpVoice object's Speak method asynchronously. Then, until the SpVoice object's EndStream event gets raised, the spoken phrase stream is retrieved from the SpAudioPlug output object and passed in to the SpAudioPlug input object. After the entire stream has been processed (signaled by the EndStream event), the SpInProcRecoContext object's Recognition event is raised. Code in this event procedure then reads its Result parameter, which evaluates to an ISpeechRecoResult object.

This ISpeechRecoResult object's PhraseInfo property returns an ISpeechPhraseInfo object that contains detailed information about the last recognized phrase. The example code displays a couple message boxes that list the settings returned by the ISpeechPhraseInfo object's properties and methods.

Note A SpInProcRecoContext context restricts available resources to one context or application. That is, an SR engine or microphone usedSpInProcRecoContext/shared by such a recognition context may not be used by any other applications. In situations requiring the highest performance standards, response time or exacting recognition quality, use an InProc context. InProc contexts are important to embedded systems in other hardware platforms and are also used for non-microphone recognition such as recognizing streams from a file.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition:
    Set RecoContext = Recognizer.CreateRecoContext
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Const NL = vbNewLine
    Dim Phrase As Variant
    Dim PhraseBuilder As Object
    Dim PhraseInfo As ISpeechPhraseInfo
    Dim SDAttributes As SpeechDisplayAttributes
    Dim T As String
    Dim TextRecognized As String

    On Error GoTo EH

    TextRecognized = Result.PhraseInfo.GetText

    T = "The speech recognition engine's output is--" & NL & NL
    T = T & TextRecognized & NL & NL
    T = T & "The members of the ISpeechPhraseInfo interface are--"
    T = T & NL & NL

    With Result.PhraseInfo
        T = T & "AudioSizeBytes: " & .AudioSizeBytes & NL
        T = T & "AudioSizeTime: " & .AudioSizeTime & NL
        T = T & "AudioStreamPosition: " & .AudioStreamPosition & NL
        T = T & "Elements(3): " & .Elements.Item(3).DisplayText & NL
        T = T & "EngineId: " & .EngineId & NL

        If Len(.EnginePrivateData) = 0 Then
            T = T & "EnginePrivateData: None" & NL
        End If

        T = T & "GetDisplayAttributes: " & .GetDisplayAttributes & NL
        T = T & "GrammarId: " & .GrammarId & NL
        T = T & "LanguageId: " & .LanguageId & NL

        If Not .Properties Is Nothing Then
            T = T & "Properties: " & .Properties.Count & NL
        Else
            T = T & "Properties: Nothing" & NL
        End If

        If Not .Replacements Is Nothing Then
            T = T & "Replacements: " & .Replacements.Count & NL
        Else
            T = T & "Replacements: Nothing" & NL
        End If

        T = T & "RetainedSizeBytes: " & .RetainedSizeBytes & NL
        T = T & "Rule (# of Elements): " & .Rule.NumberOfElements & NL
        T = T & "StartTime: " & .StartTime
    End With

    MsgBox T, vbInformation

    With Result.PhraseInfo

        T = "Demo of SaveToMemory and RestorePhraseFromMemory methods--"
        T = T & NL & NL

        ' Store phrase first.
        Phrase = .SaveToMemory

        ' Retrieve phrase:
        Set PhraseBuilder = CreateObject("SAPI.SpPhraseInfoBuilder")
        Set PhraseInfo = PhraseBuilder.RestorePhraseFromMemory(Phrase)

        T = T & PhraseInfo.GetText
        MsgBox T, vbInformation

    End With

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Const NL = vbNewLine
    Dim T As String

    T = "Desc: " & Err.Description & NL
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub


ISpeechPhraseElement Code Example (Microsoft Speech Platform)

 Microsoft Speech Platform

Interface: ISpeechRecoResultTimes

ISpeechRecoResultTimes Code Example

The following Visual Basic form code demonstrates the properties and methods of the ISpeechRecoResultTimes object. This object is contained in the Times property of the ISpeechRecoResult object that is returned by a RecoContext's Recognition event.

To run this code, paste it into the Declarations section of a form that contains no controls. In addition to the usual reference to the Microsoft Speech Object Library, this code also needs a reference to the simpleaudio 1.0 Type Library.

The Form_Load procedure creates and sets up two SpAudioPlug objects (one for output and one for input), a SpVoice object, a SpInProcRecoContext object, and an ISpeechRecoGrammar object. The SpVoice object's EndStream event procedure and the SpInProcRecoContext object's Recognition event procedure are declared. Finally, the ISpeechRecoGrammar object's DictationLoad and DictationSetState methods are called.

Once the preceding objects have been correctly set up, the code passes the phrase "One of the world's seven wonders" to the SpVoice object's Speak method asynchronously. Then, until the SpVoice object's EndStream event gets raised, the spoken phrase stream is retrieved from the SpAudioPlug output object and passed in to the SpAudioPlug input object. After the entire stream has been processed (signaled by the EndStream event), the SpInProcRecoContext object's Recognition event is raised. Code in this event procedure then reads its Result parameter, which evaluates to an ISpeechRecoResult object.

This ISpeechRecoResult object's Times property returns an ISpeechRecoResultTimes object that contains four properties (Length, OffsetFromStart, StreamTime, and TickCount). The example code displays a message box that lists the settings of these properties for the current recognition object.

Note A SpInProcRecoContext context restricts available resources to one context or application. That is, an SR engine or microphone usedSpInProcRecoContext/shared by such a recognition context may not be used by any other applications. In situations requiring the highest performance standards, response time or exacting recognition quality, use an InProc context. InProc contexts are important to embedded systems in other hardware platforms and are also used for non-microphone recognition such as recognizing streams from a file.

Option Explicit

Const AUDIOFORMAT = SAFT8kHz16BitMono

' Text-to-Speech variables:
Dim WithEvents Voice As SpVoice
Dim EndofStream As Boolean
Dim AudioPlugOut As SpAudioPlug

' Speech Recognition variables:
Dim WithEvents RecoContext As SpInProcRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Recognizer As SpInprocRecognizer
Dim AudioPlugIn As SpAudioPlug

Private Sub Form_Load()

    Const Text = "One of the world's seven wonders"
    Dim Output As Variant

    On Error GoTo EH

    Set Voice = New SpVoice

    ' Set up output audio:
    Set AudioPlugOut = New SpAudioPlug
    AudioPlugOut.Init True, AUDIOFORMAT
    Set Voice.AudioOutputStream = AudioPlugOut

    ' Set up input audio:
    Set AudioPlugIn = New SpAudioPlug
    AudioPlugIn.Init False, AUDIOFORMAT
    Set Recognizer = New SpInprocRecognizer
    Set Recognizer.AudioInputStream = AudioPlugIn

    ' Set up speech recognition:
    Set RecoContext = Recognizer.CreateRecoContext
    Set Grammar = RecoContext.CreateGrammar(1)
    Grammar.DictationLoad
    Grammar.DictationSetState SGDSActive

    ' Speak some text to be recognized.
    Voice.Speak Text, SVSFlagsAsync

    Do While EndofStream = False
        DoEvents

        ' Get audio data from audio object.
        Output = AudioPlugOut.GetData

        ' Output audio data to input audio object--
        If (Len(Output) * 2 <> 0) Then
            AudioPlugIn.SetData (Output)
        End If

    Loop

    Grammar.DictationSetState SGDSInactive

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub RecoContext_Recognition _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant, _
    ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
    ByVal Result As SpeechLib.ISpeechRecoResult)

    Const NL = vbNewLine
    Dim MyTimes As ISpeechRecoResultTimes
    Dim T As String

    On Error GoTo EH

    Set MyTimes = Result.Times

    With MyTimes
        T = "Length: " & .Length & NL
        T = T & "OffsetFromStart: " & .OffsetFromStart & NL
        T = T & "StreamTime: " & .StreamTime & NL
        T = T & "TickCount: " & .TickCount
        MsgBox T, vbInformation
        End
    End With

EH:
    If Err.Number Then ShowErrMsg
End Sub

Private Sub Voice_EndStream _
   (ByVal StreamNumber As Long, _
    ByVal StreamPosition As Variant)

    EndofStream = True

End Sub

Private Sub ShowErrMsg()

    ' Declare identifiers:
    Dim T As String

    T = "Desc: " & Err.Description & vbNewLine
    T = T & "Err #: " & Err.Number
    MsgBox T, vbExclamation, "Run-Time Error"
    End

End Sub