How to: Use Source Voice Callbacks

When you create a source voice, you can pass a structure to it that defines callbacks for certain audio events. You can use these callbacks to perform actions or to signal other code.

  1. Create a class that inherits from the IXAudio2VoiceCallback interface. All member functions of IXAudio2VoiceCallback are purely virtual, and must be defined. The only function of interest in this example is OnStreamEnd. Therefore, the rest of the functions are stubs. The OnStreamEnd function triggers an event that indicates the sound is done playing.

    class VoiceCallback : public IXAudio2VoiceCallback
    {
    public:
        HANDLE hBufferEndEvent;
        VoiceCallback(): hBufferEndEvent( CreateEvent( NULL, FALSE, FALSE, NULL ) ){}
        ~VoiceCallback(){ CloseHandle( hBufferEndEvent ); }
    
        //Called when the voice has just finished playing a contiguous audio stream.
        void OnStreamEnd() { SetEvent( hBufferEndEvent ); }
    
        //Unused methods are stubs
        void OnVoiceProcessingPassEnd() { }
        void OnVoiceProcessingPassStart(UINT32 SamplesRequired) {    }
        void OnBufferEnd(void * pBufferContext)    { }
        void OnBufferStart(void * pBufferContext) {    }
        void OnLoopEnd(void * pBufferContext) {    }
        void OnVoiceError(void * pBufferContext, HRESULT Error) { }
    };
    
  2. Create a source voice with IXAudio2::CreateSourceVoice using an instance of the callback class created previously as the pCallback parameter.

    VoiceCallback voiceCallback;
    if( FAILED(hr = pXaudio2->CreateSourceVoice( &pSourceVoice, (WAVEFORMATEX*)&wfx,
                                 0, XAUDIO2_DEFAULT_FREQ_RATIO, &voiceCallback, NULL, NULL ) ) ) return;
    
  3. After starting the voice, use the WaitForSingleObjectEx method to wait for the event to be triggered.

    WaitForSingleObjectEx( voiceCallback.hBufferEndEvent, INFINITE, TRUE );
    

Callbacks

XAudio2 Callbacks

XAudio2 Programming Guide

How to: Build a Basic Audio Processing Graph

How to: Stream a Sound from Disk