使用Microsoft.Speech或System.Speech命名空间进行语音识别

时间:2015-03-30 07:29:16

标签: c#

我正在尝试在C#桌面应用程序中使用语音识别,如果用户说“按3”或“按4”,那么该数字应该写在图表上(比如标签)。我能够识别用户说出的“按下”这个词,但不能超出这个范围。请帮忙。以下是我的示例代码:

    string txtSpoken = "";
    string[] words = new string[10];

    public Form1()
    {
        InitializeComponent();

        SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();
        _recognizer.LoadGrammar(new Grammar(new GrammarBuilder("press")) { Name = "pressGrammar" }); // load a grammar
        _recognizer.SpeechRecognized += _recognizer_SpeechRecognized;
        _recognizer.SetInputToDefaultAudioDevice(); // set the input of the speech recognizer to the default audio device
        _recognizer.RecognizeAsync(RecognizeMode.Multiple); // recognize speech asynchronous
        // _recognizer.Recognize();
    }

    void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
        string txt = e.Result.Text;
        this.Invoke(new MethodInvoker(() =>
        {
            listBox1.Items.Add("I heard you say: "
                + txt);
        })); // WinForm specific

        if (e.Result.Text == "press") // e.Result.Text contains the recognized text
        {
            textBox1.Text = "3";
            label1.Text += " 3 ";
            //   MessageBox.Show("The test was successful!");
        }

        txtSpoken += e.Result.Text;
        MessageBox.Show(txtSpoken);


        if (txt.IndexOf("press") >= 0)
        {
            words = txt.Split(' ');
        }
    }

1 个答案:

答案 0 :(得分:0)

问题是,你的语法只包含单词press。对于用户语音和语法之间的匹配,用户必须完全说出语法中的一个元素。 我建议您创建Choices,例如:

Choices inputs = new Choices();
inputs.Add(new string[] {"press 3", "press 4"});

GrammarBuilder gb = new GrammarBuilder();
gb.Append(inputs);
Grammar g = new Grammar(gb);
_recognizer.LoadGrammar(g);

有关详细信息,请参阅this tutorial