Your
gram
declaration runs BEFORE the Form.Load event is fired, so on the first run of your app, the grammar.xml file doesn't exist and is empty.
Your code should be creating the Grammar object after it has written the file:
Public Class Form1
Dim engine As New SpeechRecognitionEngine
Dim gram As Grammar
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim choices = New Recognition.Choices()
choices.Add("Red")
choices.Add("Blue")
choices.Add("Green")
choices.Add("Yellow")
Dim gb = New GrammarBuilder()
gb.Append(choices)
Dim doc = New Speech.Recognition.SrgsGrammar.SrgsDocument(gb)
IO.Directory.CreateDirectory("C:\Test")
IO.Directory.CreateDirectory("C:\Test\Speech")
Dim xWriter = System.Xml.XmlWriter.Create("C:\Test\Speech\mygrammar.xml")
doc.WriteSrgs(xWriter)
xWriter.Close()
Dim compiledFile = New FileStream("C:\Test\Speech\mycompiledgrammar.cfg", FileMode.OpenOrCreate)
Speech.Recognition.SrgsGrammar.SrgsGrammarCompiler.Compile("C:\Test\Speech\mygrammar.xml", compiledFile)
compiledFile.Close()
gram = New Grammar("C:\Test\Speech\mygrammar.xml") End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If gram IsNot Nothing Then
engine.LoadGrammar(gram)
engine.SetInputToWaveFile("D:\record.wav")
Else
' The grammar wasn't loaded...
' Do something about the condition or notify the user.
End If
End Sub
End Class