Search code examples
vbaexcelspeech

VBA - Save SAPI speech to a GIVEN file type?


My Task

It's possible to use speech in Office applications. My goal to save MS SAPI speech to a given file type. AFAIK my code example saves to a WAV file.

Problem

I don't know, if it's possible to define the wanted file type extension only or if it's necessary to do some further setting. I didn't find an appropriate solution using VBA.

Question Is there a code example how to precisely define a wanted file type, e.g. MP3, save a given text to this file type using the necessary settings (AudioStream)?

Code

In this code example I' m naming the output file directly as WAV with full uncertainty if this will be a WAV file.

I used late binding and included a comment to early binding, too.

Private Sub Speech2WAV()
' Purpose: save text Voice object to file
' Idea:    cf. .Net Article with some adaptions http://www.codeguru.com/vb/gen/vb_misc/samples/article.php/c13893/Text-to-Speech-Using-Windows-SAPI.htm
' Declare variables
  Dim s            As String
  s = "Could you give me a code example to save this text to a defined file type?"

'' ----------------------------------------------
'' Early Binding - reference do MS Speech Object Lib (SAPI.dll) needed
'' ----------------------------------------------
'  Dim oVoice       As New SpeechLib.SpVoice
'  Dim cpFileStream As New SpeechLib.SpFileStream
'' ----------------------------------------------

' ----------------------------------------------
' Late Binding
' ----------------------------------------------
  Dim oVoice       As Object
  Dim cpFileStream As Object

  Set oVoice = CreateObject("SAPI.SpVoice")
  Set cpFileStream = CreateObject("SAPI.SpFileStream")

' ----------------------------------------------

10   cpFileStream.Open ThisWorkbook.Path & "\test.wav", _
                   SpeechLib.SpeechStreamFileMode.SSFMCreateForWrite, False
20   Set oVoice.AudioOutputStream = cpFileStream
30   Set oVoice.Voice = oVoice.GetVoices.Item(0)
40   oVoice.Volume = 100
50   oVoice.Speak s, _
                  SpeechLib.SpeechVoiceSpeakFlags.SVSFDefault
55   oVoice.Rate = 1        ' speed
56   oVoice.Volume = 100    ' volume

60   Set oVoice = Nothing
70   cpFileStream.Close
80   Set cpFileStream = Nothing
Exit Sub
OOPS:       ' Error Handler
     MsgBox "ERL=" & Erl & "|ErrNo=" & Err.Number & "|" & Err.Description, vbExclamation, "Error in Speec2WAV"
End Sub

Note

Thx to @ashleedawg 's comment I can recommend the following links to the MS Speech API:

-White papers SAPI 5.3

-Microsoft Speech API 5.4


Solution

  • sapi only generates wav files.

    use ffmpeg to convert to other formats ... http://ffmpeg.org

    example of usage in vba ... use ffmpeg in vba to change video format