Microsoft Docs

DirectSound

DirectSound provides a low‑level interface for playing and recording waveform audio. It enables developers to control sound mixing, 3‑D positioning, hardware acceleration, and more on Windows platforms.

Getting Started

To begin using DirectSound, include the appropriate headers and link against dsound.lib. A simple initialization sequence is shown below.

#include <windows.h>
#include <dsound.h>

#pragma comment(lib, "dsound.lib")
#pragma comment(lib, "dxguid.lib")

int main()
{
    HRESULT hr;
    LPDIRECTSOUND8 pDS = nullptr;

    // Initialize COM
    CoInitializeEx(nullptr, COINIT_MULTITHREADED);

    // Create DirectSound object
    hr = DirectSoundCreate8(nullptr, &pDS, nullptr);
    if (FAILED(hr)) return -1;

    // Set cooperative level
    hr = pDS->SetCooperativeLevel(GetConsoleWindow(),
        DSSCL_PRIORITY);
    // ...
    return 0;
}

Creating a DirectSound Object

The DirectSoundCreate8 function creates a DirectSound8 object that supports the latest features.

FunctionDescription
DirectSoundCreate8Creates a DirectSound8 object.
IDirectSound8::SetCooperativeLevelSpecifies how the app will share the sound hardware with other apps.
IDirectSound8::CreateSoundBufferCreates a secondary buffer for playback.
IDirectSoundBuffer8::PlayStarts playback of the buffer.

Playing Sounds

Below is a minimal example that loads a WAV file into a secondary buffer and plays it.

bool LoadWaveFile(const wchar_t* filename, LPDIRECTSOUNDBUFFER8* ppBuffer, LPDIRECTSOUND8 pDS)
{
    // Simplified wave loader (error handling omitted)
    HMMIO hFile = mmioOpen(const_cast(filename), nullptr, MMIO_ALLOCBUF | MMIO_READ);
    if (!hFile) return false;

    MMCKINFO parent;
    mmioDescend(hFile, &parent, nullptr, 0);

    MMCKINFO chunk;
    mmioDescend(hFile, &chunk, &parent, 0);
    DWORD dataSize = chunk.cksize;

    // Prepare buffer description
    DSBUFFERDESC desc = {0};
    desc.dwSize = sizeof(desc);
    desc.dwFlags = DSBCAPS_GLOBALFOCUS;
    desc.dwBufferBytes = dataSize;
    desc.lpwfxFormat = (WAVEFORMATEX*)malloc(chunk.cksize);
    mmioRead(hFile, (HPSTR)desc.lpwfxFormat, dataSize);

    // Create buffer
    HRESULT hr = pDS->CreateSoundBuffer(&desc, reinterpret_cast(ppBuffer), nullptr);
    mmioClose(hFile, 0);
    return SUCCEEDED(hr);
}

// Usage
LPDIRECTSOUNDBUFFER8 pBuffer = nullptr;
if (LoadWaveFile(L"test.wav", &pBuffer, pDS))
{
    pBuffer->Play(0, 0, 0);
}

Advanced Topics

Reference

For detailed API documentation, see the official MSDN reference: