Search code examples
c#speech-recognitionspeech-synthesis

Recognition reads twice after stopping it and resuming it again?


I made a speech handler object and when I switch on the speech recognition with a button in the first time and test it, it responds just fine. but when I stop the speech recognition with a command and switch it again with the button it repeats the speech twice and thrice and more if I stop and resume again and again. here is my code:

private void simpleButton1_Click(object sender, EventArgs e)
    {
        try
        {
            JARVIS.Dispose();
            JARVIS= new SpeechSynthesizer();
            JARVIS.Speak("How can i help you sir?");
            _recognizer.LoadGrammar(new Grammar(new GrammarBuilder("test")));
            _recognizer.LoadGrammar(new Grammar(new GrammarBuilder("good bye")));

            _recognizer.SpeechRecognized += _recognizer_SpeechRecognized;
            _recognizer.SetInputToDefaultAudioDevice();
            _recognizer.RecognizeAsync(RecognizeMode.Multiple);
        }
        catch
        {

        }
    }
    private void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
        try
        {

            if (e.Result.Text == "test") // e.Result.Text contains the recognized text
            {
                JARVIS.Speak("Test was successful!!");
            }
            if (e.Result.Text == "good bye")
            {
                JARVIS.Speak("Good Bye sir");
                JARVIS.Dispose(); 
            }
        }
    }

Solution

  • This happens because you add handler to the event two times without removing the previously added one here:

    _recognizer.SpeechRecognized += _recognizer_SpeechRecognized;
    

    If designed properly your code should look like this:

    // invoke this method only once when you setup the whole system
    private void init() {
            JARVIS= new SpeechSynthesizer();
            _recognizer.LoadGrammar(new Grammar(new GrammarBuilder("test")));
            _recognizer.LoadGrammar(new Grammar(new GrammarBuilder("good bye")));
            _recognizer.SpeechRecognized += _recognizer_SpeechRecognized;
            _recognizer.SetInputToDefaultAudioDevice();
    
    }
    
    // Recognizer is already configured, just speak and recognize
    private void simpleButton1_Click(object sender, EventArgs e)
    {
            JARVIS.Speak("How can i help you sir?");
            _recognizer.RecognizeAsync(RecognizeMode.Multiple);
    }
    
    // Handler for recognition results
    private void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
            if (e.Result.Text == "test") { // e.Result.Text contains the recognized text
                JARVIS.Speak("Test was successful!!");
            }
            if (e.Result.Text == "good bye") {
                JARVIS.Speak("Good Bye sir");
            }
    }