using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Speech.Recognition; namespace WindowsFormsApp1 { public partial class Form1 : Form { private string Text; private SpeechRecognitionEngine recognizer; private DictationGrammar dictationGrammar; public Form1() { InitializeComponent(); string[] a = { }; SRecognition(a,1); } private void button1_Click(object sender, EventArgs e) { //RecognitionResult result = recognizer.Recognize(); // Console.WriteLine(result.Text); recognizer.RecognizeAsync(RecognizeMode.Multiple); } private void button2_Click(object sender, EventArgs e) { recognizer.RecognizeAsyncStop(); } public void SRecognition(string[] fg, int i) //创建关键词语列表 { CultureInfo myCIintl = new CultureInfo("zh-CN"); foreach (RecognizerInfo config in SpeechRecognitionEngine.InstalledRecognizers())//获取所有语音引擎 { Console.WriteLine(config.Culture.EnglishName); if (config.Culture.Equals(myCIintl)) { recognizer = new SpeechRecognitionEngine(config); break; }//选择识别引擎 } if (recognizer != null) { InitializeSpeechRecognitionEngine(fg);//初始化语音识别引擎 dictationGrammar = new DictationGrammar(); } else { MessageBox.Show("创建语音识别失败"); } } void InitializeSpeechRecognitionEngine(string[] s) { // Create and load a dictation grammar. //recognizer.LoadGrammar(new DictationGrammar()); // Configure input to the speech recognizer. recognizer.SetInputToDefaultAudioDevice(); // Modify the initial silence time-out value. recognizer.InitialSilenceTimeout = TimeSpan.FromSeconds(5); GrammarBuilder GB = new GrammarBuilder(); GB.Append("选择"); GB.Append(new Choices(new string[] { "红色", "绿色" })); Grammar G = new Grammar(GB); Console.WriteLine(G.RuleName); G.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(G_SpeechRecognized); recognizer.LoadGrammar(G); } void G_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { Text = e.Result.Text; switch (e.Result.Text) { case "选择红色": BackColor = Color.Red; button2.BackColor = BackColor; break; case "选择绿色": BackColor = Color.Green; button2.BackColor = BackColor; break; } } } }
C#调用window语音识别
最新推荐文章于 2024-06-20 16:26:35 发布