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

时间:2015-05-10 22:16:21

标签: c# speech-recognition speech-synthesis

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

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

1 个答案:

答案 0 :(得分:1)

这是因为您在事件中添加处理程序两次而不删除之前添加的处理程序:

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