I’m a beginner in programming and I’m trying to build a simple application to display message box that shows what I tried to say using voice recognition. The problem is when I say “hello” for the first time, for example, no message box is displayed. If I try one more time, a correct message box is played. In the third time that I say “hello”, 2 message boxes are displayed. In the 4th time, 3 message boxes, and so on. Can anyone help with this problem?
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;
}
}
}
}
Following code is the reason you get multiple message boxes:
Everytime SpeechRecognized is raised, it registers to the same event with the same eventhandler.
It should register to the event only once.
I guess what you want to do is following: