问题
Hello i try to create simple AI program , so i define two grammar and load them and i get this error at least one grammar must be loaded before doing a recognition. the error from visual studio is :
An exception of type 'System.InvalidOperationException' occurred in System.Speech.dll but was not handled in user code
Additional information: At least one grammar must be loaded before doing a recognition.
here is the code this is the class
class DefineGrammar
{
/// <summary>
/// Define Choices
/// </summary>
Choices greeting;
Choices DateAndTime;
/// <summary>
/// Define the Grammar var
/// </summary>
Grammar greetingGrammar;
Grammar DateAndTimeGrammar;
SpeechRecognitionEngine rec = new SpeechRecognitionEngine();
public void LoadGrammar()
{
// put the data inside the choice
greeting = new Choices(new string[] { "hello", "how are you" });
DateAndTime = new Choices(new string[] { "what time is it", "what is today" });
// Define Grammar builder to put the choice inside it
GrammarBuilder greetingGrammarBuillder = new GrammarBuilder(greeting);
GrammarBuilder DateAndTimeGrammarBuilder = new GrammarBuilder(DateAndTime);
//put the grammar builder inside the grammar
greetingGrammar = new Grammar(greetingGrammarBuillder);
greetingGrammar.Name = "GreetingGrammar";
DateAndTimeGrammar = new Grammar(DateAndTimeGrammarBuilder);
DateAndTimeGrammar.Name = "DateAndTimeGrammar";
rec.LoadGrammar(greetingGrammar);
rec.LoadGrammar(DateAndTimeGrammar);
}
}
and here is the main page :
public partial class MainWindow : Window
{
SpeechSynthesizer s = new SpeechSynthesizer();
SpeechRecognitionEngine rec = new SpeechRecognitionEngine();
DefineGrammar gr = new DefineGrammar();
public MainWindow()
{
rec.RequestRecognizerUpdate();
gr.LoadGrammar();
rec.SpeechRecognized += Rec_SpeechRecognized;
rec.SetInputToDefaultAudioDevice();
rec.RecognizeAsync(RecognizeMode.Multiple);
}
}
回答1:
In your DefineGrammar class, you have a member field of type SpeechRecognitionEngine to which you load the grammar if LoadGrammar()
is invoked.
In your main class, you have a different instance of that type on which you try to invoke recognition.
Now, the error is that you have two separate instances of SpeechRecognitionEngine.
One way to solve this could be to change your DefineGrammar as follows:
Instead of public void LoadGrammar()
make it public void LoadGrammar( SpeechRecognitionEngine rec )
and remove the member field rec
in that class.
There are other possibilities but this will do the job. The difference is that now you load the Grammar to the instance that is used in your main class, not a different one.
来源:https://stackoverflow.com/questions/41760897/at-least-one-grammar-must-be-loaded-before-doing-a-recognition