| using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Speech; using System.Speech.Recognition; using System.Globalization; using System.Windows.Forms; namespace StudyBeta { public class SRecognition { public SpeechRecognitionEngine recognizer = null;//語音辨識引擎 public DictationGrammar dictationGrammar = null; //自然文法 public System.Windows.Forms.Control cDisplay; //顯示控制項 public SRecognition(string[] fg) //建立關鍵詞語列表 { CultureInfo myCIintl = new CultureInfo("en-US"); foreach (RecognizerInfo config in SpeechRecognitionEngine. InstalledRecognizers())//擷取所有語音引擎 { if (config.Culture.Equals(myCIintl) && config.Id == "MS-1033-80-DESK" ) { recognizer = new SpeechRecognitionEngine(config); break; }//選擇美國英語的識別引擎 } if (recognizer != null) { InitializeSpeechRecognitionEngine(fg);//初始化語音辨識引擎 dictationGrammar = new DictationGrammar(); } else { MessageBox.Show("建立語音辨識失敗"); } } private void InitializeSpeechRecognitionEngine(string[] fg) { recognizer.SetInputToDefaultAudioDevice();//選擇預設的音訊輸入裝置 Grammar customGrammar = CreateCustomGrammar(fg); //根據關鍵字數組建立文法 recognizer.UnloadAllGrammars(); recognizer.LoadGrammar(customGrammar); //載入文法 recognizer.SpeechRecognized += new EventHandler <SpeechRecognizedEventArgs>(recognizer_SpeechRecognized); recognizer.SpeechHypothesized += new EventHandler <SpeechHypothesizedEventArgs>(recognizer_SpeechHypothesized); } public void BeginRec(Control tbResult)//關聯視窗控制項 { TurnSpeechRecognitionOn(); TurnDictationOn(); cDisplay = tbResult; } public void over()//停止語音辨識引擎 { TurnSpeechRecognitionOff(); } public virtual Grammar CreateCustomGrammar(string[] fg) //創造自訂文法 { GrammarBuilder grammarBuilder = new GrammarBuilder(); grammarBuilder.Append(new Choices(fg)); return new Grammar(grammarBuilder); } private void TurnSpeechRecognitionOn()//啟動語音辨識函數 { if (recognizer != null) { recognizer.RecognizeAsync(RecognizeMode.Multiple); //識別模式為連續識別 } else { MessageBox.Show("建立語音辨識失敗"); } } private void TurnSpeechRecognitionOff()//關閉語音辨識函數 { if (recognizer != null) { recognizer.RecognizeAsyncStop(); TurnDictationOff(); } else { MessageBox.Show("建立語音辨識失敗"); } } private void recognizer_SpeechRecognized(object sender, SpeechRecognized EventArgs e) { //識別出結果完成的動作,通常把識別結果傳給某一個控制項 string text = e.Result.Text; cDisplay.Text = text; } private void TurnDictationOn() { if (recognizer != null) { recognizer.LoadGrammar(dictationGrammar); //載入自然文法 } else { MessageBox.Show("建立語音辨識失敗"); } } private void TurnDictationOff() { if (dictationGrammar != null) { recognizer.UnloadGrammar(dictationGrammar); //卸載自然文法 } else { MessageBox.Show("建立語音辨識失敗"); } } } } |