Search code examples
uwplinq-to-xmlspeech-recognitionxmldocumentspeech

How to implement cross-platform SRGs grammar from .NET to UWP


I have two applications that are communicating with each other remotely. One application (call it "A") needs to define some custom grammar for a speech recognition engine running in a remote UWP application (call this one application "B"). I'd like to use a custom class that encapsulates the grammar rules as well as some other ancillary data, and since this class must cross between the full .NET framework (4.7) and UWP framework I am looking into implementing it into a .NET Standard 2.0 class library that both applications reference. As for the grammar, the best way seems to be SRGS constraints specified as XML (https://learn.microsoft.com/en-us/windows/uwp/design/input/define-custom-recognition-constraints) since both application A and B will be able to create Xml. I anticipate the Xml to either be created programmatically or loaded from a file. The encapsulating custom grammar objects will be created on application A and then transmitted to application B and will generally look something like this:

public class MyCustomGrammarStuff()
{
    public Int32 Data1 { get; set; }
    public Int32 Data2 { get; set; }
    public String Stuff { get; set; }
    public XmlDocument GrammarRules {get; set; } // Loaded from file or created in code.
}

When application A receives this object it must then instantiate a "SpeechRecognitionGrammarFileConstraint" object using "GrammarRules" in the "MyCustomGrammarStuff" object. According to the documentation for this class (https://learn.microsoft.com/en-us/uwp/api/Windows.Media.SpeechRecognition.SpeechRecognitionGrammarFileConstraint) the constructor takes an argument of type "Windows.Storage.StorageFile".

My question is how to I take the XmlDocument object and use it to programmatically instantiate a StorageFile object? I'd prefer not to start doing things like writing/loading from temporary files.


Solution

  • If you want a StorageFile, you could create one in some folder and then write all XML data to it like this:

    XmlDocument xmlDocument = ...;
    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename.xml");
    await FileIO.WriteTextAsync(file, xmlDocument.ToString());