无法开始识别:在进行识别之前必须至少加载一个语法

时间:2014-11-21 15:59:11

标签: c# speech-recognition

我试图制作一个基本的语音识别应用程序,但我遇到了错误。 当我单击启用按钮时,我收到以下错误: 在进行识别之前必须至少加载一个语法

即使我设置并加载了一个。 有人可以帮帮我吗?

这是我的代码:

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 Voice_Recognition
{
    public partial class Form1 : Form
    {
        SpeechRecognitionEngine recEngine = new SpeechRecognitionEngine();
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            recEngine.RecognizeAsyncStop();
            btnDisable.Enabled = false;
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            Choices commands = new Choices();
            commands.Add(new String[] { "Say Hello", "Print my name" });
            GrammarBuilder gBuilder = new GrammarBuilder();
            gBuilder.Append(commands);
            Grammar grammar = new Grammar(gBuilder);

            recEngine.LoadGrammar(grammar);
            recEngine.SetInputToDefaultAudioDevice();
            recEngine.SpeechRecognized +=new EventHandler<SpeechRecognizedEventArgs>(recEngine_SpeechRecognized);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            recEngine.RecognizeAsync(RecognizeMode.Multiple);
            btnDisable.Enabled = true;
        }
        void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            switch (e.Result.Text)
            {
                case "Say Hello":
                    MessageBox.Show("Hello Andrea");
                    break;
                case "Print my name":
                    richTextBox1.Text += "\nAndrea";
                    break;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

richTextBox1_TextChanged方法中的代码放在Form1构造函数中。就目前而言,每次文本更改时都会重新加载语法,但是在程序启动时它没有被加载(并且方法连接代码将无缘无故地被多次调用)。因此,如果您在框中输入任何内容之前单击按钮,则不会实例化语法。