首页 > 代码库 > c#创建类似Siri的语音问答的简单应用

c#创建类似Siri的语音问答的简单应用

利用.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;               
            }
        }

所有的命令都保存在"command.txt"文件中,记得用unicode保存才行。

运行程序,即可实现语音问答。

也可将程序应用到使用语音控制家用电器,实现智能家居(可参考 http://blog.csdn.net/soft2buy/article/details/6248333 )。


本文完整代码下载:


c#创建类似Siri的语音问答的简单应用