一個基於c#3.0的開發基於2000/XP/2003下語音識別的通用類
廢話少說看程式碼
using System;using System.Collections.Generic;using System.Linq;using System.Text;using SpeechLib;using System.Windows.Forms;using System.Collections;
namespace [email protected]{ public class speechxp {
private SpeechLib.SpSharedRecoContext objRecoContext; private SpeechLib.ISpeechRecoGrammar grammar; private SpeechLib.ISpeechGrammarRule rule = null; private SpeechLib.ISpeechGrammarRuleState state; private SpeechLib.ISpeechPhraseElement PhraseElem; public System.Windows.Forms.Control cDisplay;
public speechxp(string FileName, Control cDisplay) {
}
private void initSAPI() { try { objRecoContext = new SpeechLib.SpSharedRecoContext(); objRecoContext.AudioLevel += new _ISpeechRecoContextEvents_AudioLevelEventHandler(RecoContext_VUMeter);//設定聲音事件的響應函式 objRecoContext.Recognition += new _ISpeechRecoContextEvents_RecognitionEventHandler(RecoContext_Recognition);//設定成功識別事件的響應函式 objRecoContext.EventInterests = SpeechLib.SpeechRecoEvents.SRERecognition | SpeechLib.SpeechRecoEvents.SREAudioLevel;//設定響應事件
//create grammar interface with ID = 0 grammar = objRecoContext.CreateGrammar(1);//語法的例項 } catch (Exception ex) { MessageBox.Show("Exception /n" + ex.ToString(), "Error - initSAPI"); } } private void SAPIGrammarFromFile(string FileName) { try { grammar.CmdLoadFromFile(FileName, SpeechLib.SpeechLoadOption.SLODynamic); grammar.CmdSetRuleIdState(0, SpeechRuleState.SGDSActive);
} catch { MessageBox.Show("載入語法檔案失敗 " + FileName + "/n", "Error - SAPIGrammarFromFile"); } } public void RecoContext_Recognition(int StreamNumber, object StreamPosition, SpeechRecognitionType RecognitionType, ISpeechRecoResult e) {
int i; ArrayList reco = new ArrayList(); string phrase = e.PhraseInfo.GetText(0, -1, true);
cDisplay.Text = e.PhraseInfo.GetText(0, -1, true);
foreach (SpeechLib.ISpeechPhraseElement PhraseElem in e.PhraseInfo.Elements) { /// listBox1.Items.Add(PhraseElem.Pronunciation);新增語音指令
}
i = e.PhraseInfo.Elements.Count; for (int h = 0; h < i; h++) { }
}
public void RecoContext_VUMeter(int StreamNumber, object StreamPosition, int e) { int hg = e; } }}
類的呼叫
hhh = new SpRecognition(file); 定義好的語法XML檔案 hhh.BeginRec(textBox10); 關聯到顯示識別結果的控制元件