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 <noreply@anthropic.com>
This commit is contained in:
1 parent
89b7959404
commit
5ea2740895
3 files changed
+309
No files matched your search
@@ -10,6 +10,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.15" />
|
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.15" />
|
||||||
|
<PackageReference Include="NAudio" Version="3.3.0" />
|
||||||
<PackageReference Include="WPF-UI" Version="4.3.0" />
|
<PackageReference Include="WPF-UI" Version="4.3.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,174 @@
|
|||||||
|
using System.IO;
|
||||||
|
using NAudio.Wave;
|
||||||
|
|
||||||
|
namespace Radiosender.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Plays one audio file at a time through the default output device.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// <see cref="TrackFinished"/> and <see cref="PositionChanged"/> are raised on a thread-pool thread,
|
||||||
|
/// never on the WPF UI thread. WPF callers must marshal with <c>Dispatcher.Invoke</c> or
|
||||||
|
/// <c>Dispatcher.BeginInvoke</c> before touching UI elements.
|
||||||
|
/// </remarks>
|
||||||
|
public sealed class MusicPlayer
|
||||||
|
{
|
||||||
|
private static readonly Lazy<MusicPlayer> 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;
|
||||||
|
|
||||||
|
/// <summary>Raised when a track reaches its end. Not raised by <see cref="Stop"/> or by <see cref="Play"/> replacing a track.</summary>
|
||||||
|
public event EventHandler? TrackFinished;
|
||||||
|
|
||||||
|
/// <summary>Raised about every 250 ms while a track is playing, with the current position.</summary>
|
||||||
|
public event EventHandler<TimeSpan>? 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; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Playback volume from 0 (silent) to 1 (full). Kept across tracks.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Stops the current track and starts playing <paramref name="filePath"/>.</summary>
|
||||||
|
/// <exception cref="FileNotFoundException">The file does not exist.</exception>
|
||||||
|
/// <exception cref="InvalidDataException">The file is not a readable audio file.</exception>
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Stops playback and releases the file and audio device. Does not raise <see cref="TrackFinished"/>.</summary>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
using System.IO;
|
||||||
|
using NAudio.Wave;
|
||||||
|
using Radiosender.Services;
|
||||||
|
|
||||||
|
namespace Radiosender.Tests;
|
||||||
|
|
||||||
|
/// <summary>Skips the test on machines without an audio output device (for example CI agents).</summary>
|
||||||
|
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<FileNotFoundException>(() => 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<InvalidDataException>(() => MusicPlayer.Instance.Play(path));
|
||||||
|
Assert.False(MusicPlayer.Instance.IsPlaying);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Volume_OutOfRange_Throws()
|
||||||
|
{
|
||||||
|
Assert.Throws<ArgumentOutOfRangeException>(() => MusicPlayer.Instance.Volume = 1.5f);
|
||||||
|
Assert.Throws<ArgumentOutOfRangeException>(() => 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<TimeSpan> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user