C# 尝试检查语音识别时出错。用户代码未处理InvalidOperationException

C# 尝试检查语音识别时出错。用户代码未处理InvalidOperationException,c#,speech-recognition,voice-recognition,speech-synthesis,C#,Speech Recognition,Voice Recognition,Speech Synthesis,错误是: System.Core.dll中发生“System.InvalidOperationException”类型的异常,但未在用户代码中处理 附加信息:序列不包含任何元素 当程序点击这一行时,会出现此错误 var cmd = words.Where(c => c.Text == command).First(); 顺便说一句,这个节目的重点是表演一个语音人工智能,就像《钢铁侠三部曲》中那样 JarvisDriver.cs #region using directives usin

错误是:

System.Core.dll中发生“System.InvalidOperationException”类型的异常,但未在用户代码中处理

附加信息:序列不包含任何元素

当程序点击这一行时,会出现此错误

var cmd = words.Where(c => c.Text == command).First();
顺便说一句,这个节目的重点是表演一个语音人工智能,就像《钢铁侠三部曲》中那样

JarvisDriver.cs

#region using directives

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Windows;
using System.Diagnostics;
using JarvisAPI;

#endregion


namespace SpeechRecognition
{
    class JarvisDriver
    {
         #region locals

         /// <summary>
         /// the engine
         /// </summary>
         SpeechRecognitionEngine speechRecognitionEngine = null;

         /// <summary>
         /// The speech synthesizer
         /// </summary>
         SpeechSynthesizer speechSynthesizer = null;

         /// <summary>
         /// list of predefined commands
         /// </summary>
         List<Word> words = new List<Word>();

         /// <summary>
         /// The last command
         /// </summary>
         string lastCommand = "";

         /// <summary>
         /// The name to call commands
         /// </summary>
         string aiName = "Jarvis";

         #endregion

         #region ctor

         public void Start()
         {

             try
             {
                 // create the engine
                 speechRecognitionEngine = createSpeechEngine("en-US");

                 // hook to event
                 // new EventHandler<SpeechRecognizedEventArgs>();
                 speechRecognitionEngine.SpeechRecognized += new    EventHandler<SpeechRecognizedEventArgs>     (speechRecognitionEngine_SpeechRecognized);

                 // load dictionary
                 loadGrammarAndCommands();

                 // use the system's default microphone
                 speechRecognitionEngine.SetInputToDefaultAudioDevice();

                 // start listening
                 speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);

                 //Create the speech synthesizer
                 speechSynthesizer = new SpeechSynthesizer();
                 speechSynthesizer.Rate = -5;

             }
             catch (Exception ex)
             {
                 Console.WriteLine("Voice recognition failed " + ex.Message);
             }

             //Keeps the command prompt going until you say jarvis quit
             while(lastCommand.ToLower() != "quit")
             {

             }

         }

         #endregion

         #region internal functions and methods

         /// <summary>
         /// Creates the speech engine.
         /// </summary>
         /// <param name="preferredCulture">The preferred culture.</param>
         /// <returns></returns>
         private SpeechRecognitionEngine createSpeechEngine(string preferredCulture)
         {
             foreach (RecognizerInfo config in SpeechRecognitionEngine.InstalledRecognizers())
             {
                 if (config.Culture.ToString() == preferredCulture)
                 {
                     speechRecognitionEngine = new SpeechRecognitionEngine(config);
                     break;
                 }
             }

             // if the desired culture is not found, then load default
             if (speechRecognitionEngine == null)
             {
                 Console.WriteLine("The desired culture is not installed on this machine, the speech-engine will continue using "
                + SpeechRecognitionEngine.InstalledRecognizers()[0].Culture.ToString() + " as the default culture.",
                "Culture " + preferredCulture + " not found!");
                 speechRecognitionEngine = new SpeechRecognitionEngine(SpeechRecognitionEngine.InstalledRecognizers()[0]);
             }

             return speechRecognitionEngine;
         }

         /// <summary>
         /// Loads the grammar and commands.
         /// </summary>
         private void loadGrammarAndCommands()
              {
                  try
                  {
                      Choices texts = new Choices();
                      texts.Add("Jarvis");
                      string[] lines = File.ReadAllLines(Environment.CurrentDirectory + "\\example.txt");
                      foreach (string line in lines)
                      {
                          // skip commentblocks and empty lines..
                          if (line.StartsWith("--") || line == String.Empty) continue;

                          // split the line
                          var parts = line.Split(new char[] { '|' });

                          // add commandItem to the list for later lookup or execution
                          words.Add(new Word() { Text = parts[0], AttachedText = parts[1], IsShellCommand = (parts[2] == "true") });

                          // add the text to the known choices of speechengine
                          texts.Add(parts[0]);
                      }
                      GrammarBuilder grammarBuilder = new GrammarBuilder(texts);
                      grammarBuilder.Culture = new System.Globalization.CultureInfo("en-GB");
                      Grammar wordsList = new Grammar(grammarBuilder);
                      speechRecognitionEngine.LoadGrammarAsync(wordsList);

                      DictationGrammar dict = new DictationGrammar();
                      speechRecognitionEngine.LoadGrammarAsync(dict);

                  }
                  catch (Exception ex)
                  {
                      throw ex;
                  }
              }

              /// <summary>
              /// Gets the known command.
              /// </summary>
              /// <param name="command">The order.</param>
              /// <returns></returns>
              private string getKnownTextOrExecute(string command)
              {
                  if (command.StartsWith("Jarvis"))
                  {
                      Console.WriteLine("Said Jarvis");
                      command = command.Replace("Jarvis ", "");
                  }
                  else
                  {
                      Console.WriteLine("Said Random Thing");
                      return "";
                  }

                  Console.WriteLine("Passed" + command);

                  var cmd = words.Where(c => c.Text == command).First();
                  Console.WriteLine("Said Random Thing");

                  if (cmd.IsShellCommand)
                  {
                      Console.WriteLine("is command");
                      Process proc = new Process();
                      proc.EnableRaisingEvents = false;
                      proc.StartInfo.FileName = cmd.AttachedText;
                      proc.Start();
                      lastCommand = command;

                      if (command.ToLower() == "i have a burn victim")
                      {
                          Console.WriteLine("Burn");
                          return "Fetching list of burn centers for you sir";
                      }
                      else
                      {
                          Console.WriteLine("Starting Somethign");
                          return "I've started : " + command;
                      }
                  }
                  else
                  {
                      Console.WriteLine("Set Last Command");
                      lastCommand = command;
                      return cmd.AttachedText;
                  }
              }

              #endregion

              #region speechEngine events

              /// <summary>
              /// Handles the SpeechRecognized event of the engine control.
              /// </summary>
              /// <param name="sender">The source of the event.</param>
              /// <param name="e">The <see cref="System.Speech.Recognition.SpeechRecognizedEventArgs"/> instance containing the event data.</param>
              void speechRecognitionEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
              {
                  string command = getKnownTextOrExecute(e.Result.Text);

                  if (command != "")
                  {
                      speechSynthesizer.SpeakAsync(command);
                      Console.WriteLine("Failed");
                  }
              }

          #endregion

      }
  }
namespace SpeechRecognition
{
    /// <summary>
    /// represents a word
    /// </summary>
    public class Word
    {
        public Word() { }
        public string Text { get; set; }
        public string AttachedText { get; set; }
        public bool IsShellCommand { get; set; }
    }
}
-- format
-- [text to recognize] | [text to display or execute] | [is text a command?]

-- simple text --
one|you said "one"|false
two|you said "two"|false
three|you said "three"|false
four|you said "four"|false
five|you said "five"|false
six|you said "six"|false
seven|you said "seven"|false
eight|you said "eight"|false
nine|you said "nine"|false
ten|you said "ten"|false
Patrick|you said "Patrick"|false
do you like me|you made me I kinda have too|false
could you open calculator for me please|calc|true


-- commands --
wordpad|wordpad.exe|true
calculator|calc.exe|true
I have a burn victim|"http://en.wikipedia.org/wiki/List_of_burn_centers_in_the_United_States"|    true