如何使用 VBA 播放波形文件或声音文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9443801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 12:40:01  来源:igfitidea点击:

How to play a wave file or sound file using VBA

vba

提问by user1222679

I have a wave file that I want to play using VBA. Please help me to create a button that when clicked on plays the wave file.

我有一个想要使用 VBA 播放的波形文件。请帮我创建一个按钮,点击时播放波形文件。

回答by Jerry Beaucaire

Here's a way for WAV files. Put **this code**in a regular code module:

这是WAV文件的一种方式。将**这段代码**放在一个普通的代码模块中:

Option Explicit
Public Declare Function sndPlaySound32 _
    Lib "winmm.dll" _
    Alias "sndPlaySoundA" ( _
        ByVal lpszSoundName As String, _
        ByVal uFlags As Long) As Long

Sub PlayTheSound(ByVal WhatSound As String)
    If Dir(WhatSound, vbNormal) = "" Then
        ' WhatSound is not a file. Get the file named by
        ' WhatSound from the Windows\Media directory.
        WhatSound = Environ("SystemRoot") & "\Media\" & WhatSound
        If InStr(1, WhatSound, ".") = 0 Then
            ' if WhatSound does not have a .wav extension,
            ' add one.
            WhatSound = WhatSound & ".wav"
        End If
        If Dir(WhatSound, vbNormal) = vbNullString Then
            Beep            ' Can't find the file. Do a simple Beep.
            Exit Sub
        End If
    Else
        ' WhatSound is a file. Use it.
    End If

    sndPlaySound32 WhatSound, 0&    ' Finally, play the sound.
End Sub

Now, you can play any wav file through any other macro by calling that routine above and feeding in any filename found in the /Media folder:

现在,您可以通过调用上面的例程并输入 /Media 文件夹中找到的任何文件名,通过任何其他宏播放任何 wav 文件:

Sub PlayIt()
    Select Case Range("A1").Value
        Case "good"
            PlayTheSound "chimes.wav"
        Case "bad"
            PlayTheSound "chord.wav"
        Case "great"
            PlayTheSound "tada.wav"
    End Select
End Sub

Play around with that.

玩那个。

Here's a sample file where I use that to dramatically reveal random names and tasks for the day, it is attached to a button like you plan to do:

这是一个示例文件,我用它来显着显示当天的随机名称和任务,它附加到您计划执行的按钮上:

Random Task List with AUDIO Reveal

带有 AUDIO Reveal 的随机任务列表