C# grammar and switch wildcard

2019-04-17 11:30发布

问题:

I would like to add, that whenever it recognizes 'search X' it is going to search for 'X', but i don't know how i have to add that to the grammar, or how to do such a thing with my switch statement.

private void Form1_Load(object sender, EventArgs e)
{
    Choices commands = new Choices();
    commands.Add(new string[] { "hello", "start chrome", "search" });
    GrammarBuilder gBuilder = new GrammarBuilder();
    gBuilder.Append(commands);
    gBuilder.Culture = new System.Globalization.CultureInfo("en-GB");
    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 "hello":
            synthesizer.SpeakAsync("Hello! How are you doing today?");
            break;
        case "start chrome":
            Process.Start("http://www.google.com");
            break;
        case "search":
            SearchChrome("search");
            break;
    }
}

static void SearchChrome(string searchterm)
{
    Process.Start("https://www.google.com/search?q=" + searchterm);
}

So i'd like to add to my grammar "Search X", and to my cases "Search X", with it searching for whatever X is.

Thanks in advance!

回答1:

You must make a more complex grammar. The type of grammar rule you chose is the Choice one. It doesn't suit exactly what you wanna do as you want to capture what follows a keyword. To capture the following you must use the SemanticResultKey rule. It is explained here: https://docs.microsoft.com/en-us/dotnet/api/system.speech.recognition.semanticresultkey?view=netframework-4.7.2

The example matches exactly what you want: it extracts the password from the expression "My password is ....."