Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Example: A Spoken Hello, World Using the Microsoft Speech API

Once you've either referenced the Microsoft Speech Object Library in Visual Studio .NET, or run the TLBIMP.EXE utility on SAPI.DLL, you're ready to write the code that uses this COM component. This can be done with these two steps:

  1. Type the following code either in a Visual Studio .NET project or in your favorite text editor.

    		The C# version (HelloWorld.cs):
      using SpeechLib;
      class Class1
      {
       static void Main()
       {
       SpVoice voice = new SpVoice();
       voice.Speak("Hello, World!", SpeechVoiceSpeakFlags.SVSFDefault);
       }
      }
      

    The Visual Basic .NET version (HelloWorld.vb):

    Imports SpeechLib Module Module1 Sub Main() Dim voice as SpVoice voice = new SpVoice() voice.Speak("Hello, World!") End Sub End Module The C++ version (HelloWorld.cpp): #using <mscorlib.dll> // Required for all managed programs #using <SpeechLib.dll> // The assembly created by TLBIMP.EXE using namespace SpeechLib; void main() { SpVoice* voice = new SpVoiceClass(); voice->Speak("Hello, World!", SpeechVoiceSpeakFlags::SVSFDefault); };

    Because Visual C++ .NET projects do not provide a mechanism for referencing COM components, TLBIMP.EXE needs to be used to create SpeechLib.dll regardless of whether or not you use Visual Studio .NET.

  2. Compile and run the code (and listen to the voice). Feel free to have some more fun with the Speech API. You'll find that interacting with it is easy after you've gotten this far.

Notice the differences between the C#, Visual Basic .NET, and C++ versions of the same program. For example, the C# and C++ calls to Speak use two parameters but the same call in VB .NET has just one parameter. That's because the second parameter is optional, yet C# and C++ do not support optional parameters. Instead, a value must always be passed. Also notice that the C++ program instantiates SpVoiceClass instead of SpVoice as the others do. In this case, the C# and VB .NET compilers are doing some extra work behind-the-scenes to enable the user to work with a class that has the same name as the original COM coclass. More information about this extra work is given in the next chapter, "An In-Depth Look at Imported Assemblies."

  • + Share This
  • 🔖 Save To Your Account