跳至內容

Visual Basic for Applications/從 VBA 字串建立 WAV 檔案

來自華夏公益教科書,開放的書籍,開放的世界
  • 此程式碼模組將從 VBA 字串開始建立一個有聲的 wav 檔案。在 VBA 編輯器中,應將引用設定為 Microsoft Speech Object Library
  • 引數 只是要說的目標字串和目標檔名完整路徑。該過程 建立 檔案,但不會將其作為音訊播放。建立後,可以透過相鄰頁面中的過程來播放 wav 檔案,或者透過在 Windows 資源管理器中簡單地開啟檔案來進行測試。
  • 未新增任何錯誤程式碼。例如,如果嘗試使用受限制的資料夾,則會引發錯誤。使用者可以考慮新增一些錯誤捕獲。
  • 目標波形檔案不需要存在。如果它不存在,它將被建立。如果它存在,它將被覆蓋。
  • 請注意,使用者應在檔案路徑中輸入自己的配置檔案。該作者無法使環境路徑正常工作,否則它將使程式碼獨立於配置檔案詳細資訊。

VBA 程式碼

[編輯 | 編輯原始碼]

將整個程式碼列表複製到 Excel 標準模組中。修改路徑以適合您自己的路徑,並執行頂部過程以建立可重用的字串 wav 檔案。請記住將引用設定為 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

另請參閱

[編輯 | 編輯原始碼]
[編輯 | 編輯原始碼]
華夏公益教科書