必须加载至少一个语法错误c# [英] At least one grammar must be loaded error c#

查看:117
本文介绍了必须加载至少一个语法错误c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿!

所以我的语音识别程序有问题。它给了我这个错误:在进行识别之前必须至少加载一个语法。无论如何这里代码。



谢谢!



 使用系统; 
使用 System.Collections.Generic;
使用 System.ComponentModel;
使用 System.Data;
使用 System.Drawing;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;
使用 System.Windows.Forms;
使用 System.Speech.Synthesis;
使用 System.Speech.Recognition;
使用 System.Diagnostics;

命名空间 Speech_Recognition_test_3
{
public partial class Form1:Form
{
private static SpeechSynthesizer synth = new SpeechSynthesizer();
private static SpeechRecognitionEngine recEngine = new SpeechRecognitionEngine();

public Form1()
{
InitializeComponent();
}

private void button1_Click( object sender,EventArgs e)
{
// kokliknešzačneposlušati
这里显示错误
recEngine.RecognizeAsync(RecognizeMode.Multiple);
// enable-a drugi按钮
button2.Enabled = ;
}

private void Form1_Load( object sender,EventArgs e)
{
Choices toDo = new Choices();
toDo.Add( new string [] { 打开itunes 打开chrome 打开文件资源管理器});

// naredi grammar ki ga program uporablja za preverjanje izgoverjene besede
GrammarBuilder grammarBuilder = new GrammarBuilder();
grammarBuilder.Append(toDo);
语法语法= new 语法(grammarBuilder);

// Začneuporabljati语法
在这里据说加载语法
recEngine.LoadGrammarAsync(grammar);
// Tuseduočidefaultnaprava za snemanje
recEngine.SetInputToDefaultAudioDevice() ;
recEngine.SpeechRecognized + = recEngine_SpeechRecognised;
}

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

public static void recEngine_SpeechRecognised( object sender,SpeechRecognizedEventArgs e)
{
switch (e.Result.Text)
{

case open itunes
MessageBox.Show( 打开iTunes);
break ;
case open chrome
MessageBox.Show( 打开谷歌浏览器);
break ;
case 打开文件资源管理器
MessageBox.Show( 我不能这样做);
break ;
}
}

私有 void richTextBox1_TextChanged( object sender,EventArgs e)
{

}

private void button3_Click( object sender,EventArgs e)
{
MessageBox.Show( Hello World!);
}
}
}





我尝试了什么:



我不知道该尝试什么。 ///////////////////////////

解决方案

这里出了点问题。正如你所展示的那样,代码甚至无法编译。您不能将 string [] 附加到语法构建器,您必须附加 Choice 的实例。这是一个正确的代码片段:

  string  [] phrase =  new   string  [] {
// ...
}
选择choiceSet = 选择(短语);
GrammarBuilder grammarBuilder = new GrammarBuilder();
grammarBuilder.Append(choiceSet);

或者,甚至更简单

  string  [] phrase =  new   string  [] {
// ...
}
选择choiceSet = new 选择(短语);
GrammarBuilder grammarBuilder = new GrammarBuilder(choiceSet);





除此之外(叹气)......令人惊讶的是,与识别器一起使用的公寓模型有一个非常非常潜意识的问题。有两种不同的引擎。根据平台和可能的.NET版本,引擎 System.Speech.Recognition.SpeechRecognitionEngine 需要[MTAThread],另一个 System.Speech.Recognition .SpeechRecognizer ,requries [STAThread]。



由于某种原因,错误选择公寓状态会导致您报告的消息。不久之前,我很快就弄明白了,因为微软的初步样本有效,可以用于比较。然而,当我从XP切换到Windows 7时,这个问题已经消失,其中两个引擎都与两个公寓状态中的任何一个一起工作。并非所有应用程序类型都允许为主线程选择任何公寓状态,但您可以随时在您可以使用所需公寓状态创建的其他线程中完成所有工作。



所以,首先,按照我上面的代码片段,如果它还没有工作,尝试更改公寓状态。在你提出一些后续问题之前,请先尝试一下,然后告诉我们你的操作系统版本,.NET版本和引擎类型。



顺便说一下,这个答案是基于我刚刚完成的测试。一切都有效。如果你愿意,我会给你一个完整的样本,但在你尝试修改你的代码之后,请。







正如我所承诺的,这是一个功能齐全的样本:

  namespace  SpeechConsole {
使用系统;
使用 System.Speech.Recognition;

class 计划{

const string QuiteCommand = 退出; // ,离开这里;
const string RepeatInstructionCommand = 重复指令;
const string ShutUpCommand = 闭嘴;

void 运行(){
尝试 {
string [] phrase = new string [] {
10 上一页 记住 忘记 保存
RepeatInstructionCommand,ShutUpCommand,QuiteCommand,};
Choices choiceSet = new 选择(短语);
GrammarBuilder grammarBuilder = new GrammarBuilder(choiceSet);
grammarBuilder.Append(choiceSet);
SpeechRecognitionEngine engine = new SpeechRecognitionEngine();
// 另一个有效的选项:
// SpeechRecognizer engine = new SpeechRecognizer();
engine.LoadGrammar( new 语法(grammarBuilder));
engine.RecognizeCompleted + =(source,eventInfo)= > {
// ...
}; // engine.RecognizeCompleted
engine.SpeechRecognitionRejected + =(source,eventInfo)= > {
Console.WriteLine( 什么你到底想说什么?!);
}; // engine.SpeechDetected
engine.SpeechRecognized + =(source,eventInfo)= > {
Console.WriteLine( @ 检测到:{0},eventInfo.Result.Text);
if (eventInfo.Result.Text == QuiteCommand)
System.Diagnostics.Process.GetCurrentProcess()。Kill();
if (eventInfo.Result.Text == RepeatInstructionCommand)
Instructions(phrase);
}; // engine.SpeechRecognized
engine.SetInputToDefaultAudioDevice();
说明(短语);
engine.RecognizeAsync(RecognizeMode.Multiple);
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
} catch (例外e){
Console.WriteLine( {0}:{1},e.GetType()。Name,e.Message);
} // exception
} // 运行

void 说明( string []短语){
Console.WriteLine( 说出以下其中一项:);
foreach 字符串提示 in 短语)
Console.WriteLine( + prompt);
Console.WriteLine();
} // 说明

// [System.MTAThread]
// < span class =code-comment>重要!语音识别在某些系统上无法在STAThread上运行

// 在这种情况下,请使用默认值(根本没有属性)
// 或[System.MTAThread]但不是[系统.STAThread]
静态 void Main(){
Console .Title = Ctrl + C或说\退出以退出;
new Program()。Run();
} // 主要

} // 类程序

} // 命名空间SpeechConsole





-SA

Hey!
So i'm having problem with my speech recognition program. It gives me this error: "At least one grammar must be loaded before doing a recognition." Anyways here the code.

Thanks!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Synthesis;
using System.Speech.Recognition;
using System.Diagnostics;

namespace Speech_Recognition_test_3
{
    public partial class Form1 : Form
    {
        private static SpeechSynthesizer synth = new SpeechSynthesizer();
        private static SpeechRecognitionEngine recEngine = new SpeechRecognitionEngine();

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //ko klikneš začne poslušati
            Here it shows me the error
            recEngine.RecognizeAsync(RecognizeMode.Multiple);
            //enable-a drugi button
            button2.Enabled = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Choices toDo = new Choices();
            toDo.Add(new string[] { "open itunes", "open chrome", "open file explorer" });

            //naredi grammar ki ga program uporablja za preverjanje izgoverjene besede
            GrammarBuilder grammarBuilder = new GrammarBuilder();
            grammarBuilder.Append(toDo);
            Grammar grammar = new Grammar(grammarBuilder);

            //Začne uporabljati grammar
            Here it loads the grammar supposedly
            recEngine.LoadGrammarAsync(grammar);
            //Tu se določi default naprava za snemanje
            recEngine.SetInputToDefaultAudioDevice();
            recEngine.SpeechRecognized += recEngine_SpeechRecognised;
        }

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

        public static void recEngine_SpeechRecognised(object sender, SpeechRecognizedEventArgs e)
        {
            switch (e.Result.Text)
            {
                
                case "open itunes":
                    MessageBox.Show("Opening iTunes");
                    break;
                case "open chrome":
                    MessageBox.Show("Opening Google Chrome");
                    break;
                case "open file explorer":
                    MessageBox.Show("I cant do that");
                    break;
            }
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
                MessageBox.Show("Hello World!");
        }
    }
}



What I have tried:

I don't know what to try. ///////////////////////////

解决方案

Something is wrong here. The code, as you show it, could not even compile. You cannot append string[] to a grammar builder, you have to append an instance of Choice. This is a correct code fragment:

string[] phrases = new string[] {
   // ...
}
Choices choiceSet = new Choices(phrases);
GrammarBuilder grammarBuilder = new GrammarBuilder();
grammarBuilder.Append(choiceSet);

or, even simpler

string[] phrases = new string[] {
   // ...
}
Choices choiceSet = new Choices(phrases);
GrammarBuilder grammarBuilder = new GrammarBuilder(choiceSet);



In addition to that (sigh)… there is a very, very subliminal problem related, surprisingly, to apartment model you are using with the recognizer. There are two different engines. Depending on the platform and probably .NET version, the engine System.Speech.Recognition.SpeechRecognitionEngine requires [MTAThread], another one System.Speech.Recognition.SpeechRecognizer, requries [STAThread].

Wrong choice of the apartment state, by some reason, cause the message you reported. A while ago, I quickly figured it out, because rudimentary Microsoft samples worked and could be used for comparison. However, this problem has gone when I switched from XP to Windows 7, where both engines works with either of the two apartment states. Not all application types allow to chose any apartment state for a main thread, but you can always do all your work in some other thread you can create with required apartment state.

So, first, follow my code fragment above and, if it does not yet work, try to change apartment state. Before you ask some follow up questions, please try it out and then tell us you OS version, .NET version and type of the engine.

By the way, this answer is based on testing I've just done. All works. If you want, I'll give you a complete sample, but after your try to fix your code, please.

[EDIT]

As I promised, this is a fully functional sample:

namespace SpeechConsole {
    using System;
    using System.Speech.Recognition;

    class Program {

        const string QuiteCommand = "Quit"; //, "Go out of here";
        const string RepeatInstructionCommand = "Repeat instructions";
        const string ShutUpCommand = "Shut up";

        void Run() {
            try {
                string[] phrases = new string[] {
                    "10", "Previous", "Remember", "Forget", "Save",
                    RepeatInstructionCommand, ShutUpCommand, QuiteCommand, };
                Choices choiceSet = new Choices(phrases);
                GrammarBuilder grammarBuilder = new GrammarBuilder(choiceSet);
                grammarBuilder.Append(choiceSet);
                SpeechRecognitionEngine engine = new SpeechRecognitionEngine();
                // another option which works:
                //SpeechRecognizer engine = new SpeechRecognizer();
                engine.LoadGrammar(new Grammar(grammarBuilder));
                engine.RecognizeCompleted += (source, eventInfo) => {
                    // ...
                }; //engine.RecognizeCompleted
                engine.SpeechRecognitionRejected += (source, eventInfo) => {
                    Console.WriteLine("What the hell you're trying to say?!");
                }; //engine.SpeechDetected
                engine.SpeechRecognized += (source, eventInfo) => {
                    Console.WriteLine(@"Detected: ""{0}""", eventInfo.Result.Text);
                    if (eventInfo.Result.Text == QuiteCommand)
                        System.Diagnostics.Process.GetCurrentProcess().Kill();
                    if (eventInfo.Result.Text == RepeatInstructionCommand)
                        Instructions(phrases);
                }; //engine.SpeechRecognized
                engine.SetInputToDefaultAudioDevice();
                Instructions(phrases);
                engine.RecognizeAsync(RecognizeMode.Multiple);
                System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
            } catch (Exception e) {
                Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message);
            } //exception
        } //Run

        void Instructions(string[] phrases) {
            Console.WriteLine("Say one of the following:");
            foreach (string prompt in phrases)
                Console.WriteLine("           " + prompt);
            Console.WriteLine();
        } //Instructions

        // [System.MTAThread]
        // IMPORTANT! speech recognition will not work on STAThread on some systems
        // In this case, use default (no attribute at all)
        // or [System.MTAThread] but not [System.STAThread]
        static void Main() {
            Console.Title = "Ctrl+C or say \"Quit\" to exit";            
            new Program().Run();
        } //Main

    } //class Program

} //namespace SpeechConsole



—SA


这篇关于必须加载至少一个语法错误c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆