'备注(运行以下代码时在win7中可以直接运行,前提是开启语音服务的情况下。如果是xp就要先按装Speech SDK 5.1才行)
'第一步:工程 - 引用 - Microsoft Speech Object Library
'第二步:将以下代码放到专门的XML编辑器中,然后另存为,扩展名为XML,(请不要直接用记事本编辑,因为那样死活都无效)
'************代码************
<GRAMMAR LANGID="804">
<RULE ID="1" Name="number" TOPLEVEL="ACTIVE">
<L PROPNAME="number">
<P VAL="1">张三</P>
<P VAL="2">李四</P>
<P VAL="3">中国</P>
<p VAL="4">美国</p>
</L>
</RULE>
</GRAMMAR>
'************代码************
'************窗体代码************
Dim WithEvents RecoContext As SpSharedRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim Voice As SpVoice
Private Sub Form_Load()
If (RecoContext Is Nothing) Then
Set RecoContext = New SpSharedRecoContext
Set Grammar = RecoContext.CreateGrammar(0)
Grammar.CmdLoadFromFile App.Path & "\语音数据.xml", SLODynamic '加载刚刚编写的xml文件
Grammar.CmdSetRuleIdState 0, SGDSActive
End If
End Sub
Private Sub RecoContext_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechRecognitionType, ByVal Result As ISpeechRecoResult)
Text1.Text = Result.PhraseInfo.GetText(0, -1, True) '识别结果
End Sub
'************窗体代码************
'==================================以上是针对准确识别的代码==================================
'==================================以下是针对模糊识别的代码==================================
Option Explicit
Dim WithEvents RecoContext As SpSharedRecoContext
Dim Grammar As ISpeechRecoGrammar
Dim m_bRecoRunning As Boolean
Dim m_cChars As Integer
Private Sub Form_Load()
SetState False
End Sub
Private Sub Command1_Click() '开始聆听
Debug.Assert Not m_bRecoRunning
If (RecoContext Is Nothing) Then
Set RecoContext = New SpSharedRecoContext
Set Grammar = RecoContext.CreateGrammar(1)
Grammar.DictationLoad
End If
Grammar.DictationSetState SGDSActive
SetState True
End Sub
Private Sub Command2_Click() '结束聆听
Debug.Assert m_bRecoRunning
Grammar.DictationSetState SGDSInactive
SetState False
End Sub
Private Sub RecoContext_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Variant, ByVal RecognitionType As SpeechRecognitionType, ByVal Result As ISpeechRecoResult)
Text1.Text = Result.PhraseInfo.GetText '识别结果
End Sub
Private Sub SetState(ByVal bNewState As Boolean)
m_bRecoRunning = bNewState
Command1.Enabled = Not m_bRecoRunning
Command2.Enabled = m_bRecoRunning
End Sub