March 11, 2011

Text-to-Speech Recognition (TTS)

There is a lot of examples having place on internet about text-to-speech recognition. Mostly are in vb.net or other source. But here i am introducing code in C#.Net Framework 4.0.


I am using Microsoft Speech SDK 5.1 or you can use built-in SAPI which is already install in every type of windows. This is Windows Form Application using C# and you have to add following controls in your form

3 Buttons named as;
  • Start ----> btnStart
  • Stop ----> btnStop
  • Exit ----> btnExit

1 combo box named as;
  • cmbInstalledVoice (Dropdown style = dropdownlist)

2 Trach control named as;
  • Volume -----> btnVolume (Set minimum = 0 and maximum = 100)
  • Rate -----> btnRate (Set minimum = -10 and maximum = 10)

1 Textbox named as;
  • TextBox ------> txtVoiceText (multiline = true)

Here's also the sketch of form including these controls
Text-To-Speech-Image

Now add web reference in your project, For Web Reference
Right click on reference in solution explorer then click on Add Reference, in tab name .Net add reference name System.Speech

C# Code:


using System.Speech.Synthesis;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Diagnostics;

private SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();

private void Form1_Load(object sender, EventArgs e)
{
    ReadOnlyCollection(installedvoice) getInstalledVoice = speechSynthesizer.GetInstalledVoices(CultureInfo.CurrentCulture);
    VoiceInfo voiceInfo = getInstalledVoice[0].VoiceInfo;

    foreach (InstalledVoice installedVoice in getInstalledVoice)
    {
       voiceInfo = installedVoice.VoiceInfo;
       cmbInstalledVoice.Items.Add(voiceInfo.Name.ToString());
    }
}
private void btnStart_Click(object sender, EventArgs e)
{
   speechSynthesizer.SelectVoice(cmbInstalledVoice.Text);
   speechSynthesizer.SpeakAsync(txtVoiceText.Text);
}

private void btnVolume_ValueChanged(object sender, EventArgs e)
{
   speechSynthesizer.Volume = btnVolume.Value;
}

private void btnRate_ValueChanged(object sender, EventArgs e)
{
   speechSynthesizer.Rate = btnRate.Value;
}

private void btnStop_Click(object sender, EventArgs e)
{
   speechSynthesizer.SpeakAsyncCancelAll();
}

private void btnExit_Click(object sender, EventArgs e)
{
   this.Close();
}