user1580348
user1580348

Reputation: 6051

Output content of text file to computer voice via batch file

I have this batch file:

@echo off
echo StrText="Application created Successfully" > spk.vbs
echo set ObjVoice=CreateObject("SAPI.SpVoice") >> spk.vbs
echo ObjVoice.Speak StrText >> spk.vbs
start spk.vbs

This batch file creates spk.vbs in the same directory and outputs the text "Application created Successfully" with the computer voice.

Now I want the batch file to speak out the content of a text file given to it on the command line instead (%1). And the spk.vbs file should be created in the default Windows temporary directory instead. How can I do this?

***Edit 06.11.2012 20:24

Meanwhile I've discarded the idea of using a batch file script to generate a vbs script file and want to use the vbs script directly. Although I am an absolute beginner with VBS I created this one:

Set objFSO = CreateObject("Scripting.FileSystemObject")
strAFile = Wscript.Arguments(0)
Set objFile = objFSO.GetFile(strAFile)
If objFile.Size > 0 Then
  Set objReadFile = objFSO.OpenTextFile(Wscript.Arguments(0), 1)
  strContents = objReadFile.ReadAll 
  objReadFile.Close
  set ObjVoice=CreateObject("SAPI.SpVoice") 
  ObjVoice.Speak strContents 
Else
  Wscript.Echo "The file is empty."
End If

It works, but probaly I've made a lot of mistakes. Can someone tell me how the vbs script can be optimized? Thank you!

***Edit 06.11.2012 22:19

After this worked a few times, now it does not work anymore: Now the computer speaker outputs only "Y" and the first character of the text file! Has this something to do with an error in my script?

***Edit 10.11.2012 19:32 Found the bug: The above script work only with ANSI-coded text-files. It does not work with UNICODE text-files! Why? How can I make it work with UNICODE text-files too?

Upvotes: 0

Views: 5039

Answers (1)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Use the 4th parameter of the .OpenTextFile (or the 2nd parameter of the .OpenAsTextStream) method to specify whether to open the file as ASCII or Unicode (16).

I don't find any serious mistakes in your code snippet, but perhaps you want to consider:

  1. using "Option Explicit" (explicitly)
  2. checking whether the user passed at least one argument to the script
  3. avoiding to refer to the same 'object' via different names/variables (strAFile, WScript.Arguments(0))
  4. using .OpenAsTextStream as you have a File object already
  5. avoiding 'magic numbers' (e.g. 1) by defining the appropriate constants (e.g. ForReading)
  6. avoiding unnecessary variables (code you don't write can't be wrong)

E.g:

Set objReadFile = objFSO.OpenTextFile(WScript.Arguments(0), 1)
strContents = objReadFile.ReadAll 
objReadFile.Close

==>

Const cnUnicode = -1
...
strContents = objFile.OpenAsTextStream(ForReading, cnUnicode).ReadAll()

Upvotes: 1

Related Questions