Saturday, January 12, 2013

Playing WAV files using VBA

Playing WAV sound files using with VBA. This method makes use of the windows winmm.dll file to play a specific wav file. An example that VBA is able to utilize windows libraries to improve productivity of Microsoft Office Tools.

'Declare this part at the top of the Module
Public Declare Function sndPlaySound Lib "winmm.dll" _
Alias "sndPlaySoundA" (ByVal lpszSoundName As String, _
ByVal uFlags As Long) As Long

'Method to play wav file
Sub PlayWavFile(WavFileName As String, Wait As Boolean)
'Check if there is a valid file
If Dir(WavFileName) <> "" Then
'Pause all running codes and play the sound
If Wait Then
sndPlaySound WavFileName, 0
'Play sound concurrently with the running code
Else
sndPlaySound WavFileName, 1
End If
'If the input was to stop the sound, this should not be able to overlap over any
'sound file as a sound file has to have a .wav extension in order to be played
ElseIf WavFileName = "Stop" Then
'Play an empty file
sndPlaySound " ", 1
End If
End Sub
Parameters:
WavFileName -- The location of the wav sound file that you want to play. You can utilize relative paths to find the sound file (ThisWorkbook.Path, ThisDocument.Path, etc.).
(Input "Stop" to stop the currently playing sound, or play another sound to cut of the currently playing sound)
Wait -- This will decide how the sound file be played. True means that all codes will be paused and the sound file will be played whereas False will play the sound as the code runs.

To use this method, simply call the PlayWavFile method

Some examples:
PlayWavFile "C:\MyWaveFileLocation.wav", True
PlayWavFile ThisWorkbook.Path & "\WavFileBesideExcelFile.wav", False
PlayWavFile "Stop" False

No comments: