我是一名編程初學者,我試圖構建一個簡單的應用程序來顯示消息框,顯示我試圖用語音識別說的內容。問題是我第一次說「你好」時,例如,沒有消息框顯示。如果我再試一次,會彈出正確的消息框。在第三次我說「你好」時,顯示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;
}
}
}
}
爲什麼你寫的'foreach'循環? – SLaks