The simplest way to create the DirectSound object is with the DirectSoundCreate function. The first parameter of this function specifies the GUID of the device to be associated with the object. You can obtain this GUID by Enumeration of Sound Devices, or you can simply pass NULL to create the object for the default device.
LPDIRECTSOUND lpds;
HRESULT hr = DirectSoundCreate(NULL, &lpds, NULL));
The function returns an error if there is no sound device or if the sound device is under the control of an application using the waveform-audio (non-DirectSound) functions. You should prepare your applications for this call to fail so that they can either continue without sound or prompt the user to close the application that is already using the sound device.
You can also create the DirectSound object by using the CoCreateInstance function, as follows:
if FAILED(CoInitialize(NULL))
return FALSE;
LPDIRECTSOUND lpds;
dsrval = CoCreateInstance(&CLSID_DirectSound,
NULL,
CLSCTX_INPROC_SERVER,
&IID_IDirectSound,
&lpds);
if SUCCEEDED(dsrval)
dsrval = IDirectSound_Initialize(lpds, NULL);
CLSID_DirectSound is the class identifier of the DirectSound driver object class and IID_IDirectSound is the DirectSound interface that you should use. The lpds parameter is the uninitialized object CoCreateInstance returns.
Before you use a DirectSound object created with the CoCreateInstance function, you must call the IDirectSound::Initialize method. This method takes the same driver GUID parameter that DirectSoundCreate uses (NULL in this case). After the DirectSound object is initialized, you can use and release the DirectSound object as if it had been created by using the DirectSoundCreate function.
Before you close the application, close the COM library by calling the CoUninitialize function, as follows:
CoUninitialize();