VC++ MVP 2006, C# MVP 2007 Ravi Bhavnani's .NET bits
A compendium of scribblings, hacks, and things .NET

Linkworthy
  • The CodeProject
  • CodePlex
  • Channel 9
  • The Lab with Leo Laporte
  •  
    Say what!?
    Speech synthesis the managed way
    by Ravi Bhavnani, 17 Dec 2007
    Home  All articles

    Among the new bits in .NET 3.0 is the SpeechSynthesizer class that exposes SAPI's functionality to managed code without having to resort to P/InvokeSpeechSynthesizer is located in the System.Speech.Synthesis namespace.  To speak text, we simply call Speak() or SpeakAsync() with a string containing the text to be spoken.  To terminate the speech, call SpeakAsyncCancelAll().

      1   SpeechSynthesizer ss = new SpeechSynthesizer();
      2   ss.SpeakAsync ("Hello, world");
      3   ...
      4   ss.SpeakAsyncCancelAll();

    The speech is spoken using the object's current properties of Voice, Rate and VolumeVoice is the name of an installed voice, Rate is an integer between -10 and 10, and Volume is an integer between 0 and 100 and represents the percentage of the audio device's main volume.  The list of installed voices is obtained by calling GetInstalledVoices() as shown below.

      1   ReadOnlyCollection<InstalledVoice>
      2     voices = ss.GetInstalledVoices();
      3   if (voices.Count > 0)
      4       ss.Voice = voices[0];

    Saving the spoken text as a .WAV file is easily done by directing the synthesizer's output to the file, speaking the text, and redirecting the output to the default audio device.

      1   // Save speech as .WAV file
      2   ss.SetOutputToWaveFile ("C:\\hello.wav");
      3   ss.Speak ("Hello, world");
      4   ss.SetOutputToDefaultAudioDevice();

    And there you have it - speech synthesis in a few words.

     

    Most of the drivel at this site is copyright Ravi Bhavnani.
    Questions or comments?  Send mail to ravib@ravib.com