跳至内容

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

另请参阅

[编辑 | 编辑源代码]
[编辑 | 编辑源代码]
华夏公益教科书