【问题标题】:NullReferenceException when starting recognizer with RecognizeAsync使用 RecognizeAsync 启动识别器时出现 NullReferenceException
【发布时间】:2016-09-25 10:39:04
【问题描述】:

您好,我目前正在开发一个程序,该程序应该能够识别我的声音,然后记下它听到的内容,但是当我运行代码并单击按钮启动 recEngine 时,它​​会显示“未处理的类型异常'System.NullReferenceException' 发生在 System.Speech.dll 中”,并且在提示中它说 var 之前可能为 null。但是我之前设置了变量还是我做错了什么。

这是代码

using System;
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 BtnEnable_Click(object sender, EventArgs e)
        {

这是出现错误的那一行。

            recEngine.RecognizeAsync(RecognizeMode.Multiple);
            // BtnEnable.Enabled = false;
            BtnDisable.Enabled = true;
        }

        private void Form1_Load(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.LoadGrammarAsync(grammar);
            recEngine.SetInputToDefaultAudioDevice();
            recEngine.SpeechRecognized += recEngine_SpeechRecognized;
        }

        private void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            switch (e.Result.Text)
            {
                case "say hello":
                    Log.Text += "\nHello";
                    break;
                case "print my name":
                    Log.Text += "\nMyname";
                    break;

            }
        }

        private void BtnDisable_Click(object sender, EventArgs e)
        {
            BtnEnable.Enabled = true;
            BtnDisable.Enabled = false;
            recEngine.RecognizeAsyncStop();
        }
    }
 }

在提示菜单中显示:

-在调用方法之前检查对象是否为空

-使用“new”关键字创建对象实例

提前致谢

【问题讨论】:

    标签: speech-recognition sapi


    【解决方案1】:

    一些看起来很奇怪的事情:

    • 使用recEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recEngine_SpeechRecognized); 而不是recEngine.SpeechRecognized += recEngine_SpeechRecognized;

    • 可能在您开始识别时语法尚未完成加载;使用LoadGrammar 而不是LoadGrammarAsync(或为LoadGrammarCompleted 添加处理程序)。

    • 我一直觉得明确指定识别器(和语法)的文化信息很方便,因为这样可以防止对所使用的语言产生误解。

    【讨论】:

      猜你喜欢
      • 2017-10-21
      • 1970-01-01
      • 2012-06-25
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 2020-10-31
      相关资源
      最近更新 更多