diff --git a/src/client/spark/Notifications/INotifier.cs b/src/client/spark/Notifications/INotifier.cs index 94e9add92..2d27730c6 100644 --- a/src/client/spark/Notifications/INotifier.cs +++ b/src/client/spark/Notifications/INotifier.cs @@ -2,6 +2,7 @@ using bts.api; using bts.shell; using bts.spark; +using bts.utils; using mbts.config; using mbts.persist; using mbts.spark; @@ -114,6 +115,7 @@ namespace mbts.ui { void dispose_core() { Disposable.dispose(ref _settings_sub); Disposable.dispose(ref _toast_controller); + Disposable.dispose(ref _sound_player); if (_dispatcher != null && !_dispatcher.HasShutdownStarted) { _dispatcher.BeginInvokeShutdown(DispatcherPriority.Background); } @@ -158,15 +160,25 @@ namespace mbts.ui { } } - class SoundNotificationPlayer { - readonly IReadOnlyDictionary _players; - - public static SoundNotificationPlayer create() => new SoundNotificationPlayer(_all_players()); + class SoundNotificationPlayer : IDisposable { + IReadOnlyDictionary _players; SoundNotificationPlayer(IReadOnlyDictionary players) => _players = players; + public static SoundNotificationPlayer create() => + new SoundNotificationPlayer(_all_players()); + + public void Dispose() { + if (_players != null) { + _players.Values.DisposeAll(); + _players = null; + } + } + public void play_sounds(IEnumerable sounds) { + if (_players == null) + return; foreach (var s in sounds) { switch (s.sound_type_case) { case SoundNotification.SoundTypeOneofCase.System: _players.GetValueOrDefault(s.system_sound.Value)?.play(); break; @@ -177,7 +189,8 @@ namespace mbts.ui { } static IReadOnlyDictionary _all_players() => - EnumHelper.get_values().ToReadOnlyDictionary(s => s, NAudioPlayer.create); + EnumHelper.get_values() + .ToReadOnlyDictionaryWhere(NAudioPlayer.try_create); } // This class adopts to role of view-controller in the mvc paradigm, rather than view-model in mvvm. diff --git a/src/client/spark/Notifications/NAudioPlayer.cs b/src/client/spark/Notifications/NAudioPlayer.cs index 938af0b95..c62fc91b1 100644 --- a/src/client/spark/Notifications/NAudioPlayer.cs +++ b/src/client/spark/Notifications/NAudioPlayer.cs @@ -1,4 +1,5 @@ -using bts.shell; +using bts; +using bts.shell; using mbts.ui.utility; using NAudio.Wave; using System; @@ -6,29 +7,71 @@ using System.IO; using System.Threading.Tasks; namespace mbts.ui { - class NAudioPlayer { + class NAudioPlayer : IDisposable { // number of milliseconds to delay playing sound, // during which time all subsequent requests to play the same sound will be ignored. const int _delay_ms = 75; readonly int _start_position; + IDisposable _stream_in; WaveOutEvent _wave_out = new WaveOutEvent(); WaveFileReader _wave_reader; bool _is_playing, _is_play_requested; - public NAudioPlayer(Stream uwave_stream, int start_position = 0) { - var ms = new MemoryStream(); - uwave_stream.CopyTo(ms); - ms.Position = 0; - _wave_reader = new WaveFileReader(ms); + /// should not be disposed by the caller, + /// as NAudioPlayer handles that in its own Dispose method; + /// this constructor is private is to prevent such misuse. + NAudioPlayer(Stream stream_in, int start_position = 0) { + _stream_in = stream_in; + _wave_reader = new WaveFileReader(stream_in); _wave_reader.Position = _start_position = (start_position < _wave_reader.Length ? start_position : 0); _wave_out.Init(_wave_reader); _wave_out.PlaybackStopped += _on_playback_stopped; } - public static NAudioPlayer create(SoundNotification.SystemSound system_sound) { - var stream = _get_stream(system_sound); - var sb = EnumHelper.get_attribute(system_sound); - return sb != null ? new NAudioPlayer(stream, sb.start_position) : new NAudioPlayer(stream); + /// is a proxy/buffer for the _wave_out.PlaybackStopped event. + /// It serves a couple purposes: + /// 1) The main callback () + /// is guarenteed to be executed first (though it would be anyways, since that + /// callback is hooked up in the constructor, the proxy event makes it obvious). + /// 2) is only raised after playback is truly complete, + /// meaning there are no pending requests to repeat the sound. + event Action _playback_stopped; + + public static bool try_create(SoundNotification.SystemSound system_sound, out NAudioPlayer result) { + if (_try_get_stream(system_sound, out var stream)) { + var sb = EnumHelper.get_attribute(system_sound); + result = sb != null ? new NAudioPlayer(stream, sb.start_position) : new NAudioPlayer(stream); + return true; + } + result = null; + return false; + } + + public static void play(SoundNotification.SystemSound system_sound) { + if (try_create(system_sound, out var player)) { + try { + var temp = player; + temp._playback_stopped += temp.Dispose; + player.play(); + player = null; + } catch (Exception ex) { + Log.Ui.warn($"Encountered exception playing the system sound '{system_sound}': {ex}."); + } finally { + player?.Dispose(); + } + } else { + Log.Ui.warn($"Unable to play the system sound '{system_sound}': unexpected sound type (did not find an audio stream that corresponds to this enum value)."); + } + } + + public void Dispose() { + if (_wave_out != null) { + _wave_out.PlaybackStopped -= _on_playback_stopped; + _wave_out.Dispose(); + _wave_out = null; + } + Disposable.dispose(ref _wave_reader); + Disposable.dispose(ref _stream_in); } public void play() { @@ -46,6 +89,8 @@ namespace mbts.ui { if (_is_play_requested) { _is_play_requested = false; _play_core(); + } else { + _playback_stopped?.Invoke(); } } @@ -56,18 +101,26 @@ namespace mbts.ui { _is_playing = false; } - static Stream _get_stream(SoundNotification.SystemSound system_sound) { + static bool _try_get_stream(SoundNotification.SystemSound system_sound, out Stream stream) { + UnmanagedMemoryStream um_stream; switch (system_sound) { - case SoundNotification.SystemSound.GameCorrect: return bts.Properties.Resources.game_sound_correct; - case SoundNotification.SystemSound.GameIncorrect: return bts.Properties.Resources.game_sound_wrong; - case SoundNotification.SystemSound.GameOverArcade: return bts.Properties.Resources.game_over_arcade; - case SoundNotification.SystemSound.Whistle: return bts.Properties.Resources.whistle; - case SoundNotification.SystemSound.BellCounter: return bts.Properties.Resources.bell_counter; - case SoundNotification.SystemSound.Powerup: return bts.Properties.Resources.powerup; - case SoundNotification.SystemSound.CashRegister: return bts.Properties.Resources.cash_register_purchase; - case SoundNotification.SystemSound.Reload: return bts.Properties.Resources.reload_1911; - default: throw new NotImplementedException($"Unknown {nameof(SoundNotification.SystemSound)}: {system_sound}."); + case SoundNotification.SystemSound.GameCorrect: um_stream = bts.Properties.Resources.game_sound_correct; break; + case SoundNotification.SystemSound.GameIncorrect: um_stream = bts.Properties.Resources.game_sound_wrong; break; + case SoundNotification.SystemSound.GameOverArcade: um_stream = bts.Properties.Resources.game_over_arcade; break; + case SoundNotification.SystemSound.Whistle: um_stream = bts.Properties.Resources.whistle; break; + case SoundNotification.SystemSound.BellCounter: um_stream = bts.Properties.Resources.bell_counter; break; + case SoundNotification.SystemSound.Powerup: um_stream = bts.Properties.Resources.powerup; break; + case SoundNotification.SystemSound.CashRegister: um_stream = bts.Properties.Resources.cash_register_purchase; break; + case SoundNotification.SystemSound.Reload: um_stream = bts.Properties.Resources.reload_1911; break; + default: + stream = null; + return false; } + stream = new MemoryStream(); + um_stream.CopyTo(stream); + um_stream.Dispose(); + stream.Position = 0; + return true; } } -} \ No newline at end of file +} diff --git a/src/client/spark/view/Controls/DIYGrid/Settings/Animation/SoundAnimationView.xaml.cs b/src/client/spark/view/Controls/DIYGrid/Settings/Animation/SoundAnimationView.xaml.cs index ff41bae64..bc22ed26e 100644 --- a/src/client/spark/view/Controls/DIYGrid/Settings/Animation/SoundAnimationView.xaml.cs +++ b/src/client/spark/view/Controls/DIYGrid/Settings/Animation/SoundAnimationView.xaml.cs @@ -38,11 +38,7 @@ namespace mbts.ui.controls { } public static ICommand PreviewSoundCommand => - new DelegateCommand(s => { - try { - NAudioPlayer.create(s).play(); - } catch (NAudio.MmException) { } - }); + new DelegateCommand(NAudioPlayer.play); #region SoundTypes public static readonly DependencyProperty SoundTypesProperty = diff --git a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs index e0980227f..45e61f264 100644 --- a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs @@ -390,6 +390,15 @@ namespace System.Collections.Generic { public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector, Func element_selector, IEqualityComparer comparer) => new ReadOnlyDictionary(enumerable.ToDictionary(key_selector, element_selector, comparer)); + public static ReadOnlyDictionary ToReadOnlyDictionaryWhere(this IEnumerable keys, TryGetValue value_selector) { + var mdict = new Dictionary(); + foreach (var k in keys) { + if (value_selector(k, out var val)) + mdict[k] = val; + } + return new ReadOnlyDictionary(mdict); + } + public static ILookup ToFlatLookup(this IEnumerable source, Func key_selector, Func> selector) => source.SelectMany(v => { var k = key_selector(v);