Speech Recognition in C#.Net
Sunday, April 26, 2009
I’ve now started playing around with speech recognition using C# in Visual Studio 2008. The last time I demonstrated Speech Synthesis to read the contents out loud from a text file. However this implementation is command based and not dictation based. This is very very basic and it recognizes only one word and then displays the results from database containing that word. For basics on getting started with speech utilities in C#, refer to my last post here.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Speech;using System.Speech.Recognition;using System.Data;using System.Data.SqlClient;using System.Data.SqlTypes;namespace speechrecog{class Program{//connection initialization to the databasestatic string connectionString = "Data Source=MEOW-PC;Initial Catalog=Shopping_eye;Integrated Security=SSPI";static SqlConnection cn = new SqlConnection(connectionString);static void Main(string[] args){new Program();}private Program(){//access to the default shared speech recognition engine used by the desktopSpeechRecognizer rec = new SpeechRecognizer();rec.SpeechRecognized += rec_SpeechRecognized;//add the words in choices that you want to be recognizedChoices c = new Choices();c.Add("cheese");c.Add("pizza");c.Add("olives");c.Add("exit");//Populate the grammar builder with the choices and load it as a new grammarGrammarBuilder pizzadetails = new GrammarBuilder(c);Grammar g = new Grammar(pizzadetails);rec.LoadGrammar(g);rec.Enabled = true;Console.Read();}void rec_SpeechRecognized(object sender, SpeechRecognizedEventArgs e){if (e.Result.Text == "exit")System.Environment.Exit(0);//Closes the console when you say exitstring cassy =e.Result.Text;Console.Write(cassy);//This query will display the results containing the word that was recognizedstring squery = "select * from speechrecogtest where name like '%"+cassy+"%'";SqlDataAdapter da = new SqlDataAdapter(squery, cn);DataTable dt = new DataTable();cn.Open();// Fill the data table with select statement's query results:int recordsAffected = da.Fill(dt);System.Console.WriteLine();if (recordsAffected > 0){foreach (DataRow dr in dt.Rows){System.Console.Write(dr[0]);System.Console.Write(" ");System.Console.Write(dr[1]);System.Console.Write(" ");System.Console.Write(dr[2]);System.Console.WriteLine("");}}}}}
So, when I say “cheese”, the following entries containing the word are retrieved from the database and displayed on the console. I am still figuring how to loop the program to recognize my commands back to back, as per the choices mentioned in the code. Until then, keep trying and experimenting…Au Revoire!