Playing sound in DirectX

You can play WAV and MIDI files in DirectX using DirectMusic. Using DirectMusic requires COM, so you must initialize COM before using DirectMusic and shut it down when your program finishes. (Please keep in mind that I am not a COM expert, so I can't guarantee that the COM part of these notes is 100% correct.)

You will need three kinds of objects to play sounds:

Each of these objects is made using the CoCreateInstance. You will only need one performance object and one loader object, but you might want more than one segment.

My Sound Class

I made a Sound class that you can use:
sound.h    sound.cpp

The Sound class has two static functions, initialize and shutdown. I made them static because I didn't want to associate them with a particular object, because there could be many Sound objects created and destroyed in a program, but I only want to call initialize and shutdown once. These two functions use pointers to the performance object and the loader. I made those pointers static variables so that any object in the class can use them, but there will only be one of each of them during the whole time that the program is running.

Member Functions

bool play(DWORD numRepeats);
bool stop();
bool isPlaying();
bool load(string fileName);
bool unload();

Although each of these returns a bool value, the current versions don't check any results and should probably just be void.

load takes a file name as an argument and then loads that file. Note: It always looks in the Sounds directory, under the current working directory. This function should not be called until Sound::initialize has been called.

play takes a parameter that tells how many times the sound should be repeated. If you only want the sound to be played once, pass zero for the value of the parameter. If you pass the value DMUS_SEG_REPEAT_INFINITE, the sound will play forever.

unload should be called before Sound::shutdown is called. Not all of the examples I looked at used code like this, but I found that when I didn't have it and ran in debug mode the program would hang.

Project Set-Up

You will need some include files and a library file: