我是一名编程初学者,我试图构建一个简单的应用程序来显示消息框,显示我试图用语音识别说的内容。问题是我第一次说“你好”时,例如,没有消息框显示。如果我再试一次,会弹出正确的消息框。在第三次我说“你好”时,显示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