Wednesday, March 23, 2011

Speech Recognition Part 2 - Command Mode

As announced, this post is a sequel to the previous one, so the topic is again speech recognition, this time though the Command Mode.
As the name already suggests, the recorded sound is analyzed for specific commands. Of course you could use the previously introduced Dictation Mode and look for commands in the recorded texts yourself, but the Command Mode offers some advantages.
One the one hand it enables a continous checking, if commands were spoken, and on the other hand the recognition is better, since the program knows only the commands and thus has to distinguish just between them.
Now directly to the code: The requirements (including the ressources etc). are the same as in the previous post.
For recognizing the commands we now however use an instance of the class SpeechRecognizer. This expects also a grammar, which we now have to fill manually with words, which should be recognized
By setting the property Enabled to true, the speech recognition is activated.
When a command is recognized, the event SpeechRecognized is triggered, we assign a function to this, so we can use the event.
If a SpeechRecognizer is initialized, a window opens for speech recognition - here the user has to push the big microphone button, to start the recognition.
Pressing the button has nothing to do with the property Enabled - both have to be activated. A way to start the speech recognition only by code and to let the window stay hidden I unfortunately did not find. But I would be interested if somebody knows a way - so if someone has an idea, please let me know!
The code:

        private void StartListening()
        {
            SpeechRecognizer SR = new SpeechRecognizer();
            // register the commands
            Choices Commands = new Choices();
            Commands.Add("Stop");
            Commands.Add("Los");
            GrammarBuilder GB = new GrammarBuilder(Commands); // load the commands with a GrammerBuilder
            Grammar CommandGrammar = new Grammar(GB); // create a grammar with the GrammarBuilder
            SR.LoadGrammar(CommandGrammar); // load the grammar
            SR.SpeechRecognized += CommandRecognized; // function to handle the event
            SR.Enabled = true;
        }

        private void CommandRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            string Command = e.Result.Text;
            // here more code to process ...
        }

No comments:

Post a Comment