VB Application Sample: Command and Control Recognition (SAPI 5.3)
VB Application Sample: Command and Control Recognition
The following code sample represents a simple, but functional, recognition application. It uses a command and control grammar which limits the recognizable text to those listed in the configuration file. In this case, the file is named sol.xml and the file contents are listed in the second code box below. The text is restricted to the single command "new game."
The commented lines in the Visual Basic code refer to hypothetical labels in a form to possibly display information. If a speech attempt does not match the new game rule pattern, it could also display "(no recognition)". Of course you may modify this application as needed to fit your own requirements.
Before running the application, a speech reference must be included. Using the Project->References menu, find and select the Microsoft Speech Object Library.
Public WithEvents RC As SpSharedRecoContext Public myGrammar, b As ISpeechRecoGrammar Private Sub Form_Load() On Error GoTo EH Set RC = New SpSharedRecoContext Set myGrammar = RC.CreateGrammar myGrammar.CmdLoadFromFile "sol.xml", SLODynamic myGrammar.CmdSetRuleIdState 0, SGDSActive EH: If Err.Number Then ShowErrMsg End Sub Private Sub RC_FalseRecognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal Result As SpeechLib.ISpeechRecoResult) 'Label1.Caption = "(no recognition)" End Sub Private Sub RC_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechLib.SpeechRecognitionType, ByVal Result As SpeechLib.ISpeechRecoResult) 'Label1.Caption = Result.PhraseInfo.GetText End Sub Private Sub RC_StartStream(ByVal StreamNumber As Long, ByVal StreamPosition As Variant) 'Label2.Caption = Val(StreamNumber) End Sub Private Sub ShowErrMsg() ' Declare identifiers: Const NL = vbNewLine Dim T As String T = "Desc: " & Err.Description & NL T = T & "Err #: " & Err.Number MsgBox T, vbExclamation, "Run-Time Error" End End Sub
In addition to copying the code to the Visual Basic project, copy the following XML code into a new file named sol.xml.
<GRAMMAR LANGID="409"> <DEFINE> <ID NAME="RID_NewGame" VAL="101"/> </DEFINE> <RULE NAME="newgame" ID="RID_NewGame" TOPLEVEL="ACTIVE"> <P>new +game</P> </RULE> </GRAMMAR>
In cases when a second grammar file is needed, copy the following XML code into a new file named sol2.xml.
<GRAMMAR LANGID="409"> <DEFINE> <ID NAME="RID_FileGame" VAL="200"/> </DEFINE> <RULE NAME="filegame" ID="RID_FileGame" TOPLEVEL="ACTIVE"> <P>file +game</P> </RULE> </GRAMMAR>