This project has moved and is read-only. For the latest updates, please go here.

WasapiOut COMException if speaker removed

Oct 25, 2011 at 9:19 AM

I am setting up audio playback this way:

        private IWavePlayer GetWavePlayer(int deviceNumber = 0)
        {
            WasapiOut wavePlayer = new WasapiOut(AudioClientShareMode.Shared, false, 300);
            wavePlayer.PlaybackStopped += OnPlaybackStopped;
            wavePlayer.Init(_provider);
            wavePlayer.Play(); // <-- this line causes exception if speakers are disabled
 
            return wavePlayer;
        }

While playing audio using WasapiOut and disabling current speaker causes the following exception:

System.Runtime.InteropServices.COMException was unhandled
Message=Exception from HRESULT: 0x88890004
Source=NAudio  ErrorCode=-2004287484
StackTrace:
       at NAudio.CoreAudioApi.Interfaces.IAudioClient.GetCurrentPadding(Int32& currentPadding)
       at NAudio.Wave.WasapiOut.PlayThread() in I:\Repository\Sample\NAudio Source\NAudio\Wave\WaveOutputs\WasapiOut.cs:line 134
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

This lead me to

WasapiOut.cs line 134:

numFramesPadding = audioClient.CurrentPadding;

And:

        /// <summary>
        /// Gets the current padding (must initialize first)
        /// </summary>
        public int CurrentPadding
        {
            get
            {
                int currentPadding;
                Marshal.ThrowExceptionForHR(audioClientInterface.GetCurrentPadding(out currentPadding));
                return currentPadding;
            }
        }

I guess the "audioClientInterface" is NULL if no audio output device is available.

Is there a way to get around the unhandled COM exception as I am not able to catch it in my application?

Similar problem were with WaveIn: "no recording devices on Windows 7 / Vista?" (http://naudio.codeplex.com/discussions/274165) and this were fixed here http://naudio.codeplex.com/SourceControl/network/Forks/bobasaurus/recordingPullCableFix.

Probably I could think out a hack how to fix the symptom in the NAudio source but I would prefer not to make local changes that would be overwritten with new release of NAudio.

What would be the right way to handle audio endpoint addition and removal or change of default device in theory?
What about device event notifications? 

 

Thanks

Nov 1, 2011 at 5:22 PM

Yes, probably there should be a way that WasapiOut can report device removed with an event you can subscribe to and then simply stop playback if the device is removed. We could even make the PlaybackStopped event have some kind of way of reporting the reason for playback stopped.