问题
Hi i'm currently developing a program that is supposed to recognize my voice and then write down what it hears, but when i run the code and i click the buttun to start the recEngine it says that "An unhandled exception of type 'System.NullReferenceException' occurred in System.Speech.dll", and in the tips it says that it's possible that the var was null before. But i have setted the variable before or am i doing something wrong.
Here is the Code
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)
{
This is the line where the error shos up.
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();
}
}
}
In the tips Menu it says:
-Check to determine if the object was null before calling the method
-Use the "new" Keyword to create an object instance
Thanks in advance
回答1:
A couple of things that look odd:
use
recEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recEngine_SpeechRecognized);
instead ofrecEngine.SpeechRecognized += recEngine_SpeechRecognized;
It's possible the grammar hasn't completed loading by the time you start recognition; use
LoadGrammar
instead ofLoadGrammarAsync
(or add a handler forLoadGrammarCompleted
).I've always found it handy to explicitly specify the cultureinfo for the recognizer (and the grammar), as that prevents misunderstandings about what language is being used.
来源:https://stackoverflow.com/questions/39685914/nullreferenceexception-when-starting-recognizer-with-recognizeasync