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(
string key,
string uri,
float volume,
float pan,
float playbackSpeed)
26 _key = Guid.NewGuid().ToString(
"N");
27 _volume = Math.Clamp(volume, 0f, 1f);
28 _pan = Math.Clamp(pan, -1f, 1f);
29 _playbackSpeed = Math.Clamp(playbackSpeed, AudioResource.MinimumPlaybackSpeed, AudioResource.MaximumPlaybackSpeed);
30 BrowserAudioInterop.Load(_key, uri, loop:
false, _volume, _pan, _playbackSpeed, OnEnded);
42 public BrowserAudioPlaybackHandle(
string key,
byte[] data,
string mimeType,
float volume,
float pan,
float playbackSpeed)
44 ArgumentNullException.ThrowIfNull(data);
48 _key = Guid.NewGuid().ToString(
"N");
49 _volume = Math.Clamp(volume, 0f, 1f);
50 _pan = Math.Clamp(pan, -1f, 1f);
51 _playbackSpeed = Math.Clamp(playbackSpeed, AudioResource.MinimumPlaybackSpeed, AudioResource.MaximumPlaybackSpeed);
52 BrowserAudioInterop.LoadBytes(
54 Convert.ToBase64String(data),
64 public event EventHandler? PlaybackCompleted;
66 private void OnEnded()
68 if (!_disposed && !_isLooping)
69 PlaybackCompleted?.Invoke(
this, EventArgs.Empty);
77 _ => AudioPlaybackState.Stopped
81 public TimeSpan CurrentTime => TimeSpan.FromSeconds(Math.Max(0d, BrowserAudioInterop.GetCurrentTime(_key)));
84 public TimeSpan Duration => TimeSpan.FromSeconds(Math.Max(0d, BrowserAudioInterop.GetDuration(_key)));
87 public string? TemporaryFilePath =>
null;
96 BrowserAudioInterop.SetLoop(_key, value);
106 _volume = Math.Clamp(value, 0f, 1f);
107 BrowserAudioInterop.SetVolume(_key, _volume);
117 _pan = Math.Clamp(value, -1f, 1f);
118 BrowserAudioInterop.SetPan(_key, _pan);
123 public float PlaybackSpeed
125 get => _playbackSpeed;
128 _playbackSpeed = Math.Clamp(value, AudioResource.MinimumPlaybackSpeed, AudioResource.MaximumPlaybackSpeed);
129 BrowserAudioInterop.SetPlaybackSpeed(_key, _playbackSpeed);
134 public void Play(
bool fromStart =
true)
137 BrowserAudioInterop.Play(_key, fromStart);
144 BrowserAudioInterop.Pause(_key);
152 BrowserAudioInterop.Play(_key, fromStart:
false);
156 public void Seek(TimeSpan position)
159 var seconds = Math.Max(0d, position.TotalSeconds);
160 BrowserAudioInterop.SetCurrentTime(_key, seconds);
167 BrowserAudioInterop.Stop(_key);
170 private void ThrowIfDisposed()
172 ObjectDisposedException.ThrowIf(_disposed,
this);
178 public void Dispose()
183 BrowserAudioInterop.Unload(_key);
184 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 ...