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

最佳答案

以下代码是您获得多个消息框的原因:

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);

关于c# - 发出语音识别C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13610157/

10-13 06:26