C#语音识别不会回答我

时间:2019-11-19 17:48:43

标签: c# voice speech

我编写了这个简单的代码,但似乎无法识别我的声音。我尝试了一切,从使用另一个输入(麦克风)到读取异常。它总是直接变成“出事了”。有人可以检查我的代码是否有错误?或者,如果您遇到相同的问题,我该如何解决?我也在互联网上搜索了一段时间,但找不到正确的答案。

代码:

using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Synthesis;
using System.Speech.Recognition;
using System.Threading;

namespace voice_bot
{
    public partial class Form1 : Form
    {
        SpeechSynthesizer s = new SpeechSynthesizer();
        Choices list = new Choices();
        public Form1()
        {
            SpeechRecognitionEngine rec = new SpeechRecognitionEngine();

            list.Add(new String[] { "hello", "how are you" });

            Grammar gr = new Grammar(new GrammarBuilder(list));
            s.Speak("hello, my name is voice bot. If you would like to talk with me, go ahead");

            try
            {
                rec.RequestRecognizerUpdate();
                rec.LoadGrammar(gr);
                rec.SpeechRecognized += rec_SpeachRecognized;
                rec.SetInputToDefaultAudioDevice();
                rec.RecognizeAsync(RecognizeMode.Multiple);
            }
            catch (Exception e)
            {
                s.Speak("Something went wrong");    
            }          

        }

        public void say(String h)
        {
            s.Speak(h);
        }





        private void rec_SpeachRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            string r = e.Result.Text;


            if (r == "hello")
            {            
                s.Speak("hi");                
            }

            if (r == "how are you")
            {
                s.Speak("good, how are you?");               
            }
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:0)

我不确定您要在哪个平台上进行尝试,但是System.Speech的版本非常老。

您可能会尝试使用Microsoft提供的最新语音平台(请注意:我在System.Speech和此最新语音平台上都工作过)。您可以在以下位置签出新平台:https://aka.ms/speech/sdk。有很多示例可以帮助您快速找到可行的解决方案,并且可以在“所有”现代平台操作系统(Windows,Linux,Android,iOS,Mac等)上以及通过“所有”现代编程语言运行(C ++,C#,Java,JavaScript,Python,Objective-C,Swift等...)

-抢劫