Make your scripts sing

In an earlier post, I showed you how to make your scripts talk back. Well, you can also use the SAPI object to “speak” a wav file. Imagine having a script play a sound when it finishes a long query or process.  This is pretty easy to do. The limitation is that the object will only play wav files.

What you need to do is create a  SAPI.SpFileStream.1 object and then invoke it’s OPEN method, passing it the parameter of a filename.

Set objFile = CreateObject(“SAPI.SpFileStream.1”)
objFile.Open “C:\windows\media\tada.wav”

The voice object uses the SpeakStream method to “speak” the file:

objSPVoice.Speakstream objFile

It is good practice to close the file after you are done with it.

objFile.Close

That’s all there is to it.  I’ve put together a sample script that gets your media directory (typically %windir%\media) and lists all the files that end in .wav.  The default voice will speak each filename and then “speak” the file so you can hear it.

On Error Resume Next
Dim objShell,objFSO,objFiles
Dim objSPVoice,objFile
 
Set objSPVoice=CreateObject(“SAPI.SpVoice”)
Set objFile = CreateObject(“SAPI.SpFileStream.1”)
Set objShell=CreateObject(“wscript.shell”)

strWinDir= objShell.ExpandEnvironmentStrings(“%WinDir%”)

strMediaDir=strWinDir & “\Media”

Set objFSO=CreateObject(“Scripting.FileSystemObject”)

Set objFiles=objFSO.GetFolder(strMediaDir).Files

For Each file In objFiles
‘only get .wav files
    If Right(file.name,3)=”wav” Then
    WScript.Echo file
    DemoWav file
    End If
Next

Sub DemoWav(File)
On Error Resume Next
    Err.Clear
    objFile.Open file
    If Err.Number<>0 Then Exit Sub ‘bail if there is a problem
                                    ‘opening the file
    objSPVoice.Speak file.name
    objSPVoice.SpeakStream objFile
    objFile.Close
End Sub

The DemoWav subroutine attempts to opens each file.  I added some error handling as on my system some of the wav files caused an error when they were opened, yet they play just fine in Windows Media Player. I just skip those since this is a demo anyway. 

Now your scripts can talk back and sing to you.

(The Microsoft Scripting Guys have a nice article on this topic at http://www.microsoft.com/technet/scriptcenter/funzone/games/sapi.mspx)