Mercurial > servermonitor
diff ServerMonitor/Objects/ServerMonitor.cs @ 29:f6235dc0a8ec
Add ability to play a sound on check failure.
author | Brad Greco <brad@bgreco.net> |
---|---|
date | Fri, 14 Jun 2019 21:01:55 -0400 |
parents | 437442cd8090 |
children | 2ffb0bda7705 |
line wrap: on
line diff
--- a/ServerMonitor/Objects/ServerMonitor.cs Sun Jun 02 17:55:38 2019 -0400 +++ b/ServerMonitor/Objects/ServerMonitor.cs Fri Jun 14 21:01:55 2019 -0400 @@ -1,4 +1,5 @@ using Microsoft.Win32; +using NAudio.Wave; using Renci.SshNet; using Renci.SshNet.Common; using ServerMonitorApp.Properties; @@ -6,6 +7,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Media; using System.Net.NetworkInformation; using System.Threading; using System.Threading.Tasks; @@ -34,6 +36,8 @@ // then executes. private Dictionary<Task<CheckResult>, int> tasks; private ServerSummaryForm mainForm; + private WaveOut waveOut = new WaveOut(); + MediaFoundationReader mediaReader; /// <summary>Fires when the status of a check changes.</summary> public event EventHandler<CheckStatusChangedEventArgs> CheckStatusChanged; @@ -90,7 +94,7 @@ { bool triedBackup = false; - Read: + Read: TextReader reader = null; try { @@ -322,9 +326,43 @@ mainForm.AlertServerForm(result.Check); if (result.FailAction.In(FailAction.FlashTaskbar, FailAction.NotificationBalloon)) mainForm.ShowBalloon(result); + PlaySound(result.FailSound); } } + /// <summary>Plays a sound.</summary> + /// <param name="sound"> + /// If null, no sound is played. + /// If string.Empty, the Windows default error sound is played. + /// Otherwise, plays the sound at the given path. + /// </param> + private void PlaySound(string sound) + { + if (sound == string.Empty) + SystemSounds.Asterisk.Play(); + else if (sound != null) + { + try + { + mediaReader = new MediaFoundationReader(sound); + waveOut.Init(mediaReader); + waveOut.PlaybackStopped += WaveOut_PlaybackStopped; + waveOut.Play(); + } + catch + { + // Play the default sound if something went wrong. + SystemSounds.Asterisk.Play(); + } + } + } + + /// <summary>Disposes the media reader after sound playback.</summary> + private void WaveOut_PlaybackStopped(object sender, StoppedEventArgs e) + { + mediaReader.Dispose(); + } + /// <summary>Reads all check results from the log for a server.</summary> /// <param name="server">The server whose check results should be read.</param> /// <returns>A list of all check results found in the log file for the given server.</returns>