How to: Play a sound with XAudio2

This topic describes the minimum steps required to play previously-loaded audio data in XAudio2.

After you initialize XAudio2 (see How to: Initialize XAudio2) and load the audio data (see How to: How to: Load Audio Data Files in XAudio2), you can play a sound by creating a source voice, and passing audio data to it.

To play a sound

  1. First initialize XAudio2 for audio playback by following the steps described in How to: Initialize XAudio2.

  2. Then populate a WAVEFORMATEX structure and an XAUDIO2_BUFFER structure by following the steps described in How to: Load audio data files in XAudio2.

    Note

    Depending on the format of the audio data, you might need to use a larger data structure (one that contains a WAVEFORMATEX structure) in place of a WAVEFORMATEX. For more info, see the WAVEFORMATEX topic.

  3. Next, to create what's known as a source voice, call the IXAudio2::CreateSourceVoice method. That will give you a pointer to an IXAudio2SourceVoice interface. The format of the voice is specified by the values set in the WAVEFORMATEX structure.

    IXAudio2SourceVoice* m_pXAudio2SourceVoice{};
    ...
    winrt::check_hresult(m_xAudio2->CreateSourceVoice(&m_pXAudio2SourceVoice, (WAVEFORMATEX*)&wfx)));    
    
  4. Submit an XAUDIO2_BUFFER to the source voice by calling the IXAudio2SourceVoice::SubmitSourceBuffer method.

    winrt::check_hresult(m_pXAudio2SourceVoice->SubmitSourceBuffer(&xAudio2Buffer));
    

    Note

    The audio sample data pointed to by the pBuffer parameter of SubmitSourceBuffer is still owned by the app, and it must remain allocated and accessible until the sound stops playing.

  5. To start the source voice, call the IXAudio2SourceVoice::Start method. Since all XAudio2 voices send their output to the mastering voice by default, audio from the source voice automatically makes its way to the audio device that was created/selected at initialization. In a more complicated audio graph, the source voice would need to specify which voice its output should be sent to.

    winrt::check_hresult(m_pXAudio2SourceVoice->Start(0));
    

Smart pointers

For safety and convenience, you can use a smart pointer for the IXAudio2 interface. But the voice interfaces (such as IXAudio2MasteringVoice) don't have a Release method, so you'll see a build error if you try to use a smart pointer for those. In these code snippets we use a smart pointer where possible, and a raw pointer where necessary.