以下代碼可朗讀指定文本文件中的內容,中英文皆可。
Dim fso,openFile,voice,str,filePath,fileCharset
'filePath為要朗讀的文本文件路徑,根據實際替換
filePath = "D:\測試.txt"
'fileCharset為要朗讀的文本文件編碼,根據實際替換
fileCharset = "utf-8"
Set fso = CreateObject("Scripting.FileSystemObject")
Set voice = CreateObject("SAPI.SpVoice")
Set openFile = fso.OpenTextFile(filePath, 1, True)
'將從文本中讀取的文字存入Str
str = ReadFile(filePath, fileCharset)
'朗讀文字
voice.Speak str
'作用:從文件中讀取文本
'參數:
'filePath:文件路徑
'charSet:文件編碼格式
Function ReadFile(filePath, charSet)
Dim Str
Set stm = CreateObject("Adodb.Stream")
stm.Type = 2
stm.mode = 3
stm.charset = charSet
stm.Open
stm.loadfromfile filePath
Str = stm.readtext
stm.Close
Set stm = Nothing
ReadFile = Str
End Function
使用方法:
- 新建一個文本文件,如 “測試.txt”,在里面輸入你想要朗讀的文字並保存,保存時記住編碼格式;
- 再新建一個文本文件,將以下代碼粘貼進去;
- 將filePath修改為要朗讀的文本文件的路徑,將fileCharset修改為要朗讀的文本文件的編碼格式;
- 修改無誤后將文件保存為 "ANSI" 或 “UTF-16 LE” 編碼且文件名以 “.vbs” 結尾的文件;
- 雙擊剛才保存的vbs文件開始朗讀。