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
Initialize the XAudio2 engine by following the steps described in How to: Initialize XAudio2.
Depending on the format of the audio data, you may need to use a larger data structure containing a WAVEFORMATEX structure in place of a WAVEFORMATEX. See the WAVEFORMATEX reference page for more information.
IXAudio2SourceVoice* pSourceVoice; if( FAILED(hr = pXAudio2->CreateSourceVoice( &pSourceVoice, (WAVEFORMATEX*)&wfx ) ) ) return hr;
if( FAILED(hr = pSourceVoice->SubmitSourceBuffer( &buffer ) ) ) return hr;
The audio sample data to which buffer points is still 'owned' by the app and must remain allocated and accessible until the sound stops playing.
Use the Start function to start the source voice. 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 selected at initialization. In a more complicated audio graph, the source voice would have to specify the voice to which its output should be sent.
if ( FAILED(hr = pSourceVoice->Start( 0 ) ) ) 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<IXAudio2SourceVoice> SourceVoice; HRESULT hr; if( FAILED(hr = pXAudio2->CreateSourceVoice( &SourceVoice, (WAVEFORMATEX*)&wfx ) ) ) throw Platform::Exception::CreateException(hr); if( FAILED(hr = SourceVoice->SubmitSourceBuffer( &buffer ) ) ) throw Platform::Exception::CreateException(hr); if ( FAILED(hr = SourceVoice->Start( 0 ) ) ) throw Platform::Exception::CreateException(hr);
Ensure that all smart pointers to XAUDIO2 objects are fully released before you release the IXAudio2 object.