Yuriy
Yuriy

Reputation: 130

NAudio, windows service, multithreading

I have windows service who play *.wav files (multithreading) through NAudio.dll

    public static void PlayFileBackground(string fileName)
    {
        Task.Run(() => { PlayFile(fileName); });
    }

    private static void PlayFile(string fileName)
    {
        if (File.Exists(fileName) == true)
        {
            try
            {
                var manualResetEvent = new ManualResetEvent(false);
                using (var wfr = new WaveFileReader(fileName))
                using (WaveChannel32 wc = new WaveChannel32(wfr) { Volume = 1, PadWithZeroes = false })
                using (var audioOutput = new DirectSoundOut())
                {
#region play
                    audioOutput.Init(wc);                        
                    audioOutput.Play();
                    audioOutput.PlaybackStopped += (sender, e) => { manualResetEvent.Set(); }; 
                    manualResetEvent.WaitOne();
                    audioOutput.Stop();
#endregion
                }
            }
            catch (Exception exception)
            {                
                logger.Error("Error NAudio.\n{0}", exception.ToString()); //<-never don't catch
            }
        }
    }

if the region 'play' commented -> All works

if the region 'play' uncommented -> Sometimes my service stops without any errors.

I try attach with debugger and i see: An unhandled exception of type 'System.ExecutionEngineException' occurred in NAudio.dll

Also: A first chance exception of type 'System.AccessViolationException' occurred in NAudio.dll

Are there any ideas?

Upvotes: 1

Views: 745

Answers (1)

Yuriy
Yuriy

Reputation: 130

I found the recommendation to replace DirectSoundOut > WaveOutEvent. And now all works properly. Thanks stuartd.

Upvotes: 1

Related Questions