应用程序可以利用SpSharedRecoContext接口创建不同的与语音识别引擎的连接。每一个连接都可以使用各自的事件并且使用不同的语音识别语法(grammars)。每一个基于SAPI语音识别的应用程序必须具有至少一个SpSharedRecoContext接口。
第一种方法: 自己定义Grammar
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Diagnostics;
using SpeechLib;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
private SpeechLib.ISpeechGrammarRule menuRule = null;
private SpeechLib.SpSharedRecoContext objRecoContext;
private ISpeechRecoGrammar grammar;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// 得到一个RecoContext实例.
objRecoContext = new SpeechLib.SpSharedRecoContext();
// 指派一个事件给Hypothesis Event(中间层暂定的识别,即,初级的,临时的识别).
objRecoContext.Hypothesis += new _ISpeechRecoContextEvents_HypothesisEventHandler(Hypo_Event);
// 指派一个事件给语音识别.
objRecoContext.Recognition += new _ISpeechRecoContextEvents_RecognitionEventHandler(Reco_Event);
//创建grammer实例.
grammar = objRecoContext.CreateGrammar(0);
label1.Text = "Speak Out one of the following./r/n1. 人民 2. 马克思 3. 孙中山 4. 恩格斯/r/n5. 杨茂巍 6. 王芳 7. 世界 8. 成都";
//激活菜单命令.
menuRule = grammar.Rules.Add("MenuCommands", SpeechRuleAttributes.SRATopLevel | SpeechRuleAttributes.SRADynamic, 1);
object PropValue = "";
menuRule.InitialState.AddWordTransition(null, "人民", " ", SpeechGrammarWordType.SGLexical, "人民", 1, ref PropValue, 1.0F);
menuRule.InitialState.AddWordTransition(null, "马克思", " ", SpeechGrammarWordType.SGLexical, "马克思", 2, ref PropValue, 1.0F);
menuRule.InitialState.AddWordTransition(null, "孙中山", " ", SpeechGrammarWordType.SGLexical, "孙中山", 3, ref PropValue, 1.0F);
menuRule.InitialState.AddWordTransition(null, "恩格斯", " ", SpeechGrammarWordType.SGLexical, "恩格斯", 4, ref PropValue, 1.0F);
menuRule.InitialState.AddWordTransition(null, "杨茂巍", " ", SpeechGrammarWordType.SGLexical, "杨茂巍", 5, ref PropValue, 1.0F);
menuRule.InitialState.AddWordTransition(null, "王芳 ", " ", SpeechGrammarWordType.SGLexical, "王芳 ", 6, ref PropValue, 1.0F);
menuRule.InitialState.AddWordTransition(null, "世界", " ", SpeechGrammarWordType.SGLexical, "世界", 7, ref PropValue, 1.0F);
menuRule.InitialState.AddWordTransition(null, "成都", " ", SpeechGrammarWordType.SGLexical, "成都", 8, ref PropValue, 1.0F);
grammar.Rules.Commit();
grammar.CmdSetRuleState("MenuCommands", SpeechRuleState.SGDSActive);
}
private void Reco_Event(int StreamNumber, object StreamPosition, SpeechRecognitionType RecognitionType, ISpeechRecoResult Result)
{
textBox1.Text = Result.PhraseInfo.GetText(0, -1, true);
}
private void Hypo_Event(int StreamNumber, object StreamPosition, ISpeechRecoResult Result)
{
textBox2.Text = Result.PhraseInfo.GetText(0, -1, true);
}
}
}
口令结束
放大
Home
End
上一页
下一页
向上
向下
左窗口
右窗口
关闭
撤消
刷新