Creating the DirectSound Object

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 lpDirectSound; 
HRESULT       hr;
hr = DirectSoundCreate(NULL, &lpDirectSound, NULL));
 

The function returns an error if there is no sound device or if the sound device is being used by 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:

  1. Initialize COM at the start of your application by calling CoInitialize and specifying NULL.
    if (FAILED(CoInitialize(NULL)))
        return FALSE;
     
  2. Create your DirectSound object by using CoCreateInstance and the IDirectSound::Initialize method, rather than the DirectSoundCreate function.
    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 driver GUID parameter that DirectSoundCreate typically 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, shut down COM by calling the CoUninitialize function, as follows:

CoUninitialize();