Sound
Up
On this page you will learn how to:
bulletbreak long lines of code
bulletadd sounds to a VB program

Adding sound to VB programs is not difficult, but a clumsy line must be included in the General Declarations area first:

Private Declare Function sndPlaySound _
Lib "winmm.dll" Alias "sndPlaySoundA" _
(ByVal lpszSoundName As String, ByVal _
uFlags As Long) As Long

This is (and has to be) a single line of code, but it has been wrapped by putting a space and an underscore character where you want to wrap the line. (Don't put these characters inside a text string i.e. between double quotes.) Using this trick, very long lines of code can be made easier to read without horizontal scrolling.

Once you have copied the above line of code into the General Declarations area of your project, then the code for playing sound is easy. Assuming you have placed a sound file called 'mysound.wav' into the same folder that contains your project, you can play it anywhere in any procedure with the following line:

rc = sndPlaySound(App.Path & "\mysound.wav", 1)

 Since your sound file will have a different name, you should replace the word mysound.wav with the name of your file, without removing the double quotes or the backslash.

Why are all the above lines rather hard to understand? It's because we are using VB to control the computer directly with this code, whereas usually we use VB to control Windows, and let Windows control the computer. So now you know.

If you would like to try a sound effect right now then

bulletmake a new Standard EXE project and save it immediately (File/Save Project) into a folder called Sound
bulletadd a command button called cmd1
bulletcopy and paste the function declaration from the top of this page into the General Declarations area at the top of the code window
bulletdownload this sound by right-clicking and saving into into the same folder that contains your project
bulletcopy and paste this code for the command button:
Private Sub cmd1_Click()
rc = sndPlaySound(App.Path & "\applause.wav", 1)
End Sub

Final notes:

bulletthe computers in the CIV computer labs do not have speakers so if you are working at school you will need to borrow headphones from Mr. W in order to hear the sounds.
bulletthe above techniques work for 'wave' sounds (sound files that have a .wav extension) but do not necessarily work for other sound formats such as MIDI (.mid) or .aif files. If you wish to play MIDI sounds then see the next project, called Video but also covering some audio formats too.
 

Previous Up Next