7/02/2012

Play a wav file (sound file) through the API when a button is clicked, based on a text box value

Question: In Access 2003/XP/2000/97, I've set up a Form that displays all of the records from the WavFiles table. The WavFiles table has a column called WavFilename that contains the name of a wav file (without the .wav extension) on our file server.
I want to create a button on the Form that allows me to play the wav file that is displayed in the WavFilename field for the current record in the Form.
How can I do this?
Answer: It is possible to play wav files within your Access database. To do this, create a new Module and paste in the following VBA


code:
Const SND_ASYNC = (1)
Const SND_NODEFAULT = (2)
Declare Function sndplaysound Lib "winmm.dll" Alias "sndPlaySoundA" (ByVal lpszSoundName As String, ByVal uFlags As Long) As Long
Public Sub API_PlaySound(pWavFile As String)
    Dim LResult As Long
    'Make a Windows API call to play a wav file
    LResult = sndplaysound(pWavFile, SND_NODEFAULT + SND_ASYNC)
End Sub

Your module should look like this:


Next, open your form in Design View and create a button. In this example, we've created a button called cmdPlay.

Right click on the button and select Properties from the popup menu.


When the Properties window appears, select the property called "On Click". A button with 3 dots should appear to the right of the property. Click on this button.


When the Choose Builder window appears, highlight Code Builder and click on the OK button.


Now enter the following code in the button's On Click event:
API_PlaySound "c:\Windows\media\" & WavFileName & ".wav"
The code above would play the wav file that is displayed in the WavFileName field on the Form. The wav file is found in the c:\Windows\media directory and the code appends the .wav extension to the end of the file name since it is stored in the database without the file extension information.

Now we'll take a look at the Form as a user would see it.
So if the user clicks on the button, Access will play the following wav file:
c:\Windows\media\chimes.wav

No comments:

Post a Comment