C# - Text To Speech

The .Net Framework makes developing Text to Speech applications very simple with the System.Speech assembly. In this article, I explain how easy it is to get started with Text to Speech.

Let's begin with a console application and add a reference to the System.Speech assembly. Once added you will also need to add the System.Speech.Synthesis namespace to your project. The primary class responsible for Text to Speech is the SpeechSynthesizer class. This class takes a "Prompt" and renders it as audio. A Prompt can either be a text or an audio file. Let's take a look at a quick example using the famous "Hello world" as an example text.
  1. Prompt textPrompt = new Prompt("Hello World");  
  2. SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();  
  3. speechSynthesizer.Speak(textPrompt)
Notice the Speak() method of the SpeechSynthesizer class, this method accepts a Prompt and renders it using the default voice. If the default voice is not to your liking, you can change it to another voice. To change the voice, you need to use the SelectVoice method of SpeechSynthesizer class. This method accepts a voice name as its argument. To get a list of available voice names, you can use the GetInstalledVoices() method, which returns a ReadOnlyCollection of type InstalledVoice. The ReadOnlyCollection can be found in the System.Collections.ObjectModel namespace.
  1. ReadOnlyCollection<InstalledVoice> installedVoice = speechSynthesizer.GetInstalledVoices();  
  2.  
  3. foreach (InstalledVoice voice in installedVoice)  
  4. {  
  5.     Console.WriteLine(voice.VoiceInfo.Name);  
  6. } 
The rendered output can easily be saved as a WAV file using the SetOutputToWaveFile() method.
  1. speechSynthesizer.SetOutputToWaveFile("file name.wav")
For this last example, let's get the currently spoken word. This is useful if you are developing an application where you want to highlight each word in the text as its spoken. The SpeakProgress event of the SpeechSynthesizer class is raised every time a word is spoken.
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.          SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();  
  6.          speechSynthesizer.SpeakProgress += new EventHandler<SpeakProgressEventArgs>(speechSynthesizer_SpeakProgress);  
  7.          speechSynthesizer.Speak("The quick brown fox jumps over the lazy dog");  
  8.  
  9.          Console.ReadKey();  
  10.     }  
  11.  
  12.     static void speechSynthesizer_SpeakProgress(object sender, SpeakProgressEventArgs e)  
  13.     {  
  14.          Console.WriteLine(e.Text );  
  15.     }  
  16. } 

No comments:

Post a Comment