1using System.Runtime.Versioning;
5[SupportedOSPlatform(
"browser")]
6internal sealed class BrowserAudioPlaybackHandle : IAudioPlaybackHandle
8 private readonly
string _key;
9 private bool _disposed;
10 private bool _isLooping;
11 private float _volume;
13 private float _playbackSpeed;
23 public BrowserAudioPlaybackHandle(
31 _key = Guid.NewGuid().ToString(
"N");
32 _volume = Math.Clamp(volume, 0f, 1f);
33 _pan = Math.Clamp(pan, -1f, 1f);
35 _playbackSpeed = Math.Clamp(
37 AudioResource.MinimumPlaybackSpeed,
38 AudioResource.MaximumPlaybackSpeed);
40 BrowserAudioInterop.Load(
59 public BrowserAudioPlaybackHandle(
67 ArgumentNullException.ThrowIfNull(data);
71 _key = Guid.NewGuid().ToString(
"N");
72 _volume = Math.Clamp(volume, 0f, 1f);
73 _pan = Math.Clamp(pan, -1f, 1f);
75 _playbackSpeed = Math.Clamp(
77 AudioResource.MinimumPlaybackSpeed,
78 AudioResource.MaximumPlaybackSpeed);
80 BrowserAudioInterop.LoadBytes(
82 Convert.ToBase64String(data),
92 public event EventHandler? PlaybackCompleted;
94 private void OnEnded()
96 if (!_disposed && !_isLooping)
97 PlaybackCompleted?.Invoke(
this, EventArgs.Empty);
105 _ => AudioPlaybackState.Stopped
109 public TimeSpan CurrentTime => TimeSpan.FromSeconds(Math.Max(0d, BrowserAudioInterop.GetCurrentTime(_key)));
112 public TimeSpan Duration => TimeSpan.FromSeconds(Math.Max(0d, BrowserAudioInterop.GetDuration(_key)));
115 public string? TemporaryFilePath =>
null;
118 public bool IsLooping
124 BrowserAudioInterop.SetLoop(_key, value);
134 _volume = Math.Clamp(value, 0f, 1f);
135 BrowserAudioInterop.SetVolume(_key, _volume);
145 _pan = Math.Clamp(value, -1f, 1f);
146 BrowserAudioInterop.SetPan(_key, _pan);
151 public float PlaybackSpeed
153 get => _playbackSpeed;
156 _playbackSpeed = Math.Clamp(value, AudioResource.MinimumPlaybackSpeed, AudioResource.MaximumPlaybackSpeed);
157 BrowserAudioInterop.SetPlaybackSpeed(_key, _playbackSpeed);
162 public void Play(
bool fromStart =
true)
165 BrowserAudioInterop.Play(_key, fromStart);
172 BrowserAudioInterop.Pause(_key);
181 BrowserAudioInterop.Play(_key, fromStart:
false);
185 public void Seek(TimeSpan position)
188 var seconds = Math.Max(0d, position.TotalSeconds);
189 BrowserAudioInterop.SetCurrentTime(_key, seconds);
196 BrowserAudioInterop.Stop(_key);
199 private void ThrowIfDisposed()
201 ObjectDisposedException.ThrowIf(_disposed,
this);
207 public void Dispose()
212 BrowserAudioInterop.Unload(_key);
213 PlaybackCompleted =
null;
void Resume()
Resume playback after a pause.
void Pause()
Pause playback. Calling Resume should continue from the paused position.
void Stop()
Stop playback and reset the current position to the start.
AudioPlaybackState
Describes the current playback state of an audio resource without exposing backend-specific playback ...