日期:2014-05-18 浏览次数:20991 次
public class SpRecognition { private static SpRecognition _Instance = null; private SpeechLib.ISpeechRecoGrammar isrg; private SpeechLib.SpSharedRecoContextClass ssrContex = null; public delegate void StringEvent(string str); public StringEvent SetMessage; private SpRecognition() { ssrContex = new SpSharedRecoContextClass(); isrg = ssrContex.CreateGrammar(1); SpeechLib._ISpeechRecoContextEvents_RecognitionEventHandler recHandle = new _ISpeechRecoContextEvents_RecognitionEventHandler(ContexRecognition); ssrContex.Recognition += recHandle; } public void BeginRec() { isrg.DictationSetState(SpeechRuleState.SGDSActive); } public static SpRecognition instance() { if (_Instance == null) _Instance = new SpRecognition(); return _Instance; } public void CloseRec() { isrg.DictationSetState(SpeechRuleState.SGDSInactive); } private void ContexRecognition(int iIndex, object obj, SpeechLib.SpeechRecognitionType type, SpeechLib.ISpeechRecoResult result) { if (SetMessage != null) { SetMessage(result.PhraseInfo.GetText(0, -1, true)); } } }
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();