Friday, March 6, 2015

Speech Recognition Windows Form Based .NET application

Speech Recognition Windows Form Based .NET application


To understand basic Speech Recognition concept, please visit my earlier post here.


Now in this post, we will work on windows based form application.
So create a simple Windows Form application which should look like this -


As mentioned in my earlier post here add reference to System.Speech Namespace.
Add following namespaces.
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Globalization;


And create reference of SpeechSynthesizer class as follows.
SpeechSynthesizer Syn;


First we would work on Text-To-Speech.


On Listen Button Click event write following code which will Speak the entered text in TextBox. If you carefully note the code below we have used two different method as Speak() and SpeakAsync(). First method Speak() will speak the specified text synchronously, we cannot use pause(), resume(), etc here. While the other method SpeakAsync() will speak asynchronously. This will help us to work on various functionalities like Pause(), Resume().


private void btnListen_Click(object sender, EventArgs e)
{
Syn = new SpeechSynthesizer();
if (textBox1.Text.Trim().Equals(string.Empty))
{
Syn.Speak("Enter Text First");
}
else
{
Syn.SpeakAsync(textBox1.Text);
}
}


On Pause button Click, write following code
private void btnPause_Click(object sender, EventArgs e)
{
if (Syn.State == SynthesizerState.Speaking)
{
Syn.Pause();
}
}


And On Resume button Click, write following code
private void btnResume_Click(object sender, EventArgs e)
{
if (Syn.State == SynthesizerState.Paused)
{
Syn.Resume();
}
}


And Now we can Build and Run to check the functionality of Text-To-Speech.


Let us now work on Speech-to-Text


And here is the code
private void Form1_Load(object sender, EventArgs e)
{
    startRecognition();
}
private void startRecognition()
{
SpeechRecognizer recognizer = new SpeechRecognizer();
recognizer.SpeechRecognized +=
new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);
}
void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
textBox1.Text = e.Result.Text;
}


When we Built and Run the application, we may get following window for the first time application execution


Click Next and follow the instructions. Once done you will get small listening window as follows.


Speak and then it will be converted to text which will appear in textbox. You can also work on several exception handling in this code.


--Happy Coding ---




No comments:

Post a Comment