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

时间:2015-07-29 19:42:20

标签: c# speech-recognition voice-recognition speech-synthesis

错误是:

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

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

当程序到达此行时会出现此错误;

#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

      }
  }

顺便说一下,该计划的目的是执行演讲AI,就像钢铁侠三部曲一样。

JarvisDriver.cs

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; }
    }
}

Word.cs

-- 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

example.txt中

.data("ui-autocomplete")._renderItem = function( ul, item ) {
      return $( "<li class='submitmore' ></li>" )
      .data( "item.autocomplete", item )
      .append('<p class="searchdata">'+item.value+'<div class="clear"></div>');
};

$(document).on("p.searchdata").click(function() {
    asd($(this).closest("li.submitmore").data("item.autocomplete"));
}

0 个答案:

没有答案