发出语音识别c#

时间:2012-11-28 16:46:34

标签: c#

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

2 个答案:

答案 0 :(得分:4)

你的内联事件处理程序(在Form_Load中)每次你说什么都会添加新的事件处理程序。

答案 1 :(得分: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);