Search code examples
c#speech-recognitionspeech-to-text

Parse first word of the command in recognized speech


I am trying to take speech input and convert them to string and show it on the richtext box control. I have read about speech synthesis and voice recognition in several articles where I learned to get commands via speech however I want to write on richtext box control after my command Write is recognized. Is it possible?

Here is the code if it helps understand what I am trying to achieve and what I have done so far

object declarations

PromptBuilder pb = new PromptBuilder();
SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();
Choices clist = new Choices();

The code for Enabling Voice Input

 private void btnEnableVoice_Click(object sender, EventArgs e)
    {
        btnEnableVoice.Enabled = false;
        btnDisableVoice.Enabled = true;

        /////////////Adding commands in a list of type Choices///////////////////////
        clist.Add(new string[] { "Is it working", "Write" });
        Grammar gr = new Grammar(new GrammarBuilder(clist));

        try
        {
            recognizer.RequestRecognizerUpdate(); ///////starting engine
            recognizer.LoadGrammar(gr);
            recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
            recognizer.SetInputToDefaultAudioDevice();
            recognizer.RecognizeAsync(RecognizeMode.Multiple);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);

        }
    }
   void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
        switch (e.Result.Text.ToString())
        { 
            case "Is it working":
                ss.SpeakAsync("Yes its working");
                break;
            case "Write":
                richTextBox1.Text += ""; //Speech to text input here
                break;
        }
    }

Solution

  • First you need to construct a grammar in a proper way to allow dictation, see for the reference http://msdn.microsoft.com/en-us/library/ms576565(v=vs.110).aspx:

     Choices clist = new Choices();
     clist.Add(new string[] { "Is it working", "Write" });
     GrammarBuilder bl = new GrammarBuilder(clist);
     bl.appendDictation();
     Grammar gr = new Grammar(bl);
    

    To parse you need something like

    void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) 
         string result = e.Result.Text.ToString();
         if (result.startsWith("Write")) {
             richTextBox1.Text += result.substring(7); // Skip first 6 chars
         } else if (result.startsWith("Is it working")) {
             ss.SpeakAsync("Yes its working");
         }
    }