If you want to play little sound files and you don't need maximum power than this snippet is right for you. I will show you a standard Win32 function that plays Wave audio files no matter whether the file is a a normal file or a resource file. I will also show you how to preload the file and play it afterwards. This function is not as powerful as DirectSound however it is easier to use and it is sometimes good enough.
The funtion we will be using is as follow:
- pszSound is the name of the file that should be played. It can be a "real" file or a resource file.
- hmod is the handle of the application. It should be set to NULL unless you play a resourcefile.
- fdwSound is a set of flags that tell the function how to load/play the file.
- SND_FILENAME: audio file is on the harddisk.
- SND_RESOURCE: audio file is a resource file.
- SND_LOOP: file will be played looped. Plays until you call PlaySound(..) with NULL as file.
- SND_ASYNC: function returns immediately and the app continues execution.
- SND_SYNC: app "pauses" until playback of the audio file is finished.
- SND_MEMORY: file is played from memory. pszSound must point to its memory image.
PlaySound returns true when the file has been played successfully and false if there was an error. Here are three little examples how to use it:
The first example simply plays a file from the HD. Nothing special.
In the second example we first load the complete file to memory and then we call PlaySound(..). The first parameter points here to the image of the sound file. Notice that this method is much faster than loading the file every time from disk. Load the file into memory when your app starts and destroy the memory block when the app quits. But don't load the file into memory every time you play the sound, that would be non-sense..
In the last example we play a soundfile from the app's resources. Remember that you have to set the second parameter - the application's handle - before playing resource files. I use the Mfc function AfxGetInstanceHandle() here. If you use the standard Win32 API, use GetModuleHandle(NULL).
That's all! If you don't want to use DirectSound, this method works very well! Questions? Comments? M@il Me. Happy Coding!