Creating a Basic Sound Buffer

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

Your application should create buffers for the most important sounds first, and then create buffers for other sounds 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 sound 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);

// Need default controls (pan, volume, frequency).

dsbdesc.dwFlags = DSBCAPS_CTRLDEFAULT;

// 3-second buffer.

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

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;

}

}