Creating a DirectSound Object

The easiest way for your application to create a DirectSound object is to call the DirectSoundCreate function and specify a NULL GUID. The function will then attempt to create the object corresponding to the wave device of the default window. You must then call the IDirectSound::SetCooperativeLevel method; no sound buffers can be played until this call has been made. The following example demonstrates this process:

LPDIRECTSOUND lpDirectSound;

if(DS_OK == DirectSoundCreate(NULL, &lpDirectSound,

NULL)) {

// Creation succeeded.

lpDirectSound->lpVtbl->SetCooperativeLevel(lpDirectSound,

hwnd, DSSCL_NORMAL);

// .

// . Place code to access DirectSound object here.

// .

} else {

// Creation failed.

// .

// .

// .

}

Your application can use the DirectSoundEnumerate function to specify the particular sound device to create. To use this function, you must create a DSEnumCallback function and, in most cases, an instance data structure, as shown in the following example:

typedef struct {

// Storage for GUIDs.

// Storage for device description strings.

} APPINSTANCEDATA, *LPAPPINSTANCEDATA;

BOOL AppEnumCallbackFunction(

LPGUID lpGuid,

LPTSTR lpstrDescription,

LPTSTR lpstrModule,

LPVOID lpContext)

{

LPAPPINSTANCEDATA lpInstance = (LPAPPINSTANCEDATA)

lpContext;

// Copy GUID into lpInstance structure.

// Strcpy description string into lpInstance

// structure.

return TRUE; // Continue enumerating.

}

Then, your application could create the DirectSound object by using the following example:

AppInitDirectSound()

{

APPINSTANCEDATA AppInstanceData;

LPGUID lpGuid;

LPDIRECTSOUND lpDirectSound;

HRESULT hr;

DirectSoundEnumerate(AppEnumCallbackFunction,

&AppInstanceData);

lpGuid = AppLetUserSelectDevice(&AppInstanceData);

// The application should check the return value of

// DirectSoundCreate for errors.

hr = DirectSoundCreate(lpGuid, &lpDirectSound, NULL);

// .

// .

// .

}

The DirectSoundCreate function fails if there is no sound device or if the sound device, as specified by the lpGuid parameter, has been allocated through the 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 using the sound device.