Play a wav file (sound file) through the API when a form opens, based on a text box value

Question: In Access 2003/XP/2000/97, I want to play a wav file when a form is loaded. But I only want the wav file to play if a text box contains a certain value. If the text box contains any other value when the form is loaded, I don't want to play the wav file.
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

Const SND_ASYNC = (1)
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 select Properties under the View menu.

When the Properties window appears, select the property called "On Load". 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 Form_Load event:
Private Sub Form_Load()
    'Play wav file only if category name is beverages
    If CategoryName = "Beverages" Then
        API_PlaySound "c:\windows\media\chimes.wav"
    End If
End Sub

The code above would play the wav file called chimes.wav that is located in the c:\windows\media directory. But the wav file is only played if the text box called CategoryName contains the value "Beverages".

No comments:

Post a Comment