Visual Basic for Applications/Make a WAV File from a VBA String

Summary

edit
  • This code module will make a voiced wav file starting from a VBA string. A reference should be set in the VBA editor to Microsoft Speech Object Library.
  • The parameters are just the intended string to be spoken and a full path to the intended file name. The process MAKES a file but does not speak it as audio. Once made, the wav file can be spoken with procedures in an adjacent page, or tested in Windows Explorer by simply opening it.
  • No error code has been added. For example, if an attempt is made to use a folder with restrictions, an error will be raised. Users might consider adding some error trapping.
  • The intended target wave file need not exist. If it does not exist it will be made. If it exists however, it will be overwritten.
  • Notice that the user should enter his own profile in the file path. This author could not make the environmental paths work which would otherwise have made the code independent of the profile details.

VBA Code

edit

Copy the entire code listing into an Excel standard module. Modify the paths to your own, and run the top procedure to make a reusable wav file of the string. Remember to set a reference to Microsoft Speech Object Library.

Option Explicit
Sub TestStringToWavFile()
    'run this to make a wav file from a text input

    Dim sP As String, sFN As String, sStr As String, sFP As String

    'set parameter values - insert your own profile name first
    'paths
    sP = "C:\Users\Your Profile Name\Documents\" 'for example
    sFN = "Mytest.wav" 'overwrites if file name same
    sFP = sP & sFN
    
    'string to use for the recording
    sStr = "This is a short test string to be spoken in a user's wave file."
    
    'make voice wav file from string
    StringToWavFile sStr, sFP

End Sub

Function StringToWavFile(sIn As String, sPath As String) As Boolean
    'makes a spoken wav file from parameter text string
    'sPath parameter needs full path and file name to new wav file
    'If wave file does not initially exist it will be made
    'If wave file does initially exist it will be overwritten
    'Needs reference set to Microsoft Speech Object Library
    
    Dim fs As New SpFileStream
    Dim Voice As New SpVoice

    'set the audio format
    fs.Format.Type = SAFT22kHz16BitMono

    'create wav file for writing without events
    fs.Open sPath, SSFMCreateForWrite, False
 
    'Set wav file stream as output for Voice object
    Set Voice.AudioOutputStream = fs

    'send output to default wav file "SimpTTS.wav" and wait till done
    Voice.Speak sIn, SVSFDefault

    'Close file
    fs.Close

    'wait
    Voice.WaitUntilDone (6000)

    'release object variables
    Set fs = Nothing
    Set Voice.AudioOutputStream = Nothing

    'transfers
    StringToWavFile = True

End Function

See Also

edit
edit