Playing WAVE Files Through The Windows API

I have seen many programs written with VB that want to have a 'beep' or 'ding' and they actually add a control and bust up the size of the program by an insane amount. Fortunately for clever people like me or you, the API has a nice little function that will do the work of playing a wave file. And with little enhancements to the function, you could even use it in a simple game!

The API call you need to use to access this magical function is as follows:

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

The function has two parameters:

The second parameter of this function is very useful to play your wave file in different ways. Maybe you want it to loop, maybe you want to play it once - this is how to do it. Most API calls have handy-dandy constants to make life easy, and the ones for this are:

Const SND_ASYNC = &H1
Const SND_LOOP = &H8
Const SND_NODEFAULT = &H2
Const SND_SYNC = &H0
Const SND_NOSTOP = &H10
Const SND_MEMORY = &H4

If we wish to use more than one of these constants in conjunction, we link them with an "or" statement so that both constants will have an effect. For example, it is best to use SND_ASYNC along with SND_LOOP to ensure that the program can continue functioning while the looped wave file is playing. If we used SND_SYNC with SND_LOOP, we would never get control back to our program! Example:

sndPlaySound App.path & "\ding.wav", SND_ASYNC or SND_LOOP

The constants do the following:

So to play the sound 'monkey.wav' that is stored in the '\sounds' folder of the application path by looping it, I would do:

sndPlaySound App.Path & "\sounds\monkey.wav", SND_LOOP

To use more than one constant, then link them with Or to make sure they will have an equal effect.

While this method is simple, in many cases it will suffice. For advanced handling of sound, use DirectSound. This method however, will work on every language that can handle the API (the way to call the API will obviously be different). The major example here is freeBASIC; instead of using FMOD to play a wav file, you can use this method.

aetherFox
avinashvora [at] gmail [dot] com.
http://avinash.qbxl.net