Microsoft DirectX 8.1 (C++)

Creating the DirectSound Object

The simplest way to create the DirectSound object is with the DirectSoundCreate8 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 pass one of the following GUIDs to specify a default device:

DSDEVID_DefaultPlayback

The default system audio device. You can also specify this device by passing a NULL pointer in the device GUID parameter. The default device is the one enumerated as "Primary DirectSound Driver".

DSDEVID_DefaultVoicePlayback

The default voice communications device. Typically this is a secondary device such as a USB headset with microphone.

If no device driver is present, the call to DirectSoundCreate8 fails.

The function returns an error if there is no sound device or, under VXD drivers, if the sound device is under the control of an application using the standard Win32 waveform-audio 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.

The following code creates a DirectSound object for the default device and obtains the IDirectSound8 interface:

LPDIRECTSOUND8 lpds; 
HRESULT hr = DirectSoundCreate8(NULL, &lpds, NULL));
 

Note   DirectSoundCreate8 does not cause CoInitialize to be called. If your application uses effect DMOs, it must call CoInitialize regardless of how the DirectSound object is created.

If your application will capture sounds as well as play them, you can conveniently create both the DirectSound and the DirectSoundCapture object, as well as playback and capture buffers, by using the DirectSoundFullDuplexCreate8 function.

You can also create the DirectSound object by using standard COM functions, as follows:

  1. Initialize COM at the start of your application by calling CoInitializeEx:
    if FAILED(CoInitializeEx(NULL, 0))
      return FALSE;
     
  2. Create the DirectSound object by using CoCreateInstance and the IDirectSound8::Initialize method, rather than the DirectSoundCreate8 function:
    LPDIRECTSOUND8 lpds; 
    HRESULT hr = CoCreateInstance(&CLSID_DirectSound8,
              NULL, 
              CLSCTX_INPROC_SERVER,
              &IID_IDirectSound8,
              &lpds);

    CLSID_DirectSound8 is the class identifier of the DirectSound driver object class and IID_IDirectSound8 is the interface identifier. The lpds parameter receives the interface pointer.

  3. Call the IDirectSound8::Initialize method to associate the object with a device. This method takes the same device GUID parameter that DirectSoundCreate8 uses.
    if SUCCEEDED(hr)
      hr = lpds->Initialize(NULL);
     
  4. Before you close the application, close the COM library by calling the CoUninitialize function, as follows:
    CoUninitialize();