我是编程的初学者,我正在尝试构建一个简单的应用程序来显示消息框,该消息框显示了我试图使用语音识别说的话。问题是当我第一次说“你好”时,例如没有显示消息框。如果我再试一次,就会播放一个正确的消息框。在我第三次说“你好”时,会显示 2 个消息框。第 4 次,3 个消息框,以此类推。任何人都可以帮助解决这个问题吗?
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;
}
}
}
}