Search code examples
c#speech-recognitionvoice-recognitionvoice

Voice Recognition - IF hello OR hi is said


Okay, so basically in C#, I want certain code to run when I say, for example, hello OR hi. I have gotten it so that when I say hello it runs the code but I can't figure out how to make it so that if I say hi instead it also runs the code. I don't want to make a whole if statement for both because I'm looking to make a whole lot in the future, (hello, hi, hey, how are you, etc). This is my code so far:

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

Solution

  • Just make a list of your potential inputs and then see if that contains what was said

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