语音识别-如果说hello或hi

本文关键字:hi hello 如果说 语音识别 | 更新日期: 2023-09-27 17:50:02

在c#中,我希望某些代码在我说hello或hi时运行。当我说hello的时候,它会运行代码但是我不知道怎么做,所以如果我说hi,它也会运行代码。我不想对两者都做一个完整的if声明,因为我希望在未来做很多事情,(你好,嗨,嘿,你好吗,等等)。这是我到目前为止的代码:

using System;
using System.Windows.Forms;
using System.Speech.Recognition;

namespace Voice_Recognition
{
    public partial class Form1 : Form
    {
        SpeechRecognitionEngine recEngine = new SpeechRecognitionEngine();
        public Form1()
        {
            InitializeComponent();
        }
        private void btnEnable_Click(object sender, EventArgs e)
        {
            recEngine.RecognizeAsync(RecognizeMode.Multiple);
            btnDisable.Enabled = true;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            Choices commands = new Choices();
            commands.Add(new string[] { "Hello", "Hey", "Hi" });
            GrammarBuilder gBuilder = new GrammarBuilder();
            gBuilder.Append(commands);
            Grammar grammar = new Grammar(gBuilder);
            gBuilder.Culture = new System.Globalization.CultureInfo("en-US");
            recEngine.LoadGrammarAsync(grammar);
            recEngine.SetInputToDefaultAudioDevice();
            recEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recEngine_SpeechRecognized);
        }
        void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            string B = "'nBRIAN: ";
            string J = "'nYOU: ";
            string said = e.Result.Text;
            if (said == "Hello")
            {
                richTextBox1.Text += J + "Hello";
                string[] Hello = { "Hello.", "Hi.", "Hey.", "What's up?", "Howdy.", "Nice to see you.", "Hey, how are you going?", "Yo.", "Hiya", "Sup.", "Wassup?",
                        "What's crackin?", "How you goin'?", "What's new?", "How are you?",
                        "Hello Jake.", "Hi Jake.", "Hey Jake.", "What's up Jake?", "Howdy Jake.", "Nice to see you Jake", "Hey, how are you going Jake?", "Yo Jake.",
                        "Hiya Jake.", "Sup Jake?", "Wassup Jake?", "How you goin' Jake?", "What's new Jake?", "How are you Jake?"};
                richTextBox1.Text += B + Hello[new Random().Next(0, Hello.Length)];
            }            
        }
        private void btnDisable_Click(object sender, EventArgs e)
        {
            recEngine.RecognizeAsyncStop();
            btnDisable.Enabled = false;
        }
    }
}

语音识别-如果说hello或hi

列一个可能输入的列表,然后看看其中是否包含了所说的内容

string[] validInputs = new string[]{"Hello", "Hi"};
if(validInputs.Contains(said))