Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
AudioResource.cs
3using Microsoft.Extensions.Logging;
4using Newtonsoft.Json;
5
6namespace Gondwana.Audio;
7
12[JsonObject(IsReference = true)]
13public class AudioResource : IDisposable
14{
16 [JsonIgnore]
17 internal DefinitionProvenance? DefinitionProvenance { get; set; }
18
23 public const float MinimumPlaybackSpeed = 0.25f;
24
28 public const float MaximumPlaybackSpeed = 4.0f;
29
30 private IAudioPlaybackHandle? _playback;
31 private bool _disposed;
32
33 [JsonProperty] private float _volume = 1.0f;
34
35 [JsonProperty] private float _pan;
36
37 [JsonProperty] private float _playbackSpeed = 1.0f;
38
39 [JsonProperty] private bool _isLooping;
40
44 public event EventHandler? PlaybackCompleted;
45
49 public Func<Task>? PlaybackCompletedAsync;
50
54 public event EventHandler? Disposed;
55
56 [JsonConstructor]
57 private AudioResource()
58 {
59 Key = string.Empty;
60 }
61
62 internal AudioResource(
63 string key,
64 IAudioPlaybackHandle playback,
65 float volume = 1.0f,
66 float pan = 0.0f,
67 float playbackSpeed = 1.0f,
68 string? filePathOrExt = null,
69 byte[]? rawBytes = null,
70 AssetsFileIdentifier? assetIdentifier = null)
71 {
72 Key = key;
73 _playback = playback ?? throw new ArgumentNullException(nameof(playback));
74
75 AssetIdentifier = assetIdentifier;
76
77 SourceFilePath = assetIdentifier is null && !string.IsNullOrWhiteSpace(filePathOrExt) &&
78 File.Exists(filePathOrExt)
79 ? filePathOrExt
80 : null;
81
82 var ext = Path.GetExtension(filePathOrExt ?? string.Empty);
83 SourceExtension = string.IsNullOrEmpty(ext) ? null : NormalizeExtension(ext);
84 OriginalBytes = rawBytes;
85
86 Volume = volume;
87 Pan = pan;
88 PlaybackSpeed = playbackSpeed;
89 IsLooping = false;
90
91 _playback.PlaybackCompleted += OnPlaybackCompleted;
92 }
93
95 [JsonProperty]
96 public string Key { get; private set; }
97
99 [JsonIgnore]
100 public byte[]? OriginalBytes { get; private set; }
101
105 [JsonProperty]
106 public string? SourceFilePath { get; private set; }
107
109 [JsonProperty]
110 public AssetsFileIdentifier? AssetIdentifier { get; private set; }
111
113 [JsonProperty]
114 public string? SourceExtension { get; private set; }
115
117 [JsonProperty]
118 public string? SourceUri { get; private set; }
119
123 [JsonIgnore]
124 public string? TempFilePath => _playback?.TemporaryFilePath;
125
129 [JsonIgnore]
130 public bool IsPaused => State == AudioPlaybackState.Paused;
131
135 [JsonIgnore]
136 public bool IsPlaying => State == AudioPlaybackState.Playing;
137
141 [JsonIgnore]
142 public AudioPlaybackState State => _playback?.State ?? AudioPlaybackState.Stopped;
143
148 [JsonIgnore]
149 public TimeSpan CurrentTime
150 {
151 get => _playback?.CurrentTime ?? TimeSpan.Zero;
152 set => Seek(value);
153 }
154
158 [JsonIgnore]
159 public TimeSpan Duration => _playback?.Duration ?? TimeSpan.Zero;
160
162 public bool IsLooping
163 {
164 get => _isLooping;
165 set
166 {
167 _isLooping = value;
168
169 if (_playback is not null)
170 _playback.IsLooping = value;
171 }
172 }
173
175 public float Volume
176 {
177 get => _volume;
178 set
179 {
180 if (float.IsNaN(value))
181 throw new ArgumentOutOfRangeException(nameof(value));
182
183 _volume = Math.Clamp(value, 0f, 1f);
184
185 if (_playback is not null)
186 _playback.Volume = _volume;
187 }
188 }
189
191 public float Pan
192 {
193 get => _pan;
194 set
195 {
196 if (float.IsNaN(value))
197 throw new ArgumentOutOfRangeException(nameof(value));
198
199 _pan = Math.Clamp(value, -1f, 1f);
200
201 if (_playback is not null)
202 _playback.Pan = _pan;
203 }
204 }
205
209 public float PlaybackSpeed
210 {
211 get => _playbackSpeed;
212 set
213 {
214 if (float.IsNaN(value))
215 throw new ArgumentOutOfRangeException(nameof(value));
216
217 _playbackSpeed = Math.Clamp(value, MinimumPlaybackSpeed, MaximumPlaybackSpeed);
218
219 if (_playback is not null)
220 _playback.PlaybackSpeed = _playbackSpeed;
221 }
222 }
223
228 public void Play(bool fromStart = true) => Playback.Play(fromStart);
229
233 public void Pause() => Playback.Pause();
234
238 public void Resume() => Playback.Resume();
239
244 public void Seek(TimeSpan position) => Playback.Seek(position);
245
249 public void Stop() => Playback.Stop();
250
253 internal void SetSourceFilePath(string filePath)
254 {
255 SourceFilePath = filePath;
256 AssetIdentifier = null;
257 SourceUri = null;
258 }
259
260 internal void SetSourceUri(string uri)
261 {
262 SourceUri = uri;
263 SourceFilePath = null;
264
265 SourceExtension = NormalizeExtension(
266 Path.GetExtension(
267 new Uri(uri, UriKind.RelativeOrAbsolute).IsAbsoluteUri
268 ? new Uri(uri).AbsolutePath
269 : uri));
270 }
271
272 internal void SetAssetIdentifier(AssetsFileIdentifier identifier) => AssetIdentifier = identifier;
273
274 internal void CopySourceFrom(AudioResource original)
275 {
276 SourceFilePath = original.SourceFilePath;
277 AssetIdentifier = original.AssetIdentifier;
278 }
279
284 internal void ReloadIntoManager(bool forceReload = false)
285 {
286 if (string.IsNullOrWhiteSpace(Key))
287 throw new InvalidOperationException("AudioResource has no Key and cannot be reloaded.");
288
289 var manager = AudioResourceManager.Instance;
290
291 if (!forceReload && manager.TryGet(Key, out var existing) && existing is not null)
292 {
293 existing.Volume = Volume;
294 existing.Pan = Pan;
295 existing.PlaybackSpeed = PlaybackSpeed;
296 existing.IsLooping = IsLooping;
297 return;
298 }
299
300 if (forceReload && manager.Contains(Key))
301 manager.Unload(Key);
302
303 AudioResource loaded;
304
305 if (AssetIdentifier is not null)
306 {
307 using var stream = AssetIdentifier.Data;
308
309 if (stream is null)
310 throw new InvalidOperationException($"Missing asset data for {Key}.");
311
312 loaded = manager.LoadFromStream(
313 Key,
314 stream,
315 SourceExtension ?? ".wav",
316 Volume,
317 Pan,
319
320 loaded.SetAssetIdentifier(AssetIdentifier);
321 }
322 else if (!string.IsNullOrWhiteSpace(SourceFilePath))
323 {
324 loaded = manager.LoadFromFile(
325 Key,
328 Volume,
329 Pan,
331 }
332 else if (!string.IsNullOrWhiteSpace(SourceUri))
333 {
334 loaded = manager.LoadFromUri(
335 Key,
336 SourceUri,
337 Volume,
338 Pan,
340 }
341 else
342 {
343 throw new InvalidOperationException($"AudioResource '{Key}' has no persisted source.");
344 }
345
346 loaded.IsLooping = IsLooping;
347 }
348
349 private IAudioPlaybackHandle Playback
350 {
351 get
352 {
353 ObjectDisposedException.ThrowIf(_disposed, this);
354
355 return _playback ?? throw new InvalidOperationException(
356 $"AudioResource '{Key}' is not attached to an audio backend. Configure an audio backend before loading or restoring audio.");
357 }
358 }
359
360 private async void OnPlaybackCompleted(object? sender, EventArgs e)
361 {
362 try
363 {
364 if (PlaybackCompletedAsync is not null)
365 await PlaybackCompletedAsync().ConfigureAwait(false);
366 }
367 catch (Exception ex)
368 {
369 Engine.Logger.LogError(ex, "PlaybackCompletedAsync threw an exception for audio resource: {Key}", Key);
370 }
371 finally
372 {
373 PlaybackCompleted?.Invoke(this, EventArgs.Empty);
374 }
375 }
376
377 private static string? NormalizeExtension(string? extension)
378 {
379 if (string.IsNullOrWhiteSpace(extension))
380 return null;
381
382 return extension.StartsWith('.')
383 ? extension.ToLowerInvariant()
384 : "." + extension.ToLowerInvariant();
385 }
386
391 public void Dispose()
392 {
393 if (_disposed)
394 return;
395
396 if (_playback is not null)
397 {
398 _playback.PlaybackCompleted -= OnPlaybackCompleted;
399 _playback.Dispose();
400 _playback = null;
401 }
402
403 _disposed = true;
404 Disposed?.Invoke(this, EventArgs.Empty);
405 GC.SuppressFinalize(this);
406 }
407}
Represents an identifier for a specific asset within a file, including its type and name.
Represents an audio resource that can be played, paused, resumed, sought, and disposed....
float Pan
Gets or sets stereo pan from -1.0 (left) through 1.0 (right).
string Key
Gets the unique key associated with this audio resource.
EventHandler? Disposed
Event raised when the resource is disposed.
float Volume
Gets or sets output volume in the range 0.0 through 1.0.
bool IsLooping
Gets or sets whether playback loops continuously.
TimeSpan CurrentTime
Gets or sets the current playback position within the resource. Setting this property seeks to the sp...
string? SourceExtension
Normalized file extension used by the configured backend.
float PlaybackSpeed
Gets or sets playback speed. 1.0 is normal speed; supported values are clamped to 0....
bool IsPlaying
Gets a value indicating whether playback is currently active.
string? TempFilePath
Gets the temporary file path used by a backend that requires file-based decoding, if any.
const float MaximumPlaybackSpeed
Maximum allowed playback speed multiplier. Values above this are clamped.
void Dispose()
Disposes the audio resource and releases any underlying playback handle and temporary files....
TimeSpan Duration
Gets the total duration of the resource, or TimeSpan.Zero when unknown.
byte?[] OriginalBytes
Gets the original byte array of the audio data, if available.
bool IsPaused
Gets a value indicating whether playback is currently paused.
void Stop()
Stops playback immediately.
void Pause()
Pauses playback if currently playing.
EventHandler? PlaybackCompleted
Event raised when non-looping playback reaches the end of the resource.
const float MinimumPlaybackSpeed
Minimum allowed playback speed multiplier. Values below this are clamped.
Func< Task >? PlaybackCompletedAsync
Optional asynchronous callback invoked when non-looping playback completes.
string? SourceFilePath
Original file path when the sound was loaded from disk. Null when loaded from an AssetsFile or URI.
AudioPlaybackState State
Gets the current high-level playback state of the resource.
void Play(bool fromStart=true)
Starts playback of the resource.
AssetsFileIdentifier? AssetIdentifier
Asset identifier when the sound was loaded from an AssetsFile.
string? SourceUri
Source URI when the resource was loaded by URI, primarily for browser playback.
void Seek(TimeSpan position)
Seeks to the specified playback position.
void Resume()
Resumes playback if currently paused.
Backend-provided playback handle used by AudioResource. Implements IDisposable to allow releasing any...
AudioPlaybackState
Describes the current playback state of an audio resource without exposing backend-specific playback ...