识别在停止并再次恢复后读取两次?

Recognition reads twice after stopping it and resuming it again?

我制作了一个语音处理程序对象,当我第一次用按钮打开语音识别并测试它时,它的响应很好。但是当我用一个命令停止语音识别并用按钮再次切换它时,如果我一次又一次地停止和恢复,它会重复语音两次、三次甚至更多。 这是我的代码:

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(); 
            }
        }
    }

发生这种情况是因为您向事件添加了两次处理程序,而没有在此处删除之前添加的处理程序:

_recognizer.SpeechRecognized += _recognizer_SpeechRecognized;

如果设计得当,您的代码应该如下所示:

// 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");
        }
}