使用VBS腳本語音朗讀文字

如下代碼可朗讀指定文本文件中的內容,中英文皆可。測試

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

使用方法:編碼

  1. 新建一個文本文件,如 「測試.txt」,在裏面輸入你想要朗讀的文字並保存,保存時記住編碼格式;
  2. 再新建一個文本文件,將如下代碼粘貼進去;
  3. 將filePath修改成要朗讀的文本文件的路徑,將fileCharset修改成要朗讀的文本文件的編碼格式;
  4. 修改無誤後將文件保存爲 "ANSI" 或 「UTF-16 LE」 編碼且文件名以 「.vbs」 結尾的文件;
  5. 雙擊剛纔保存的vbs文件開始朗讀。
相關文章
相關標籤/搜索