2012-11-28 38 views
1

我是一名編程初學者,我試圖構建一個簡單的應用程序來顯示消息框,顯示我試圖用語音識別說的內容。問題是我第一次說「你好」時,例如,沒有消息框顯示。如果我再試一次,會彈出正確的消息框。在第三次我說「你好」時,顯示2個消息框。第4次,3個消息框等。任何人都可以解決這個問題嗎?問題語音識別c#

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Speech.Recognition; 

namespace Voices 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private SpeechRecognitionEngine sre; 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      sre = new SpeechRecognitionEngine(); 
      sre.SetInputToDefaultAudioDevice(); 

      Choices commands = new Choices(); 
      commands.Add(new string[] { "hello" }); 

      GrammarBuilder gb = new GrammarBuilder(); 
      gb.Append(commands); 

      Grammar g = new Grammar(gb); 
      sre.LoadGrammar(g); 

      sre.RecognizeAsync(RecognizeMode.Multiple); 


      sre.SpeechRecognized += (s, args) => 
      { 
       foreach (RecognizedPhrase phrase in args.Result.Alternates) 
       { 
        if (phrase.Confidence > 0.9f) 
         sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized); 
       } 
      }; 

     } 

     void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) 
     { 
      switch (e.Result.Text) 
      { 
       case "hello": 
        MessageBox.Show(e.Result.Text);      
        break; 
      } 
     }  
    } 
} 
+0

爲什麼你寫的'foreach'循環? – SLaks

回答

3

下面的代碼是你得到多個消息框的原因:

sre.SpeechRecognized += (s, args) => 
{ 
    foreach (RecognizedPhrase phrase in args.Result.Alternates) 
    { 
     if (phrase.Confidence > 0.9f) 
      sre.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized); 
    } 
}; 

每次SpeechRecognized升高時,它會註冊使用相同的事件處理程序相同的事件。

它應該僅向該事件註冊一次。

我猜你想要做的是以下幾點:

if (phrase.Confidence > 0.9f) 
    sre_SpeechRecognized(s, args); 
+0

它的工作!非常感謝你!!! – user1840006

4

您的內聯事件處理程序(在中)每當您說出任何內容時都添加新的事件處理程序。

+0

謝謝你的幫助! – user1840006