The simplest way to create the device object is by using 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 enumerating devices, or you can pass one of the following GUIDs to specify a default device:
GUID definition | Description |
---|---|
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 an object for the default device and obtains the IDirectSound8 interface:
LPDIRECTSOUND8 lpds; HRESULT hr = DirectSoundCreate8(NULL, &lpds, NULL));
If your application will capture sounds as well as play them, you can conveniently create both rendering and capture devices, as well as playback and capture buffers, by using the DirectSoundFullDuplexCreate8 function.
You can also create the device object by using standard COM functions, as follows.
HRESULT hr = CoInitializeEx(NULL, 0); if (FAILED(hr)) { ErrorHandler(hr); // Add error-handling here. }
LPDIRECTSOUND8 lpds; hr = CoCreateInstance(&CLSID_DirectSound8, NULL, CLSCTX_INPROC_SERVER, IID_IDirectSound8, (LPVOID*) &lpds); if (FAILED(hr)) { ErrorHandler(hr); // Add error-handling here. }
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.
hr = lpds->Initialize(NULL); if (FAILED(hr)) { ErrorHandler(hr); // Add error-handling here. }
CoUninitialize();