使用.net语音API在SRGS语法中引用外部规则时出错

本文关键字:外部 引用 规则 出错 语法 语音 net API SRGS 使用 | 更新日期: 2023-09-27 18:21:34

下面的程序是一个简单的C#语音识别控制台应用程序,使用Microsoft托管语音API,只识别单词"yes"answers"no"。当我使用Srgs方法内联创建Srgs规则"MyRule"时,一切都正常。但是,如果我将规则放在外部XML文件中并创建SrgsRuleRef来引用它,我总是会收到错误:"无法解析对导入语法的规则引用。",媒体类型和语义标签格式,但似乎没有任何区别。

using System;
using System.Speech.Recognition;
using System.Speech.Recognition.SrgsGrammar;
namespace SpeechRecognitionConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                System.Globalization.CultureInfo culture = 
                    new System.Globalization.CultureInfo("en-US");
                SrgsRule RootRule = new SrgsRule("RootRule");
                RootRule.Add(new SrgsRuleRef(
                    new Uri("c:''projects.net''speechrecognitionconsole''MyGrammar.xml"), "MyRule"));
                RootRule.Scope = SrgsRuleScope.Public;
                SrgsDocument MyDocument = new SrgsDocument(RootRule);
                MyDocument.Culture = culture;
                Grammar g = new Grammar(MyDocument);
                g.Name = ("MyGrammar");
                SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine(culture);
                recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>
                                               (recognizer_SpeechRecognized);
                recognizer.LoadGrammar(g);
                recognizer.SetInputToDefaultAudioDevice();
                recognizer.RecognizeAsync(RecognizeMode.Multiple);
                Console.WriteLine("Starting asynchronous recognition...");
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            Console.WriteLine(e.Result.Text);
        }
    }
}

语法文件"c:''projects.net''speechidentificationconsole''MyGrammar.xml"包含:

<?xml version="1.0" encoding="utf-8"?>
<grammar xml:lang="en-US" tag-format="semantics/1.0" version="1.0" xmlns="http://www.w3.org/2001/06/grammar">
  <rule id="MyRule" scope="public">
    <one-of>
      <item>yes</item>
      <item>no</item>
    </one-of>
  </rule>
</grammar>

使用.net语音API在SRGS语法中引用外部规则时出错

为了在今天使用Visual Studio 2013实现这一点,我不得不添加root="MyRule",不确定在2012年被问到这个问题时,同样的修复是否会有所帮助。

<?xml version="1.0" encoding="utf-8"?>
<grammar xml:lang="en-US" tag-format="semantics/1.0"
 version="1.0" xmlns="http://www.w3.org/2001/06/grammar" root="MyRule">
  <rule id="MyRule" scope="public">
    <one-of>
      <item>yes</item>
      <item>no</item>
    </one-of>
  </rule>
</grammar>