From 2241c57203d36c6e55a26869b64c94a11ec00861 Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 10:20:59 +0100 Subject: [PATCH 1/3] feat: add ad and moderator placeholder content Add AdSpot and ModeratorSegment models with Title and Duration and a read-only in-memory seed list for each in PlaceholderContent. Ads and moderator talk are placeholders without audio, so no database table is needed. Lengths vary (ads 30 s to 2 min, moderator 30 s to 3 min) so the schedule generator can size these segments to end songs exactly before the news. Tests check the lists are non-empty with titles and positive durations. Refs #7 Co-Authored-By: Claude Opus 5.5 --- src/Radiosender/Models/AdSpot.cs | 4 +++ src/Radiosender/Models/ModeratorSegment.cs | 4 +++ .../Services/PlaceholderContent.cs | 27 ++++++++++++++++++ .../PlaceholderContentTests.cs | 28 +++++++++++++++++++ 4 files changed, 63 insertions(+) create mode 100644 src/Radiosender/Models/AdSpot.cs create mode 100644 src/Radiosender/Models/ModeratorSegment.cs create mode 100644 src/Radiosender/Services/PlaceholderContent.cs create mode 100644 tests/Radiosender.Tests/PlaceholderContentTests.cs diff --git a/src/Radiosender/Models/AdSpot.cs b/src/Radiosender/Models/AdSpot.cs new file mode 100644 index 0000000..4efb655 --- /dev/null +++ b/src/Radiosender/Models/AdSpot.cs @@ -0,0 +1,4 @@ +namespace Radiosender.Models; + +// Placeholder without audio: the schedule only needs a title and a length. +public record AdSpot(string Title, TimeSpan Duration); diff --git a/src/Radiosender/Models/ModeratorSegment.cs b/src/Radiosender/Models/ModeratorSegment.cs new file mode 100644 index 0000000..9784107 --- /dev/null +++ b/src/Radiosender/Models/ModeratorSegment.cs @@ -0,0 +1,4 @@ +namespace Radiosender.Models; + +// Placeholder without audio: the schedule only needs a title and a length. +public record ModeratorSegment(string Title, TimeSpan Duration); diff --git a/src/Radiosender/Services/PlaceholderContent.cs b/src/Radiosender/Services/PlaceholderContent.cs new file mode 100644 index 0000000..45235b9 --- /dev/null +++ b/src/Radiosender/Services/PlaceholderContent.cs @@ -0,0 +1,27 @@ +using Radiosender.Models; + +namespace Radiosender.Services; + +// In-memory seed data; varied lengths let the schedule generator fill gaps before the news. +public static class PlaceholderContent +{ + public static IReadOnlyList AdSpots { get; } = + [ + new("Bakery Sonnenschein", TimeSpan.FromSeconds(30)), + new("Autohaus Berger", TimeSpan.FromSeconds(45)), + new("Stadtwerke Energy Tips", TimeSpan.FromSeconds(60)), + new("Furniture Outlet Sale", TimeSpan.FromSeconds(75)), + new("Regional Bank Savings", TimeSpan.FromSeconds(90)), + new("Summer Festival Preview", TimeSpan.FromMinutes(2)), + ]; + + public static IReadOnlyList ModeratorSegments { get; } = + [ + new("Station ID", TimeSpan.FromSeconds(30)), + new("Weather Update", TimeSpan.FromSeconds(60)), + new("Traffic Report", TimeSpan.FromSeconds(90)), + new("Song Introduction", TimeSpan.FromMinutes(2)), + new("Local Events", TimeSpan.FromSeconds(150)), + new("Listener Greetings", TimeSpan.FromMinutes(3)), + ]; +} diff --git a/tests/Radiosender.Tests/PlaceholderContentTests.cs b/tests/Radiosender.Tests/PlaceholderContentTests.cs new file mode 100644 index 0000000..33b4984 --- /dev/null +++ b/tests/Radiosender.Tests/PlaceholderContentTests.cs @@ -0,0 +1,28 @@ +using Radiosender.Services; + +namespace Radiosender.Tests; + +public class PlaceholderContentTests +{ + [Fact] + public void AdSpots_AreNonEmptyWithTitlesAndPositiveDurations() + { + Assert.NotEmpty(PlaceholderContent.AdSpots); + Assert.All(PlaceholderContent.AdSpots, ad => + { + Assert.False(string.IsNullOrWhiteSpace(ad.Title)); + Assert.True(ad.Duration > TimeSpan.Zero); + }); + } + + [Fact] + public void ModeratorSegments_AreNonEmptyWithTitlesAndPositiveDurations() + { + Assert.NotEmpty(PlaceholderContent.ModeratorSegments); + Assert.All(PlaceholderContent.ModeratorSegments, segment => + { + Assert.False(string.IsNullOrWhiteSpace(segment.Title)); + Assert.True(segment.Duration > TimeSpan.Zero); + }); + } +} From faa1dc19cc5bd2bbaa9dfd06e973570efc2868fa Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 10:24:12 +0100 Subject: [PATCH 2/3] feat: add music library page with search, edit and delete Add a Library page reachable from the navigation. It lists all songs from the SQLite database, filters them by title or artist, edits title, artist, license and attribution in a dialog, and deletes a song after a confirmation prompt. File path, duration and source stay read-only. LibraryController wraps SongRepository so the view only forwards user actions. Changes are written to the database immediately, and the list reloads every time the page is shown. Refs #3 Co-Authored-By: Claude Opus 5.5 --- .../Controllers/LibraryController.cs | 42 +++++++ src/Radiosender/Views/MainWindow.xaml | 3 + src/Radiosender/Views/Pages/LibraryPage.xaml | 67 +++++++++++ .../Views/Pages/LibraryPage.xaml.cs | 63 +++++++++++ src/Radiosender/Views/SongEditWindow.xaml | 41 +++++++ src/Radiosender/Views/SongEditWindow.xaml.cs | 34 ++++++ .../LibraryControllerTests.cs | 107 ++++++++++++++++++ 7 files changed, 357 insertions(+) create mode 100644 src/Radiosender/Controllers/LibraryController.cs create mode 100644 src/Radiosender/Views/Pages/LibraryPage.xaml create mode 100644 src/Radiosender/Views/Pages/LibraryPage.xaml.cs create mode 100644 src/Radiosender/Views/SongEditWindow.xaml create mode 100644 src/Radiosender/Views/SongEditWindow.xaml.cs create mode 100644 tests/Radiosender.Tests/LibraryControllerTests.cs diff --git a/src/Radiosender/Controllers/LibraryController.cs b/src/Radiosender/Controllers/LibraryController.cs new file mode 100644 index 0000000..832c617 --- /dev/null +++ b/src/Radiosender/Controllers/LibraryController.cs @@ -0,0 +1,42 @@ +using Radiosender.Models; +using Radiosender.Services; + +namespace Radiosender.Controllers; + +public class LibraryController(SongRepository repository) +{ + /// Returns all songs whose title or artist contains (case-insensitive). + public IReadOnlyList Search(string? query) + { + var songs = repository.GetAll(); + if (string.IsNullOrWhiteSpace(query)) + return songs; + + query = query.Trim(); + return songs + .Where(s => s.Title.Contains(query, StringComparison.OrdinalIgnoreCase) + || s.Artist.Contains(query, StringComparison.OrdinalIgnoreCase)) + .ToList(); + } + + /// Writes the editable metadata; file path, duration and source keep their stored values. + /// false if the song no longer exists. + public bool Update(long id, string title, string artist, string? license, string? attribution) + { + ArgumentException.ThrowIfNullOrWhiteSpace(title); + ArgumentException.ThrowIfNullOrWhiteSpace(artist); + + var song = repository.GetById(id); + if (song is null) + return false; + + song.Title = title.Trim(); + song.Artist = artist.Trim(); + song.License = string.IsNullOrWhiteSpace(license) ? null : license.Trim(); + song.Attribution = string.IsNullOrWhiteSpace(attribution) ? null : attribution.Trim(); + return repository.Update(song); + } + + /// false if the song no longer exists. + public bool Delete(long id) => repository.Delete(id); +} diff --git a/src/Radiosender/Views/MainWindow.xaml b/src/Radiosender/Views/MainWindow.xaml index 01281d6..6c43b01 100644 --- a/src/Radiosender/Views/MainWindow.xaml +++ b/src/Radiosender/Views/MainWindow.xaml @@ -22,6 +22,9 @@ + diff --git a/src/Radiosender/Views/Pages/LibraryPage.xaml b/src/Radiosender/Views/Pages/LibraryPage.xaml new file mode 100644 index 0000000..dcf4e56 --- /dev/null +++ b/src/Radiosender/Views/Pages/LibraryPage.xaml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Radiosender/Views/Pages/LibraryPage.xaml.cs b/src/Radiosender/Views/Pages/LibraryPage.xaml.cs new file mode 100644 index 0000000..43a7857 --- /dev/null +++ b/src/Radiosender/Views/Pages/LibraryPage.xaml.cs @@ -0,0 +1,63 @@ +using System.Windows; +using System.Windows.Controls; +using Radiosender.Controllers; +using Radiosender.Models; +using Wpf.Ui.Controls; +using MessageBox = Wpf.Ui.Controls.MessageBox; + +namespace Radiosender.Views.Pages; + +public partial class LibraryPage : Page +{ + private readonly LibraryController _controller = new(App.Songs); + + public LibraryPage() => InitializeComponent(); + + private Song? Selected => SongList.SelectedItem as Song; + + // Loaded fires on every navigation to the page, so the list is reloaded from the database each time. + private void OnLoaded(object sender, RoutedEventArgs e) => Refresh(); + + private void OnSearchChanged(object sender, TextChangedEventArgs e) => Refresh(); + + private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) => + EditButton.IsEnabled = DeleteButton.IsEnabled = Selected is not null; + + private void Refresh() + { + var songs = _controller.Search(SearchBox.Text); + SongList.ItemsSource = songs; + EmptyText.Visibility = songs.Count == 0 ? Visibility.Visible : Visibility.Collapsed; + } + + private void OnEdit(object sender, RoutedEventArgs e) + { + if (Selected is not { } song) + return; + + var dialog = new SongEditWindow(song) { Owner = Window.GetWindow(this) }; + if (dialog.ShowDialog() == true) + _controller.Update(song.Id, dialog.SongTitle, dialog.Artist, dialog.License, dialog.Attribution); + Refresh(); + } + + private async void OnDelete(object sender, RoutedEventArgs e) + { + if (Selected is not { } song) + return; + + var result = await new MessageBox + { + Title = "Delete song", + Content = $"Delete \"{song.Title}\" by {song.Artist} from the library?", + PrimaryButtonText = "Delete", + CloseButtonText = "Cancel", + }.ShowDialogAsync(); + + if (result != Wpf.Ui.Controls.MessageBoxResult.Primary) + return; + + _controller.Delete(song.Id); + Refresh(); + } +} diff --git a/src/Radiosender/Views/SongEditWindow.xaml b/src/Radiosender/Views/SongEditWindow.xaml new file mode 100644 index 0000000..f0537ea --- /dev/null +++ b/src/Radiosender/Views/SongEditWindow.xaml @@ -0,0 +1,41 @@ + + + + + + + + diff --git a/src/Radiosender/Views/SongEditWindow.xaml.cs b/src/Radiosender/Views/SongEditWindow.xaml.cs new file mode 100644 index 0000000..c2d9c52 --- /dev/null +++ b/src/Radiosender/Views/SongEditWindow.xaml.cs @@ -0,0 +1,34 @@ +using System.Windows; +using Radiosender.Models; +using Wpf.Ui.Controls; + +namespace Radiosender.Views; + +/// Dialog for the editable song metadata. Only collects input; saving is done by the caller. +public partial class SongEditWindow : FluentWindow +{ + public SongEditWindow(Song song) + { + InitializeComponent(); + TitleBox.Text = song.Title; + ArtistBox.Text = song.Artist; + LicenseBox.Text = song.License; + AttributionBox.Text = song.Attribution; + } + + public string SongTitle => TitleBox.Text; + public string Artist => ArtistBox.Text; + public string License => LicenseBox.Text; + public string Attribution => AttributionBox.Text; + + private void OnSave(object sender, RoutedEventArgs e) + { + if (string.IsNullOrWhiteSpace(SongTitle) || string.IsNullOrWhiteSpace(Artist)) + { + ErrorText.Visibility = Visibility.Visible; + return; + } + + DialogResult = true; + } +} diff --git a/tests/Radiosender.Tests/LibraryControllerTests.cs b/tests/Radiosender.Tests/LibraryControllerTests.cs new file mode 100644 index 0000000..9420585 --- /dev/null +++ b/tests/Radiosender.Tests/LibraryControllerTests.cs @@ -0,0 +1,107 @@ +using Microsoft.Data.Sqlite; +using Radiosender.Controllers; +using Radiosender.Models; +using Radiosender.Services; + +namespace Radiosender.Tests; + +public sealed class LibraryControllerTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N")); + private readonly SongRepository _repository; + private readonly LibraryController _controller; + + public LibraryControllerTests() + { + _repository = new SongRepository(Path.Combine(_directory, "test.db")); + _controller = new LibraryController(_repository); + } + + public void Dispose() + { + SqliteConnection.ClearAllPools(); // pooled connections keep the file locked + Directory.Delete(_directory, recursive: true); + } + + private Song AddSong(string title, string artist) + { + var song = new Song + { + Title = title, + Artist = artist, + Duration = TimeSpan.FromSeconds(200), + FilePath = @"C:\music\song.mp3", + Source = SongSource.Upload, + License = "CC BY 4.0", + }; + _repository.Add(song); + return song; + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Search_WithoutQuery_ReturnsAllSongs(string? query) + { + AddSong("Alpha", "Band"); + AddSong("Beta", "Other"); + + Assert.Equal(2, _controller.Search(query).Count); + } + + [Fact] + public void Search_MatchesTitleOrArtistCaseInsensitive() + { + AddSong("Morning Light", "Band"); + AddSong("Evening", "The Lights"); + AddSong("Unrelated", "Nobody"); + + var titles = _controller.Search(" LIGHT ").Select(s => s.Title).ToList(); + + Assert.Equal(["Evening", "Morning Light"], titles.Order()); + } + + [Fact] + public void Update_WritesEditableFieldsAndKeepsTheRest() + { + var song = AddSong("Old", "Old Artist"); + + Assert.True(_controller.Update(song.Id, " New ", "New Artist", " ", "by someone")); + + var loaded = _repository.GetById(song.Id)!; + Assert.Equal("New", loaded.Title); + Assert.Equal("New Artist", loaded.Artist); + Assert.Null(loaded.License); + Assert.Equal("by someone", loaded.Attribution); + Assert.Equal(song.FilePath, loaded.FilePath); + Assert.Equal(song.Duration, loaded.Duration); + Assert.Equal(song.Source, loaded.Source); + } + + [Fact] + public void Update_RejectsBlankTitleOrArtist() + { + var song = AddSong("Title", "Artist"); + + Assert.ThrowsAny(() => _controller.Update(song.Id, " ", "Artist", null, null)); + Assert.ThrowsAny(() => _controller.Update(song.Id, "Title", "", null, null)); + Assert.Equal("Title", _repository.GetById(song.Id)!.Title); + } + + [Fact] + public void Update_ReturnsFalseForUnknownSong() + { + Assert.False(_controller.Update(42, "Title", "Artist", null, null)); + } + + [Fact] + public void Delete_RemovesSong() + { + var song = AddSong("Title", "Artist"); + + Assert.True(_controller.Delete(song.Id)); + Assert.Empty(_controller.Search(null)); + Assert.False(_controller.Delete(song.Id)); + } +} From 5ea27408951c2116a0ee23eae49a96bcf6e2538f Mon Sep 17 00:00:00 2001 From: Julian Lechner Date: Mon, 23 Nov 2026 10:24:03 +0100 Subject: [PATCH 3/3] feat: add music player singleton on NAudio Add MusicPlayer, a thread-safe lazy singleton that plays one audio file at a time through NAudio 3.3.0 (WaveOut and AudioFileReader). It offers Play, Pause, Resume, Stop, Position, Duration, Volume and IsPlaying, plus TrackFinished and PositionChanged events. The station needs one shared playback point that later schedule and UI code can drive. TrackFinished fires only when a track ends on its own. Stop and Play unsubscribe from the old output before releasing it, so they never raise it. Both events run on a thread-pool thread, so WPF callers must marshal to the dispatcher. Reader and output are disposed on stop, on replacement and on process exit. A missing file throws FileNotFoundException and an unreadable one InvalidDataException; in both cases the player stays stopped. Tests cover the singleton, error cases and events. Tests that need an audio device skip when none is present. Refs #6 Co-Authored-By: Claude Opus 5.5 --- src/Radiosender/Radiosender.csproj | 1 + src/Radiosender/Services/MusicPlayer.cs | 174 ++++++++++++++++++++ tests/Radiosender.Tests/MusicPlayerTests.cs | 134 +++++++++++++++ 3 files changed, 309 insertions(+) create mode 100644 src/Radiosender/Services/MusicPlayer.cs create mode 100644 tests/Radiosender.Tests/MusicPlayerTests.cs diff --git a/src/Radiosender/Radiosender.csproj b/src/Radiosender/Radiosender.csproj index c78ea43..54e8141 100644 --- a/src/Radiosender/Radiosender.csproj +++ b/src/Radiosender/Radiosender.csproj @@ -10,6 +10,7 @@ + diff --git a/src/Radiosender/Services/MusicPlayer.cs b/src/Radiosender/Services/MusicPlayer.cs new file mode 100644 index 0000000..c84fd16 --- /dev/null +++ b/src/Radiosender/Services/MusicPlayer.cs @@ -0,0 +1,174 @@ +using System.IO; +using NAudio.Wave; + +namespace Radiosender.Services; + +/// +/// Plays one audio file at a time through the default output device. +/// +/// +/// and are raised on a thread-pool thread, +/// never on the WPF UI thread. WPF callers must marshal with Dispatcher.Invoke or +/// Dispatcher.BeginInvoke before touching UI elements. +/// +public sealed class MusicPlayer +{ + private static readonly Lazy LazyInstance = new(() => new MusicPlayer()); + + private static readonly TimeSpan PositionInterval = TimeSpan.FromMilliseconds(250); + + private readonly Lock _lock = new(); + private WaveOut? _output; + private AudioFileReader? _reader; + private Timer? _positionTimer; + private float _volume = 1f; + + private MusicPlayer() + { + // Releases the audio device when the app exits. + AppDomain.CurrentDomain.ProcessExit += (_, _) => Stop(); + } + + public static MusicPlayer Instance => LazyInstance.Value; + + /// Raised when a track reaches its end. Not raised by or by replacing a track. + public event EventHandler? TrackFinished; + + /// Raised about every 250 ms while a track is playing, with the current position. + public event EventHandler? PositionChanged; + + public bool IsPlaying + { + get { lock (_lock) return _output?.PlaybackState == PlaybackState.Playing; } + } + + public TimeSpan Position + { + get { lock (_lock) return _reader?.CurrentTime ?? TimeSpan.Zero; } + } + + public TimeSpan Duration + { + get { lock (_lock) return _reader?.TotalTime ?? TimeSpan.Zero; } + } + + /// Playback volume from 0 (silent) to 1 (full). Kept across tracks. + public float Volume + { + get { lock (_lock) return _volume; } + set + { + ArgumentOutOfRangeException.ThrowIfLessThan(value, 0f); + ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 1f); + lock (_lock) + { + _volume = value; + if (_reader is not null) _reader.Volume = value; + } + } + } + + /// Stops the current track and starts playing . + /// The file does not exist. + /// The file is not a readable audio file. + public void Play(string filePath) + { + ArgumentException.ThrowIfNullOrWhiteSpace(filePath); + + lock (_lock) + { + Release(); + + if (!File.Exists(filePath)) + throw new FileNotFoundException($"Audio file not found: {filePath}", filePath); + + try + { + _reader = new AudioFileReader(filePath) { Volume = _volume }; + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + throw new InvalidDataException($"Cannot read audio file: {filePath}", ex); + } + + try + { + _output = new WaveOut(); + _output.PlaybackStopped += OnPlaybackStopped; + _output.Init(_reader); + _output.Play(); + _positionTimer = new Timer(OnPositionTimer, null, PositionInterval, PositionInterval); + } + catch + { + Release(); + throw; + } + } + } + + public void Pause() + { + lock (_lock) + { + if (_output?.PlaybackState == PlaybackState.Playing) _output.Pause(); + } + } + + public void Resume() + { + lock (_lock) + { + if (_output?.PlaybackState == PlaybackState.Paused) _output.Play(); + } + } + + /// Stops playback and releases the file and audio device. Does not raise . + public void Stop() + { + lock (_lock) Release(); + } + + // Caller holds _lock. Unsubscribing first keeps Stop and track replacement from raising TrackFinished. + private void Release() + { + _positionTimer?.Dispose(); + _positionTimer = null; + + if (_output is not null) + { + _output.PlaybackStopped -= OnPlaybackStopped; + _output.Dispose(); + _output = null; + } + + _reader?.Dispose(); + _reader = null; + } + + private void OnPlaybackStopped(object? sender, StoppedEventArgs e) + { + lock (_lock) + { + // A stale event from an output that Stop or Play already released. + if (!ReferenceEquals(sender, _output)) return; + Release(); + } + + // An exception means a device error, not a natural end of the track. + if (e.Exception is null) + ThreadPool.QueueUserWorkItem(_ => TrackFinished?.Invoke(this, EventArgs.Empty)); + } + + private void OnPositionTimer(object? state) + { + TimeSpan position; + lock (_lock) + { + if (_output?.PlaybackState != PlaybackState.Playing || _reader is null) return; + position = _reader.CurrentTime; + } + + PositionChanged?.Invoke(this, position); + } +} diff --git a/tests/Radiosender.Tests/MusicPlayerTests.cs b/tests/Radiosender.Tests/MusicPlayerTests.cs new file mode 100644 index 0000000..a97b373 --- /dev/null +++ b/tests/Radiosender.Tests/MusicPlayerTests.cs @@ -0,0 +1,134 @@ +using System.IO; +using NAudio.Wave; +using Radiosender.Services; + +namespace Radiosender.Tests; + +/// Skips the test on machines without an audio output device (for example CI agents). +public sealed class AudioDeviceFactAttribute : FactAttribute +{ + public AudioDeviceFactAttribute() + { + if (WaveOut.DeviceCount == 0) Skip = "No audio output device available."; + } +} + +public sealed class MusicPlayerTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N")); + + public MusicPlayerTests() => Directory.CreateDirectory(_directory); + + public void Dispose() + { + MusicPlayer.Instance.Stop(); + Directory.Delete(_directory, recursive: true); + } + + // Writes a short, quiet sine tone as 16-bit mono PCM. + private string CreateWav(TimeSpan length) + { + var path = Path.Combine(_directory, "tone.wav"); + var format = new WaveFormat(44100, 16, 1); + using var writer = new WaveFileWriter(path, format); + var samples = (int)(format.SampleRate * length.TotalSeconds); + for (var i = 0; i < samples; i++) + writer.WriteSample(0.05f * MathF.Sin(2 * MathF.PI * 440 * i / format.SampleRate)); + return path; + } + + [Fact] + public void Instance_ReturnsSameObjectOnRepeatedAccess() + { + Assert.Same(MusicPlayer.Instance, MusicPlayer.Instance); + } + + [Fact] + public void Instance_ReturnsSameObjectAcrossThreads() + { + var instances = new MusicPlayer[16]; + Parallel.For(0, instances.Length, i => instances[i] = MusicPlayer.Instance); + + Assert.All(instances, instance => Assert.Same(MusicPlayer.Instance, instance)); + } + + [Fact] + public void Play_MissingFile_ThrowsAndStaysStopped() + { + var path = Path.Combine(_directory, "missing.mp3"); + + var exception = Assert.Throws(() => MusicPlayer.Instance.Play(path)); + + Assert.Equal(path, exception.FileName); + Assert.False(MusicPlayer.Instance.IsPlaying); + Assert.Equal(TimeSpan.Zero, MusicPlayer.Instance.Duration); + } + + [Fact] + public void Play_UnreadableFile_ThrowsInvalidDataAndStaysStopped() + { + var path = Path.Combine(_directory, "broken.wav"); + File.WriteAllText(path, "not audio"); + + Assert.Throws(() => MusicPlayer.Instance.Play(path)); + Assert.False(MusicPlayer.Instance.IsPlaying); + } + + [Fact] + public void Volume_OutOfRange_Throws() + { + Assert.Throws(() => MusicPlayer.Instance.Volume = 1.5f); + Assert.Throws(() => MusicPlayer.Instance.Volume = -0.1f); + } + + [AudioDeviceFact] + public void Stop_DoesNotRaiseTrackFinished() + { + var player = MusicPlayer.Instance; + var finished = 0; + EventHandler handler = (_, _) => Interlocked.Increment(ref finished); + player.TrackFinished += handler; + try + { + player.Play(CreateWav(TimeSpan.FromSeconds(0.5))); + Assert.True(player.IsPlaying); + + player.Stop(); + Thread.Sleep(1000); // longer than the track, so a natural end would have fired by now + + Assert.Equal(0, finished); + Assert.False(player.IsPlaying); + } + finally + { + player.TrackFinished -= handler; + } + } + + [AudioDeviceFact] + public void Play_ShortWav_RaisesTrackFinishedAndPositionChanged() + { + var player = MusicPlayer.Instance; + using var finished = new ManualResetEventSlim(); + var positionChanged = false; + EventHandler finishedHandler = (_, _) => finished.Set(); + EventHandler positionHandler = (_, _) => positionChanged = true; + player.TrackFinished += finishedHandler; + player.PositionChanged += positionHandler; + try + { + player.Play(CreateWav(TimeSpan.FromSeconds(0.6))); + Assert.InRange(player.Duration.TotalSeconds, 0.59, 0.61); + + Assert.True(finished.Wait(TimeSpan.FromSeconds(5)), "TrackFinished was not raised."); + Assert.True(positionChanged); + Assert.False(player.IsPlaying); + Assert.Equal(TimeSpan.Zero, player.Duration); + } + finally + { + player.TrackFinished -= finishedHandler; + player.PositionChanged -= positionHandler; + } + } +}