AUdio Player Service refactor

This commit is contained in:
daniel-c-harvey
2025-09-08 14:20:38 -04:00
parent bf054f3d1b
commit a25d067dff
14 changed files with 323 additions and 158 deletions
@@ -18,7 +18,7 @@ public class AudioPlaybackEngine : IAsyncDisposable
public bool IsPlaying { get; private set; } = false;
public bool IsPaused { get; private set; } = false;
public double CurrentTime { get; private set; } = 0;
public double Duration { get; private set; } = 0;
public double? Duration { get; private set; } = null;
public double Volume { get; private set; } = 0.8;
public double LoadProgress { get; private set; } = 0;
public string? ErrorMessage { get; private set; }
@@ -55,38 +55,99 @@ public class AudioPlaybackEngine : IAsyncDisposable
try
{
ErrorMessage = null;
LoadProgress = 0;
AudioOperationResult? loadResult = await AudioInterop.InitializeBufferedPlayerAsync(PlayerId);
TrackMediaResponse? audio = await Client.GetTrackMedia(track.EntryKey);
if (loadResult?.Success != true)
{
ErrorMessage = $"Failed to initialize audio buffer: {loadResult?.Error ?? "Unknown error"}";
return;
}
if (loadResult?.Success == true)
var mediaResult = await Client.GetTrackMedia(track.EntryKey);
if (!mediaResult.Success)
{
IsLoaded = true;
ErrorMessage = null;
await StreamAndPlay(audio);
ErrorMessage = mediaResult.GetMessage();
return;
}
else
if (mediaResult.Value == null)
{
ErrorMessage = $"Failed to play audio: {loadResult?.Error ?? "No audio source provided"}";
ErrorMessage = "No audio returned from server";
return;
}
TrackMediaResponse audio = mediaResult.Value;
await StreamAndPlay(audio);
}
catch (Exception ex)
{
ErrorMessage = $"Error loading audio: {ex.Message}";
LoadProgress = 0;
IsLoaded = false;
}
}
private async Task StreamAndPlay(TrackMediaResponse audio)
{
int bytesRead = 0;
do
try
{
var buffer = new byte[8 * 1024];
int newBytes = await audio.Stream.ReadAsync(buffer, 0, buffer.Length);
bytesRead += newBytes;
if (bytesRead == 0) break;
await AudioInterop.AppendAudioBlockAsync(PlayerId, buffer);
} while (bytesRead < audio.ContentLength);
await AudioInterop.FinalizeAudioBufferAsync(PlayerId);
const int bufferSize = 32 * 1024; // Increased buffer size for better performance
long totalBytesRead = 0;
int currentBytes;
do
{
var buffer = new byte[bufferSize];
currentBytes = await audio.Stream.ReadAsync(buffer, 0, buffer.Length);
if (currentBytes > 0)
{
totalBytesRead += currentBytes;
// Resize buffer if we didn't read the full amount
if (currentBytes < bufferSize)
{
var trimmedBuffer = new byte[currentBytes];
Array.Copy(buffer, trimmedBuffer, currentBytes);
buffer = trimmedBuffer;
}
var appendResult = await AudioInterop.AppendAudioBlockAsync(PlayerId, buffer);
if (!appendResult.Success)
{
throw new Exception($"Failed to append audio block: {appendResult.Error}");
}
// Update progress during streaming
if (audio.ContentLength > 0)
{
LoadProgress = Math.Min(1.0, (double)totalBytesRead / audio.ContentLength);
}
}
} while (currentBytes > 0);
// Finalize the buffer and update metadata
var finalizeResult = await AudioInterop.FinalizeAudioBufferAsync(PlayerId);
if (!finalizeResult.Success)
{
throw new Exception($"Failed to finalize audio buffer: {finalizeResult.Error}");
}
// Update engine state with audio metadata
Duration = finalizeResult.Duration;
LoadProgress = 1.0;
IsLoaded = true;
ErrorMessage = null;
}
catch (Exception ex)
{
ErrorMessage = $"Error streaming audio: {ex.Message}";
LoadProgress = 0;
IsLoaded = false;
throw;
}
}
public async Task TogglePlayPause()
@@ -0,0 +1,28 @@
using DeepDrftModels.Entities;
namespace DeepDrftWeb.Client.Services;
public interface IPlayerService
{
// State properties
bool IsInitialized { get; }
bool IsLoaded { get; }
bool IsPlaying { get; }
bool IsPaused { get; }
double CurrentTime { get; }
double? Duration { get; }
double Volume { get; }
double LoadProgress { get; }
string? ErrorMessage { get; }
// Events for UI updates
event Action? OnStateChanged;
// Control methods
Task SelectTrack(TrackEntity track);
Task Stop();
Task TogglePlayPause();
Task Seek(double position);
Task SetVolume(double volume);
void ClearError();
}
@@ -0,0 +1,113 @@
using DeepDrftModels.Entities;
namespace DeepDrftWeb.Client.Services;
public class PlayerService : IPlayerService
{
private AudioPlaybackEngine? _audioEngine;
private bool _isInitialized = false;
public PlayerService()
{
// Parameterless constructor - AudioPlaybackEngine will be set during initialization
}
// IPlayerService state properties with defensive checks
public bool IsInitialized => _isInitialized;
public bool IsLoaded => _isInitialized && _audioEngine?.IsLoaded == true;
public bool IsPlaying => _isInitialized && _audioEngine?.IsPlaying == true;
public bool IsPaused => _isInitialized && _audioEngine?.IsPaused == true;
public double CurrentTime => _isInitialized ? _audioEngine?.CurrentTime ?? 0.0 : 0.0;
public double? Duration => _isInitialized ? _audioEngine?.Duration : null;
public double Volume => _isInitialized ? _audioEngine?.Volume ?? 0.8 : 0.8;
public double LoadProgress => _isInitialized ? _audioEngine?.LoadProgress ?? 0.0 : 0.0;
public string? ErrorMessage => _isInitialized ? _audioEngine?.ErrorMessage : null;
public event Action? OnStateChanged;
public async Task SelectTrack(TrackEntity track)
{
if (!_isInitialized)
{
await EnsureInitializedAsync();
}
if (_isInitialized && _audioEngine != null)
{
await _audioEngine.LoadTrack(track);
OnStateChanged?.Invoke();
}
}
public async Task Stop()
{
if (!_isInitialized || _audioEngine == null) return;
await _audioEngine.Stop();
OnStateChanged?.Invoke();
}
public async Task TogglePlayPause()
{
if (!_isInitialized || _audioEngine == null) return;
await _audioEngine.TogglePlayPause();
OnStateChanged?.Invoke();
}
public async Task Seek(double position)
{
if (!_isInitialized || _audioEngine == null) return;
await _audioEngine.OnSeek(position);
OnStateChanged?.Invoke();
}
public async Task SetVolume(double volume)
{
if (!_isInitialized || _audioEngine == null) return;
await _audioEngine.OnVolumeChange(volume);
OnStateChanged?.Invoke();
}
public void ClearError()
{
if (!_isInitialized || _audioEngine == null) return;
_audioEngine.ClearError();
OnStateChanged?.Invoke();
}
public async Task InitializeAsync(AudioPlaybackEngine audioEngine)
{
if (_isInitialized) return;
_audioEngine = audioEngine;
try
{
await _audioEngine.InitializeAudioPlayer();
// Wire up engine events to trigger state change notifications
_audioEngine.OnProgressChanged += async _ => OnStateChanged?.Invoke();
_audioEngine.OnPlaybackEnded += async () => OnStateChanged?.Invoke();
_isInitialized = true;
OnStateChanged?.Invoke();
}
catch (Exception ex)
{
// Log error but don't throw - allow UI to continue functioning
Console.WriteLine($"Failed to initialize audio engine: {ex.Message}");
}
}
private async Task EnsureInitializedAsync()
{
if (!_isInitialized && _audioEngine != null)
{
await InitializeAsync(_audioEngine);
}
}
}