refactor: enhance audio playback service with semaphore locking for thread safety

This commit is contained in:
HueByte
2026-02-22 16:43:05 +01:00
parent 4f96b8d986
commit 993bb1f973
2 changed files with 81 additions and 28 deletions
@@ -6,6 +6,7 @@ namespace EchoHub.Client.Services;
public class AudioPlaybackService
{
private readonly Player _player = new();
private readonly SemaphoreSlim _lock = new(1, 1);
public bool IsPlaying => _player.Playing;
public bool IsPaused => _player.Paused;
@@ -19,6 +20,7 @@ public class AudioPlaybackService
public async Task PlayAsync(string filePath)
{
await _lock.WaitAsync();
try
{
if (_player.Playing)
@@ -30,10 +32,15 @@ public class AudioPlaybackService
{
Log.Warning(ex, "Failed to play audio file: {Path}", filePath);
}
finally
{
_lock.Release();
}
}
public async Task PauseAsync()
{
await _lock.WaitAsync();
try
{
if (_player.Playing && !_player.Paused)
@@ -43,10 +50,15 @@ public class AudioPlaybackService
{
Log.Warning(ex, "Failed to pause audio playback");
}
finally
{
_lock.Release();
}
}
public async Task ResumeAsync()
{
await _lock.WaitAsync();
try
{
if (_player.Paused)
@@ -56,23 +68,33 @@ public class AudioPlaybackService
{
Log.Warning(ex, "Failed to resume audio playback");
}
finally
{
_lock.Release();
}
}
public async Task StopAsync()
{
await _lock.WaitAsync();
try
{
if (_player.Playing)
if (_player.Playing || _player.Paused)
await _player.Stop();
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to stop audio playback");
}
finally
{
_lock.Release();
}
}
public async Task SetVolumeAsync(byte volume)
{
await _lock.WaitAsync();
try
{
await _player.SetVolume(Math.Min(volume, (byte)100));
@@ -81,5 +103,9 @@ public class AudioPlaybackService
{
Log.Warning(ex, "Failed to set audio volume");
}
finally
{
_lock.Release();
}
}
}