Search code examples
speech-recognitionvoicesendkeys

sending continious keys with speech recognition


I want that when i say "space" it should keep inserting space until i say "stop". So here is my code:

    private void button1_Click(object sender, EventArgs e)
    {

        button2.Enabled = true;
      button1.Enabled = false;
        Choices sList = new Choices();
        sList.Add(new string[] { "space", "stop" });
        Grammar gr = new Grammar(new GrammarBuilder(sList));

        try
        {
            sRecognize.RequestRecognizerUpdate();
            sRecognize.LoadGrammar(gr);
            sRecognize.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(sRecognize_SpeechRecognized);
            sRecognize.SetInputToDefaultAudioDevice();
            sRecognize.RecognizeAsync(RecognizeMode.Multiple);

        }
        catch { return; }

     }


    void sRecognize_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {

       textBox1.Text = e.Result.Text.ToString(); 
        //throw new NotImplementedException();
        if (textBox1.Text == "space")
            //while (!e.Result.Text.ToString().Equals("stop"))
            {
                SendKeys.Send(" ");

            }
    }

As i am just a beginner, so if possible then please help me to understand your code with the comments.


Solution

  • Create a timer event that calls Sendkeys.Send(" "), then start the timer when you recognize 'space', and stop the timer when you recognize 'stop'.

    using System.Threading;
    Timer thetimer;
    void sRecognize_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
        if (e.Result.Text.ToString() == "space")
        {
            theTimer = new Timer(TimerCallback(timeExpired), 500); // 500 ms
        }
        else // if is stop
        {
            theTimer.Change(Timeout.Infinite, Timeout.Infinite); // stop the timer
        }
    }
    
    void timeExpired(Object stateInfo)
    {
        SendKeys.Send(" ");
    }
    

    There are other timer mechanisms you could use as well, but this is pretty straightforward.