Fixed loading multiple songs issue.

This commit is contained in:
2026-07-28 00:19:30 -04:00
parent a85c65e833
commit 7cfcbf26cc
2 changed files with 44 additions and 13 deletions

View File

@@ -6,6 +6,7 @@ namespace Harmonia.Core.Engine;
public class BassAudioEngine : IAudioEngine, IDisposable
{
private readonly BaseMediaPlayer _mediaPlayer;
private readonly SemaphoreSlim _loadLock = new(1, 1);
private CancellationTokenSource? _cancellationTokenSource;
@@ -136,27 +137,48 @@ public class BassAudioEngine : IAudioEngine, IDisposable
private async Task<bool> LoadWaveSourceAsync(string fileName)
{
_cancellationTokenSource?.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = _cancellationTokenSource.Token;
CancellationTokenSource cancellationTokenSource = new();
_cancellationTokenSource = cancellationTokenSource;
CancellationToken token = cancellationTokenSource.Token;
// Serialize loads so overlapping MediaPlayer.LoadAsync calls can't
// race and leave orphaned streams playing.
await _loadLock.WaitAsync(CancellationToken.None);
try
{
await _mediaPlayer.LoadAsync(fileName);
}
catch (Exception ex)
{
if (token.IsCancellationRequested)
return false;
//return new Result(State.Exception, ex.Message);
throw new Exception("An error occurred - " + fileName, ex);
try
{
await _mediaPlayer.LoadAsync(fileName);
}
catch (Exception ex)
{
if (token.IsCancellationRequested)
return false;
//return new Result(State.Exception, ex.Message);
throw new Exception("An error occurred - " + fileName, ex);
}
if (token.IsCancellationRequested)
{
// A newer load superseded this one; make sure this stream
// doesn't keep playing in the background.
_mediaPlayer.Stop();
return false;
}
return true;
}
finally
{
_loadLock.Release();
}
if (token.IsCancellationRequested)
return false;
return true;
}
private void UpdateSource(string fileName)