嗨,我目前正在开发一个程序,应该识别我的声音,然后写下它听到的,但是当我运行代码,我点击按钮启动recEngine,它说"类型'系统的未处理的异常。NullReferenceException'在System.Speech.dll中发生',在提示中它说var之前可能是空的。但是我之前已经设置了变量,或者我做错了什么。
下面是代码
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"关键字创建对象实例
Thanks in advance
一些看起来很奇怪的事情:
-
用
recEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recEngine_SpeechRecognized);
代替recEngine.SpeechRecognized += recEngine_SpeechRecognized;
-
当你开始识别时,语法可能还没有完成加载;
使用 我总是发现为识别器显式指定文化信息(和语法)很方便,因为这可以防止对正在使用的语言产生误解。
LoadGrammar
代替LoadGrammarAsync
(或为LoadGrammarCompleted
添加处理程序)。