How to: Initialize XAudio2

XAudio2 is initialized for audio playback by creating an instance of the XAudio2 engine, and creating a mastering voice.

To initialize XAudio2

  1. Make sure you have initialized COM. For a Windows Store app, this is done as part of initializing the Windows Runtime. Otherwise, use CoInitializeEx.

    HRESULT hr;
    hr = CoInitializeEx( nullptr, COINIT_MULTITHREADED );
    if (FAILED(hr))
        return hr;
    
  2. Use the XAudio2Create function to create an instance of the XAudio2 engine.

    IXAudio2* pXAudio2 = nullptr;
    if ( FAILED(hr = XAudio2Create( &pXAudio2, 0, XAUDIO2_DEFAULT_PROCESSOR ) ) )
        return hr;
    
  3. Use the CreateMasteringVoice method to create a mastering voice.

    The mastering voices encapsulates an audio device. It is the ultimate destination for all audio that passes through an audio graph.

    IXAudio2MasteringVoice* pMasterVoice = nullptr;
    if ( FAILED(hr = pXAudio2->CreateMasteringVoice( &pMasterVoice ) ) )
        return hr;
    

Notes for Windows Store apps

We recommend that you make use of a smart pointer to manage the lifetime of XAUDIO2 objects in an exception safe manner. For Windows Store apps, you can use the ComPtr smart pointer template from the Windows Runtime C++ Template Library (WRL).

Microsoft::WRL::ComPtr<IXAudio2> XAudio2;
HRESULT hr;
if ( FAILED(hr = XAudio2Create( &XAudio2, 0, XAUDIO2_DEFAULT_PROCESSOR ) ) )
    throw Platform::Exception::CreateException(hr);

IXAudio2MasteringVoice* pMasterVoice = nullptr;
if ( FAILED(hr = pXAudio2->CreateMasteringVoice( &pMasterVoice ) ) )
    return hr;

Note

Ensure that all XAUDIO2 child objects are fully released before you release the IXAudio2 object.

 

XAudio2 Getting Started

How to: Load Audio Data Files in XAudio2

How to: Play a Sound with XAudio2