naudio / NAudio

Audio and MIDI library for .NET
MIT License
5.58k stars 1.1k forks source link

InvalidOperationException while disposing WaveOutEvent #1184

Open pedroivobraga opened 2 months ago

pedroivobraga commented 2 months ago

I have a MixerProvider that mixes the loopback and the microphone; however, I'm experiencing an intermittent issue when disposing of the silent playback.

Into my dispose method, I'm getting the bellow exception:

System.InvalidOperationException: Handle is not initialized. at System.Runtime.InteropServices.GCHandle.Free() at NAudio.Wave.WaveOutBuffer.Dispose(Boolean disposing) at NAudio.Wave.WaveOutEvent.DisposeBuffers() at NAudio.Wave.WaveOutEvent.Dispose() at EswLinphoneClient.Media.AudioMixerProvider.Dispose(Boolean disposing)

Dispose method:

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                _mixerProvider.RemoveAllMixerInputs();

                foreach (var source in _mixers.ToArray())
                {
                    source.Buffer.ClearBuffer();
                    //source.Input.Dispose(); Removed because we were experiencing the bellow error:
                    /*
                     Exception Info: System.NullReferenceException
                        at System.Runtime.InteropServices.Marshal.ReleaseComObject(System.Object)
                        at NAudio.CoreAudioApi.AudioClient.Dispose()
                        at NAudio.CoreAudioApi.WasapiCapture.Dispose()
                     */

                }

                _mixers.Clear();
                _silentPlayer?.Dispose();
            }
            disposedValue = true;
        }
    }

Do you have any idea that what could be causing such issue?