Search code examples
vb6sapi

How to enable free diction speech recognition in VB6 using SAPI


Recently I have been attempting to create a chatbot for school, and one of the features I wanted was speech recognition. Unfortunately, due to the deprecated nature of VB6, there are very few tutorials on using SAPI for speech recognition with VB6, and none at all for enabling free diction (simply speaking without a grammar set and converting speech into text).


Solution

  • Automation Interfaces and Objects (SAPI 5.4) has the documentation.

    Trivial example:

    Option Explicit
    
    'See "Automation Interfaces and Objects (SAPI 5.4)" at MSDN.
    
    Private WithEvents RC As SpeechLib.SpInProcRecoContext
    Private RG As SpeechLib.ISpeechRecoGrammar
    
    Private Sub Form_Load()
        With New SpeechLib.SpInprocRecognizer
            Set RC = .CreateRecoContext()
            Set .AudioInput = .GetAudioInputs().Item(0)
        End With
        With RC
            .EventInterests = SRERecognition Or SREFalseRecognition
            Set RG = .CreateGrammar()
        End With
        RG.DictationSetState SGDSActive
    End Sub
    
    Private Sub Form_Resize()
        If WindowState <> vbMinimized Then
            Text1.Move 0, 0, ScaleWidth, ScaleHeight
        End If
    End Sub
    
    Private Sub Form_Unload(Cancel As Integer)
        RG.DictationSetState SGDSInactive
    End Sub
    
    Private Sub RC_FalseRecognition( _
        ByVal StreamNumber As Long, _
        ByVal StreamPosition As Variant, _
        ByVal Result As SpeechLib.ISpeechRecoResult)
    
        With Text1
            .SelStart = &H7FFF
            .SelText = "False Rec: "
            .SelText = Result.PhraseInfo.GetText()
            .SelText = vbNewLine
        End With
    End Sub
    
    Private Sub RC_Recognition( _
        ByVal StreamNumber As Long, _
        ByVal StreamPosition As Variant, _
        ByVal RecognitionType As SpeechLib.SpeechRecognitionType, _
        ByVal Result As SpeechLib.ISpeechRecoResult)
    
        With Text1
            .SelStart = &H7FFF
            .SelText = "Rec: "
            .SelText = Result.PhraseInfo.GetText()
            .SelText = vbNewLine
        End With
    End Sub