Text to Speech in 3 lines of code

Hi,

In this post I will show you how you can create a very simple text to speech program using just a few lines of code. It’s actually very simple using the System.Speech namespace. You first start by adding a new reference to System.Speech.

image

After that make sure to actually use this namespace in your code.

using System.Speech;

Ok now that we did that, le’ts finish off the codework. The only thing we need to do is create an instance of the Speech.Synthesis.SpeechSynthesizer class. Set the voice and the PC will do the talking.

if(txtMsg.Text!=String.Empty)
{
       using(System.Speech.Synthesis.SpeechSynthesizer synth = 
        new System.Speech.Synthesis.SpeechSynthesizer())
       {

           synth.SelectVoiceByHints(System.Speech.Synthesis.
           VoiceGender.Male,
           System.Speech.Synthesis.VoiceAge.Senior, 0);
           synth.Speak(txtMsg.Text);
       }
}
else
{
      MessageBox.Show("Nothing to say!");
}
Ok I have to admit, there are some more lines of code,
I did this to actually make sure we have something to say.



				
			

No comments yet. Be the first.

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word