Thursday, 12 December 2013

Converting Text To Speech in Windows Forms



Today am going to explain how we can convert the given text to voice output using C#.NET in Windows forms project.

Take a new project in windows forms. We have to add speech reference. Right click on the ‘References’ and add System.Speech dll.

In the designer page take a textbox and a button. In the code page add the following namespaces

using System.Speech;
using System.Speech.Synthesis;

Declare a new class called SpeechSynthesizer

Define an object to this class



Here I am referring the class with an object called reader.

SpeechSynthesizer reader;

In the button click event now write the following code.

First check whether the textbox has any data or not?

if (textBox1.Text != "")

If the textbox is not null then the debugger enters the following code.

reader = new SpeechSynthesizer();

reader.SpeakAsync(textBox1.Text);

Now the entire code altogether is

using System.Speech;
using System.Speech.Recognition;
using System.Speech.Synthesis;

namespace NameSpace
{
    public partial class TextToSpeech : Form
    {
        SpeechSynthesizer reader;
        public TextToSpeech()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                reader = new SpeechSynthesizer();
                reader.SpeakAsync(textBox1.Text);
            }
        }
    }
}

No comments:

Post a Comment