利用.net的语音识别库,很容易就可以制作类似Siri的简单的问答程序。
实现步骤如下:
1.创建一个新项目,并添加对System.Speech的引用。(如下图所示)
2. 在窗体内分别定义语音识别(SpeechRecognitionEngine )和语音朗读(SpeechSynthesizer )
SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine(); SpeechSynthesizer Siri = new SpeechSynthesizer();
3.在窗体启动里添加如下代码就可以了:
CultureInfo myCIintl = new CultureInfo("zh-CN"); foreach (RecognizerInfo config in SpeechRecognitionEngine.InstalledRecognizers()) { if (config.Culture.Equals(myCIintl) && config.Id == "MS-2052-80-DESK") { _recognizer = new SpeechRecognitionEngine(config); break; } } _recognizer.SetInputToDefaultAudioDevice(); _recognizer.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(File.ReadAllLines(Application.StartupPath + "\\command.txt"))))); _recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(_recognizer_SpeechRecognized); _recognizer.RecognizeAsync(RecognizeMode.Multiple);
void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { string speech = e.Result.Text; switch (speech) { case "你好": Siri.Speak("你好"); break; case "今天星期几": Siri.Speak("今天" + DateTime.Today.ToString("dddd")); break; case "今天几号": Siri.Speak("今天是" + DateTime.Today.ToString("yyyy-MM-dd")); break; case "现在几点": DateTime now = DateTime.Now; string time = now.GetDateTimeFormats('t')[0]; Siri.Speak(time); break; case "关机": System.Diagnostics.Process.Start("shutdown", "-s"); break; } }
运行程序,即可实现语音问答。
也可将程序应用到使用语音控制家用电器,实现智能家居(可参考 http://blog.csdn.net/soft2buy/article/details/6248333 )。
本文完整代码下载:
原文地址:http://blog.csdn.net/soft2buy/article/details/41677275