如何阻止语音识别引擎聆听自己的演讲

时间:2016-01-15 17:21:52

标签: c#

我用C#编写了一个语音识别引擎

    public partial class MainWindow : Window
    {

        SpeechRecognitionEngine _recognizer;
        SpeechSynthesizer sre = new SpeechSynthesizer();
        int count = 1;

    public MainWindow()
    {
        InitializeComponent();
        Initialize();
    }

    private void Initialize()
    {
        try
        {
            var culture = new CultureInfo("en-US");
            _recognizer = new SpeechRecognitionEngine(culture);
            _recognizer.SetInputToDefaultAudioDevice();
            _recognizer.LoadGrammar(GetGrammer());
            _recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(_recognizer_SpeechRecognized);

            _recognizer.RecognizeAsync(RecognizeMode.Multiple);

            sre.SelectVoiceByHints(VoiceGender.Male, VoiceAge.Child);
            sre.Rate = -2;

        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.InnerException.Message);
        }
    }

    private static Grammar GetGrammer()
    {

        var choices = new Choices();
        //add custom commands
        choices.Add(File.ReadAllLines(@"Commands.txt"));
        //to add the letters to the dictionary
        choices.Add(Enum.GetNames(typeof(Keys)).ToArray());

        var grammer = new Grammar(new GrammarBuilder(choices));

        return grammer;
    }

    void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {

        string speech = e.Result.Text; 

    //to type letters in open application like notepad
   if (Enum.GetNames(typeof(Keys)).Contains(speech))
    {
        try
        {   //send the string to the application
            SendKeys.SendWait("{" + speech + "}");
        }
        catch (ArgumentException)
        {

        }            
    }  

    //handle custom commands
        switch (speech)
        {
             case "day":
                sre.Speak("Friday");
                break;
        }
    }       
}
// where speech receives the text which the user speaks and also present in the loaded grammar (text file)

我的代码生成一个语音识别引擎,如果用户询问&#34; day&#34;它回复&#34;星期五&#34;而这反过来又有一个&#34; day&#34;在里面。所以它继续循环并继续回复&#34;星期五&#34;。什么是在发言时停止发动机聆听的最佳方法。

注意:我知道语法可以改变为令人信服的方式,例如&#34;它是什么日子&#34;但我需要它作为&#34; day&#34;本身。

此外,我不提供可重现的代码,因为这个问题可能是我遗漏了一些基本的东西。我已尝试使用某些StackOverflow问题中建议的bool bAbleToListen=true;。但是,无法找到它有用

2 个答案:

答案 0 :(得分:1)

您正在将RecognizeMode.Multiple传递给RecognizeAsync方法。

  

多个
      System.Speech.Recognition.RecognizeMode

的成员      

摘要:
指定识别不会在之后终止   完成。

所以也许你希望它在Speak之后终止并重新开始?

_recognizer.SpeechRecognized += (sender, args) =>
{
    sre.Speak("trololo");
    _recognizer.RecognizeAsync(RecognizeMode.Single);
};

_recognizer.RecognizeAsync(RecognizeMode.Single);

答案 1 :(得分:1)

rebase -p

如果语音合成器正在讲话,则不要运行收听代码。