3using Microsoft.Extensions.Logging;
12[JsonObject(IsReference =
true)]
13public class AudioResource : IDisposable
17 internal DefinitionProvenance? DefinitionProvenance {
get;
set; }
31 private bool _disposed;
33 [JsonProperty]
private float _volume = 1.0f;
35 [JsonProperty]
private float _pan;
37 [JsonProperty]
private float _playbackSpeed = 1.0f;
39 [JsonProperty]
private bool _isLooping;
57 private AudioResource()
67 float playbackSpeed = 1.0f,
68 string? filePathOrExt =
null,
69 byte[]? rawBytes =
null,
73 _playback = playback ??
throw new ArgumentNullException(nameof(playback));
77 SourceFilePath = assetIdentifier is
null && !
string.IsNullOrWhiteSpace(filePathOrExt) &&
78 File.Exists(filePathOrExt)
82 var ext = Path.GetExtension(filePathOrExt ??
string.Empty);
83 SourceExtension =
string.IsNullOrEmpty(ext) ? null : NormalizeExtension(ext);
91 _playback.PlaybackCompleted += OnPlaybackCompleted;
96 public string Key {
get;
private set; }
151 get => _playback?.CurrentTime ?? TimeSpan.Zero;
159 public TimeSpan
Duration => _playback?.Duration ?? TimeSpan.Zero;
169 if (_playback is not
null)
170 _playback.IsLooping = value;
180 if (
float.IsNaN(value))
181 throw new ArgumentOutOfRangeException(nameof(value));
183 _volume = Math.Clamp(value, 0f, 1f);
185 if (_playback is not
null)
186 _playback.Volume = _volume;
196 if (
float.IsNaN(value))
197 throw new ArgumentOutOfRangeException(nameof(value));
199 _pan = Math.Clamp(value, -1f, 1f);
201 if (_playback is not
null)
202 _playback.Pan = _pan;
211 get => _playbackSpeed;
214 if (
float.IsNaN(value))
215 throw new ArgumentOutOfRangeException(nameof(value));
219 if (_playback is not
null)
220 _playback.PlaybackSpeed = _playbackSpeed;
228 public void Play(
bool fromStart =
true) => Playback.Play(fromStart);
233 public void Pause() => Playback.Pause();
238 public void Resume() => Playback.Resume();
244 public void Seek(TimeSpan position) => Playback.Seek(position);
249 public void Stop() => Playback.Stop();
253 internal void SetSourceFilePath(
string filePath)
260 internal void SetSourceUri(
string uri)
267 new Uri(uri, UriKind.RelativeOrAbsolute).IsAbsoluteUri
268 ?
new Uri(uri).AbsolutePath
274 internal void CopySourceFrom(AudioResource original)
284 internal void ReloadIntoManager(
bool forceReload =
false)
286 if (
string.IsNullOrWhiteSpace(
Key))
287 throw new InvalidOperationException(
"AudioResource has no Key and cannot be reloaded.");
289 var manager = AudioResourceManager.Instance;
291 if (!forceReload && manager.TryGet(
Key, out var existing) && existing is not
null)
300 if (forceReload && manager.Contains(
Key))
303 AudioResource loaded;
310 throw new InvalidOperationException($
"Missing asset data for {Key}.");
312 loaded = manager.LoadFromStream(
324 loaded = manager.LoadFromFile(
332 else if (!
string.IsNullOrWhiteSpace(
SourceUri))
334 loaded = manager.LoadFromUri(
343 throw new InvalidOperationException($
"AudioResource '{Key}' has no persisted source.");
349 private IAudioPlaybackHandle Playback
353 ObjectDisposedException.ThrowIf(_disposed,
this);
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.");
360 private async
void OnPlaybackCompleted(
object? sender, EventArgs e)
369 Engine.Logger.LogError(ex,
"PlaybackCompletedAsync threw an exception for audio resource: {Key}",
Key);
377 private static string? NormalizeExtension(
string? extension)
379 if (
string.IsNullOrWhiteSpace(extension))
382 return extension.StartsWith(
'.')
383 ? extension.ToLowerInvariant()
384 :
"." + extension.ToLowerInvariant();
396 if (_playback is not
null)
398 _playback.PlaybackCompleted -= OnPlaybackCompleted;
404 Disposed?.Invoke(
this, EventArgs.Empty);
405 GC.SuppressFinalize(
this);
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 ...