1using System.Collections.Concurrent;
4using Microsoft.Extensions.Logging;
11public sealed class AudioResourceManager : IDisposable
13 [Newtonsoft.Json.JsonIgnore]
internal DefinitionProvenance? DefinitionProvenance {
get;
set; }
15 private static readonly Lazy<AudioResourceManager> _instance =
new(() =>
new AudioResourceManager());
16 private readonly ConcurrentDictionary<string, AudioResource> _soundResources =
new(StringComparer.Ordinal);
17 private readonly
object _backendLock =
new();
19 private bool _disposed;
27 private AudioResourceManager() { }
32 public static AudioResourceManager
Instance => _instance.Value;
48 ArgumentNullException.ThrowIfNull(backend);
52 if (ReferenceEquals(_backend, backend))
55 if (_backend is not
null && _soundResources.Count != 0)
57 throw new InvalidOperationException(
58 $
"Cannot replace audio backend '{_backend.Name}' with '{backend.Name}' while audio resources are loaded. Clear the audio resource manager first.");
62 Engine.
Logger.LogInformation(
"Configured Gondwana audio backend: {AudioBackend}", backend.
Name);
101 float playbackSpeed = 1.0f)
121 string? sourceExtension,
126 var bytes = File.ReadAllBytes(filePath);
128 var resource = LoadFromBytes(
131 string.IsNullOrWhiteSpace(sourceExtension) ? filePath : sourceExtension,
136 resource.SetSourceFilePath(filePath);
180 float playbackSpeed = 1.0f)
182 using var ms =
new MemoryStream();
185 return LoadFromBytes(
209 float playbackSpeed = 1.0f)
213 if (
string.IsNullOrWhiteSpace(uri))
214 throw new ArgumentException(
"Audio URI cannot be empty.", nameof(uri));
222 var speed = ClampPlaybackSpeed(playbackSpeed);
224 var playback = RequireBackend().CreateFromUri(
227 Math.Clamp(volume, 0f, 1f),
228 Math.Clamp(pan, -1f, 1f),
242 resource.SetSourceUri(uri);
243 RegisterLoadedSound(key, resource);
248 DisposeFailedLoad(resource, playback);
279 float defaultVolume = 1.0f,
280 float defaultPan = 0.0f,
281 float defaultPlaybackSpeed = 1.0f)
283 List<AudioResource> loadedSounds = [];
285 foreach (var entry
in resourceFile.GetAllEntries())
292 if (_soundResources.ContainsKey(entry.AssetName))
294 Engine.
Logger.LogDebug(
"AudioResource '{Key}' already loaded. Skipping.", entry.AssetName);
298 var stream = resourceFile.Get(entry.AssetType, entry.AssetName);
302 Engine.
Logger.LogWarning(
"Failed to retrieve stream for audio resource: {Key}", entry.AssetName);
309 using (var ms =
new MemoryStream())
313 var sound = LoadFromBytes(
319 defaultPlaybackSpeed);
321 sound.SetAssetIdentifier(
324 loadedSounds.Add(sound);
327 Engine.
Logger.LogInformation(
"Loaded sound: {Key}", entry.AssetName);
331 Engine.
Logger.LogError(ex,
"Error loading sound from asset file for key: {Key}", entry.AssetName);
373 string? newKey =
null,
374 float? volume =
null,
376 float? playbackSpeed =
null)
380 if (!_soundResources.TryGetValue(key, out var original))
382 Engine.
Logger.LogWarning(
"Attempted to clone non-existent AudioResource with key: {Key}", key);
386 newKey ??= $
"{key}_clone_{Guid.NewGuid()}";
388 if (_soundResources.ContainsKey(newKey))
390 Engine.
Logger.LogWarning(
"AudioResource with key '{Key}' already exists. Cannot clone.", newKey);
396 if (original.OriginalBytes is not
null && !
string.IsNullOrEmpty(original.SourceExtension))
398 using var stream =
new MemoryStream(original.OriginalBytes, writable:
false);
403 original.SourceExtension,
404 volume ?? original.Volume,
406 playbackSpeed ?? original.PlaybackSpeed);
408 else if (!
string.IsNullOrWhiteSpace(original.SourceUri))
413 volume ?? original.Volume,
415 playbackSpeed ?? original.PlaybackSpeed);
420 "Cannot clone AudioResource '{Key}' because its source cannot be recreated.",
426 clone.CopySourceFrom(original);
427 clone.IsLooping = original.IsLooping;
442 var ext = Path.GetExtension(fileHint);
444 if (
string.IsNullOrWhiteSpace(ext))
446 throw new InvalidOperationException(
447 $
"Audio asset '{key}' has no file extension. Ensure audio AssetsFile entries retain their extension.");
456 var speed = ClampPlaybackSpeed(playbackSpeed);
462 Math.Clamp(volume, 0f, 1f),
463 Math.Clamp(pan, -1f, 1f),
466 AudioResource? sound =
null;
470 sound =
new AudioResource(
479 RegisterLoadedSound(key, sound);
484 DisposeFailedLoad(sound, playback);
490 private static void DisposeFailedLoad(AudioResource? resource, IAudioPlaybackHandle playback)
494 if (resource is not
null)
502 Engine.Logger.LogError(ex,
"Failed to release an audio handle after loading failed.");
506 private HashSet<AudioResource>? _retainedDefinitionResources;
508 private void ReplaceExisting(
string key)
510 if (_soundResources.TryGetValue(key, out var existing))
512 if (_retainedDefinitionResources?.
Contains(existing) ==
true)
513 _soundResources.TryRemove(key, out _);
523 internal T LoadDefinitionDocument<T>(Func<T> load)
527 if (_retainedDefinitionResources is not
null)
528 throw new InvalidOperationException(
"A definition document load is already in progress.");
532 var settings = previous.Values.ToDictionary(
533 resource => resource,
534 resource => (resource.Volume, resource.Pan, resource.PlaybackSpeed, resource.IsLooping));
536 var provenance = DefinitionProvenance;
537 _retainedDefinitionResources = previous.Values.ToHashSet();
546 foreach (var resource
in _soundResources.Values.ToArray())
547 if (!_retainedDefinitionResources.Contains(resource))
550 _soundResources.Clear();
552 foreach (var pair
in previous)
553 _soundResources[pair.Key] = pair.Value;
555 foreach (var pair
in settings)
557 pair.Key.Volume = pair.Value.Volume;
558 pair.Key.Pan = pair.Value.Pan;
559 pair.Key.PlaybackSpeed = pair.Value.PlaybackSpeed;
560 pair.Key.IsLooping = pair.Value.IsLooping;
563 DefinitionProvenance = provenance;
568 _retainedDefinitionResources =
null;
571 foreach (var pair
in previous)
572 if (!_soundResources.TryGetValue(pair.Key, out var current) || !ReferenceEquals(current, pair.Value))
573 pair.Value.Dispose();
579 private static void ValidateSettings(
585 ArgumentException.ThrowIfNullOrWhiteSpace(key);
587 if (
float.IsNaN(volume) ||
float.IsNaN(pan) ||
float.IsNaN(speed))
588 throw new ArgumentOutOfRangeException(nameof(speed),
"Audio settings must not be NaN.");
591 private void RegisterLoadedSound(
string key, AudioResource sound)
593 ReplaceExisting(key);
594 _soundResources[key] = sound;
596 sound.Disposed += (_, _) =>
598 if (((ICollection<KeyValuePair<string, AudioResource>>)_soundResources).Remove(
new(key, sound)))
605 private IAudioBackend RequireBackend() => _backend
606 ??
throw new InvalidOperationException(
607 "No Gondwana audio backend is configured. Install and initialize a backend such as Gondwana.Audio.NAudio or Gondwana.Audio.Browser before loading audio.");
609 private static float ClampPlaybackSpeed(
float speed) =>
610 Math.Clamp(speed, AudioResource.MinimumPlaybackSpeed, AudioResource.MaximumPlaybackSpeed);
620 ReplaceExisting(key);
629 DefinitionProvenance =
null;
633 foreach (var resource
in _soundResources.Values.ToArray())
636 _soundResources.Clear();
646 public bool TryGet(
string key, out
AudioResource? resource) => _soundResources.TryGetValue(key, out resource);
653 public AudioResource?
Get(
string key) => _soundResources.TryGetValue(key, out var resource) ? resource :
null;
660 public bool Contains(
string key) => _soundResources.ContainsKey(key);
666 public IEnumerable<string>
GetAllKeys() => _soundResources.Keys;
672 public Dictionary<string, AudioResource>
GetAll() =>
new(_soundResources);
Represents an identifier for a specific asset within a file, including its type and name.
Represents an asset file used by the engine, providing functionality to load, manage,...
AudioResource? Clone(string key, string? newKey=null, float? volume=null, float? pan=null, float? playbackSpeed=null)
Creates a clone of an existing AudioResource. The clone may inherit or override volume,...
List< AudioResource > LoadFromEngineAssetsFile(AssetsFile resourceFile, float defaultVolume=1.0f, float defaultPan=0.0f, float defaultPlaybackSpeed=1.0f)
Loads all audio entries from the provided AssetsFile and returns the loaded resources.
void ConfigureBackend(IAudioBackend backend)
Configures the backend used for subsequently loaded audio resources. A backend cannot be replaced whi...
AudioResource LoadFromStream(string key, Stream input, string fileExt, float volume=1.0f, float pan=0.0f, float playbackSpeed=1.0f)
Loads an audio resource from the provided Stream.
List< AudioResource > LoadFromEngineAssetsFile(AssetsFile resourceFile, float defaultVolume, float defaultPan)
Compatibility overload that loads audio resources from an AssetsFile. Retains the pre-backend-refacto...
bool Contains(string key)
Determines whether an audio resource with the specified key is loaded.
AudioResource LoadFromUri(string key, string uri, float volume=1.0f, float pan=0.0f, float playbackSpeed=1.0f)
Loads an audio source by URI. This is primarily intended for URI-capable backends such as browser aud...
void Unload(string key)
Unloads and disposes the audio resource with the specified key, if it exists.
void Clear()
Disposes and clears all loaded audio resources.
AudioResource LoadFromStream(string key, Stream input, string fileExt, float volume, float pan)
Compatibility overload that loads an audio resource from a stream. Retains the pre-backend-refactor C...
bool IsBackendConfigured
Gets whether an audio backend has been configured.
IAudioBackend? Backend
Gets the currently configured audio backend, or null if none has been configured.
AudioResource LoadFromFile(string key, string filePath, float volume=1.0f, float pan=0.0f, float playbackSpeed=1.0f)
Loads an audio resource from a file on disk.
void Dispose()
Disposes the manager and all loaded audio resources. This method is idempotent.
EventHandler<(string Key, AudioResource Resource)>? SoundDisposed
Occurs when a loaded AudioResource is disposed and removed from the manager. The event payload contai...
Dictionary< string, AudioResource > GetAll()
Returns a snapshot dictionary of all loaded audio resources.
IEnumerable< string > GetAllKeys()
Returns all loaded audio resource keys.
static AudioResourceManager Instance
Gets the singleton AudioResourceManager instance.
AudioResource? Clone(string key, string? newKey, float? volume, float? pan)
Compatibility overload that creates a clone of an existing audio resource. Retains the pre-backend-re...
bool TryGet(string key, out AudioResource? resource)
Attempts to retrieve a loaded audio resource by key.
AudioResource? Get(string key)
Gets the AudioResource with the specified key, or null if not found.
AudioResource LoadFromFile(string key, string filePath, float volume, float pan)
Compatibility overload that loads an audio resource from a file path. Retains the pre-backend-refacto...
Represents an audio resource that can be played, paused, resumed, sought, and disposed....
Represents the core game engine singleton responsible for managing the main update loop,...
static ILogger< Engine > Logger
Gets the logger instance used by the engine for diagnostic and informational messages.
Creates backend-specific playback handles for the engine's common audio API.
IAudioPlaybackHandle CreateFromBytes(string key, byte[] data, string fileNameOrExtension, float volume, float pan, float playbackSpeed)
Creates a playback handle from raw audio bytes. The implementation is responsible for interpreting th...
string Name
Gets the human-readable name of the backend implementation.
AssetTypes
Defines the types of assets that can be stored and managed by the engine.