Search code examples
vbscripttext-to-speechsapi

How to save SAPI text to speech to an audio file in VBScript?


I have the following VBScript code for text to speech conversion:

Set objVoice = CreateObject("SAPI.SpVoice")
objVoice.Speak Inputbox("Enter Text")

I want to save the speech to an audio file. How can I do this?


Solution

  • You can save the SAPI output to a .WAV file as follows:

    1. Create and open a .WAV file as a stream using the SpFileStream.Open method.

    2. Assign this file stream to the SpVoice.AudioStream property.

    Here's an example:

    Const SAFT48kHz16BitStereo = 39
    Const SSFMCreateForWrite = 3 ' Creates file even if file exists and so destroys or overwrites the existing file
    
    Dim oFileStream, oVoice
    
    Set oFileStream = CreateObject("SAPI.SpFileStream")
    oFileStream.Format.Type = SAFT48kHz16BitStereo
    oFileStream.Open "C:\Work\Sample.wav", SSFMCreateForWrite
    
    Set oVoice = CreateObject("SAPI.SpVoice")
    Set oVoice.AudioOutputStream = oFileStream
    oVoice.Speak "Hello world"
    
    oFileStream.Close