Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a wave file or sound file using VBA

Tags:

vba

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.

like image 984
user1222679 Avatar asked Feb 25 '12 12:02

user1222679


1 Answers

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

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:

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

like image 141
Jerry Beaucaire Avatar answered Nov 23 '22 14:11

Jerry Beaucaire