Creating a Basic Sound Buffer

To create a sound buffer, your application fills in a DSBUFFERDESC structure and then calls the IDirectSound::CreateSoundBuffer method. This creates a DirectSoundBuffer object and returns a pointer to an IDirectSoundBuffer interface. This interface can be used to write, manipulate, and play the buffer.

You should create buffers for the most important sounds first, and continue to create them in descending order of importance. DirectSound allocates hardware resources to the first buffer that can take advantage of them.

The following example illustrates how to create a basic secondary buffer:

BOOL AppCreateBasicBuffer(

LPDIRECTSOUND lpDirectSound,

LPDIRECTSOUNDBUFFER *lplpDsb)

{

PCMWAVEFORMAT pcmwf;

DSBUFFERDESC dsbdesc;

HRESULT hr;

// Set up wave format structure.

memset(&pcmwf, 0, sizeof(PCMWAVEFORMAT));

pcmwf.wf.wFormatTag = WAVE_FORMAT_PCM;

pcmwf.wf.nChannels = 2;

pcmwf.wf.nSamplesPerSec = 22050;

pcmwf.wf.nBlockAlign = 4;

pcmwf.wf.nAvgBytesPerSec =

pcmwf.wf.nSamplesPerSec * pcmwf.wf.nBlockAlign;

pcmwf.wBitsPerSample = 16;

// Set up DSBUFFERDESC structure.

memset(&dsbdesc, 0, sizeof(DSBUFFERDESC)); // Zero it out.

dsbdesc.dwSize = sizeof(DSBUFFERDESC);

dsbdesc.dwFlags = DSBCAPS_CTRLDEFAULT; // Need default controls

(pan, volume, frequency).

dsbdesc.dwBufferBytes = 3 * pcmwf.wf.nAvgBytesPerSec; // 3 second

buffer.

dsbdesc.lpwfxFormat = (LPWAVEFORMATEX)&pcmwf;

// Create buffer.

hr = lpDirectSound->lpVtbl->CreateSoundBuffer(lpDirectSound,

&dsbdesc, lplpDsb, NULL);

if(DS_OK == hr) {

// Succeeded! Valid interface is in *lplpDsb.

return TRUE;

} else {

// Failed!

*lplpDsb = NULL;

return FALSE;

}

}