VB .NET • Stop and Start the Recognizer

Listing 3. This code provides the basic plumbing you need to start and stop the SpeechRecognizer. This code also includes the SpeechEventArgs class, which simplifies the data returned from the SpeechRecognizer, and returns the recognized phrase.

Imports System.Speech
Imports System.Speech.Recognition

Public Class Recognizer
	Protected WithEvents reco As SpeechRecognizer

	Public Event SpeechRecognized(ByVal sender As _
		Object, ByVal e As SpeechEventArgs)

	Public Sub New(ByVal options As List(Of String))
		reco = New SpeechRecognizer
		reco.Enabled = False
	End Sub

	Private Sub LoadGrammar(ByVal options As _
		List(Of String))
		Dim choices As New Choices
		For Each s As String In options

		Dim gb As New GrammarBuilder(choices)
		Dim g As New Grammar(gb)
	End Sub

	Public Sub StartListening()
		If Not reco Is Nothing Then reco.Enabled = True
	End Sub

	Public Sub StopListening()
		If Not reco Is Nothing Then reco.Enabled = False
	End Sub

	Private Sub reco_SpeechRecognized(ByVal sender _
		As Object, ByVal e As SpeechRecognizedEventArgs) _
		Handles reco.SpeechRecognized
		RaiseEvent SpeechRecognized(Me, New _
	End Sub
End Class

Public Class SpeechEventArgs
	Inherits EventArgs

	Private _result As String
	Public Property Result() As String
			Return _result
		End Get
		Set(ByVal value As String)
			_result = value
		End Set
	End Property

	Public Sub New(ByVal result As String)
		Me.Result = result
	End Sub
End Class