语音识别器中的异步等待

时间:2016-09-28 07:19:18

标签: c# async-await speech-recognition

我正在尝试通过以下更改复制this示例:

  1. 使用控制台应用程序代替Windows:这看起来很好,因为计算机正在跟我说话

  2. 使用Sync功能:这里看起来我错了。

  3. 更新 一旦程序执行完毕,它就会对我说话,并等待按下按键,之后它会等待一些“聆听”,但sre_SpeechRecognized没有被执行。

    以下是我的代码,谢谢:

    using System;
    using System.Threading.Tasks;
    using System.Speech.Synthesis;
    using System.Speech.Recognition;
    
    class Startup {
            // Create a simple handler for the SpeechRecognized event
        static void sre_SpeechRecognized (object sender, SpeechRecognizedEventArgs e)
        {
            string speech = e.Result.Text;
    
                    //handle custom commands
            switch (speech)
            {
                case "red":
                    Console.WriteLine("Hello");
                    break;
                case "green":
                    System.Diagnostics.Process.Start("Notepad");
                    break;
                case "blue":
                    Console.WriteLine("You said blue");
                    break;
                case "Close":
                   Console.WriteLine("Speech recognized: {0}", e.Result.Text);
                    break;
            }
            Console.WriteLine("Speech recognized: {0}", e.Result.Text);
        }
    
    public async Task<object> Invoke(dynamic i) {
    // Initialize a new instance of the SpeechSynthesizer.
            SpeechSynthesizer synth = new SpeechSynthesizer();
    
            // Configure the audio output. 
            synth.SetOutputToDefaultAudioDevice();
    
            // Speak a string.
            synth.Speak("This example demonstrates a basic use of Speech Synthesizer");
    
            Console.WriteLine();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
    
            // Create a new SpeechRecognitionEngine instance.
            SpeechRecognizer recognizer = new SpeechRecognizer();
    
            // Create a simple grammar that recognizes "red", "green", or "blue".
            Choices colors = new Choices();
            colors.Add(new string[] { "red", "green", "blue" });
    
            // Create a GrammarBuilder object and append the Choices object.
            GrammarBuilder gb = new GrammarBuilder();
            gb.Append(colors);
    
            // Create the Grammar instance and load it into the speech recognition engine.
            Grammar g = new Grammar(gb);
            recognizer.LoadGrammar(g);
    
            // Register a handler for the SpeechRecognized event.
            recognizer.SpeechRecognized += 
              new EventHandler<SpeechRecognizedEventArgs> (Startup.sre_SpeechRecognized);
           Console.WriteLine("Exiting now..");
       return null;
    }
    }
    

2 个答案:

答案 0 :(得分:1)

你没有开始认可。请查看您发布的链接。在示例中注册事件后,有一行sre.Recognize();(代码中缺少)。还提到了一种RecognizeAsync()方法,可能就是您想要的方法。

答案 1 :(得分:1)

修改Invoke方法,如下所示(这是Async调用者(此处为Node Js)等待Synchronous事件完成的典型情况。

重要细节(请注意此修改的基础是,否则语音引擎正在按预期工作)

  1. Made Invoke方法Sync,而不是Async,因为原始代码中没有Async调用
  2. 将返回值替换为任务以获取事件返回值
  3. 使事件内联易于使用对象
  4. 最后添加了Recognize同步方法
  5. 当任务完成事件后触发时将返回,并且将包含Task<string>内的结果,该结果可以使用TaskObject.Result属性获取结果

      public async Task<object> Invoke(dynamic i) {    // async here is required to be used by Edge.JS that is a node.js module enable communicating with C# files
      var tcs = new TaskCompletionSource<object>();
      // Initialize a new instance of the SpeechSynthesizer.
        SpeechSynthesizer synth = new SpeechSynthesizer();
    
        // Configure the audio output. 
        synth.SetOutputToDefaultAudioDevice();
    
        // Speak a string.
        synth.Speak("This example demonstrates a basic use of Speech Synthesizer");
    
        Console.WriteLine();
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    
        // Create a new SpeechRecognitionEngine instance.
    
        SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();
    
        recognizer.SetInputToDefaultAudioDevice();
    
        // Create a simple grammar that recognizes "red", "green", or "blue".
        Choices colors = new Choices();
        colors.Add(new string[] { "red", "green", "blue" });
    
        // Create a GrammarBuilder object and append the Choices object.
        GrammarBuilder gb = new GrammarBuilder();
        gb.Append(colors);
    
        // Create the Grammar instance and load it into the speech recognition engine.
        Grammar g = new Grammar(gb);
        recognizer.LoadGrammar(g);
    
        // Register a handler for the SpeechRecognized event.
        recognizer.SpeechRecognized += (sender,e) => {
    
           string speech = e.Result.Text;
    
            //handle custom commands
            switch (speech)
            {
                case "red":
                 tcs.SetResult("Hello Red");
                break;
                case "green":
                 tcs.SetResult("Hello Green");
                break;
                case "blue":
                 tcs.SetResult("Hello Blue");
                 break;
                case "Close":
                 tcs.SetResult("Hello Close");
                break;
               default:
                 tcs.SetResult("Hello Not Sure");
              break;
    }
    
     };
    
       // For Edge JS we cannot await an Async Call (else it leads to error)
       recognizer.Recognize();              
       return tcs.Task.Result;
    
       //// For pure C#
       // await recognizer.RecognizeAsync();              
       // return tcs.Task;
    }
    
  6. 异步特定更改

    1. public async Task<object> Invoke(dynamic i)(制作方法async并返回类型Task,异步方法的要求)
    2. 呼叫await recognizer.RecognizeAsync();(在异步呼叫上呼叫等待)
    3. return tcs.Task(返回类型需要为任务)