DeepWorks Studios Blazor Component Library

Demo user Administrator ยท Blazor Server Library 20261206222504-6e8ff32.dirty

DwsAudio

An audio player with its own themed controls built from DWS components: play/pause, stop, previous/next, a seek bar with the time, mute and volume, playback speed, repeat and download, plus the track's metadata, an optional visualizer and a playlist. It plays files by address, base64 data and streams, and can run headless under full control from code.

API Reference

Basic player

Source plays a file by address; Title and Artist are shown above the controls (without a Title the file name is shown). The browser's own controls are replaced by DWS buttons and sliders: drag the position bar to seek, the speed button cycles through PlaybackRates, the repeat button through the loop modes.

Sample tracksamplelib.com
Show Code
Audio.razor
<DwsAudio Name="AudioDemo_Basic" Source="https://samplelib.com/mp3/sample-9s.mp3" Title="Sample track" Artist="samplelib.com" />

Metadata

Title, Artist, Album and ArtworkUrl (or the same properties of a DwsAudioTrack) are shown with the length the file reports. The playing track also appears in the operating system's media controls (EnableMediaSession).

Evening sketchDWS Demo Band · Component Sessions
Show Code
Audio.razor
<DwsAudio Name="AudioDemo_Metadata" Source="https://samplelib.com/mp3/sample-6s.mp3"
          Title="Evening sketch" Artist="DWS Demo Band" Album="Component Sessions" ArtworkUrl="images/blackhole_black.png" />

Base64 source

Base64Source plays audio that has no address, e.g. generated or read from a database (AudioType names its type). Base64 travels inside the page, so keep it for short clips.

Generated melody (Base64Source)
Show Code
Audio.razor
<DwsAudio Name="AudioDemo_Base64" Base64Source="@_melodyBase64" AudioType="wav" Title="Generated melody (Base64Source)" />
Audio.razor.cs
private static readonly byte[] MelodyWav = File.ReadAllBytes("wwwroot/audio/melody.wav"); // generated, read from a database, ...

private string _melodyBase64 = string.Empty;

protected override void OnInitialized()
{
    _melodyBase64 = Convert.ToBase64String(MelodyWav);
}

Stream source

DwsAudioTrack.FromStreamAsync (and DwsAudioTrack.FromBytes for a byte array) turns a stream into a base64 track that a playlist plays.

Generated chime (from a stream)
Show Code
Audio.razor
<DwsAudio Name="AudioDemo_Stream" Playlist="@_streamTracks" ShowDownloadButton="true" />
Audio.razor.cs
private static readonly byte[] ChimeWav = File.ReadAllBytes("wwwroot/audio/chime.wav"); // any WAV/MP3/OGG bytes

private IReadOnlyList<DwsAudioTrack> _streamTracks = [];

protected override async Task OnInitializedAsync()
{
    // A stream read to its end and stored base64 encoded.
    using MemoryStream stream = new(ChimeWav);
    _streamTracks = [await DwsAudioTrack.FromStreamAsync(stream, "audio/wav", "Generated chime (from a stream)")];
}

Interface-Description

Name Typ Default Description
IsPlaying bool false Whether the audio is playing (or about to, while it buffers).
CurrentTime TimeSpan TimeSpan.Zero The playback position.
Duration TimeSpan? null Length of the current track; null while unknown or for a live stream.
CurrentTrack DwsAudioTrack? null The loaded track.
Tracks IReadOnlyList<DwsAudioTrack> [] The tracks the player plays: the playlist, or one track built from Source.
LastError DwsAudioErrorEventArgs? null The error that stopped the current track; null while it loads and plays fine.
CurrentChapters IReadOnlyList<DwsMediaChapter> [] The chapters of the current track in playing order.
CurrentChapter DwsMediaChapter? null The chapter being played; null before the first one or without chapters.
IsVisualizerUnavailable bool false Whether the visualizer cannot read the current source.
Name Typ Parameters Description
PlayAsync Task Starts or resumes playback; after an error it loads the track again first.
PauseAsync Task Pauses playback.
TogglePlayAsync Task Pauses while playing, plays while paused.
StopAsync Task Stops playback and returns to the start of the track.
SeekAsync Task TimeSpan position Jumps to a position, clamped to the track.
SeekToChapterAsync Task int index Jumps to the start of a chapter of the current track; an index outside the list does nothing.
SkipAsync Task TimeSpan offset Jumps forwards (positive offset) or backwards (negative) from the current position.
SetVolumeAsync Task double volume Sets the volume (0-1) and raises VolumeChanged.
SetMutedAsync Task bool muted Mutes or unmutes and raises MutedChanged.
ToggleMuteAsync Task Mutes when the sound is on, unmutes when it is muted.
SetPlaybackRateAsync Task double rate Sets the playback speed (0.25-4) and raises PlaybackRateChanged.
SetLoopModeAsync Task DwsAudioLoopMode loopMode Sets the loop mode and raises LoopModeChanged.
NextAsync Task Loads the next track (keeps playing if it was). After the last track it goes to the first only in LoopMode.Playlist.
PreviousAsync Task Loads the previous track. On the first track: the last one in LoopMode.Playlist, otherwise the track starts again.
PlayTrackAsync Task int index Loads the track at the index and plays it; the current track starts again.
DownloadAsync Task Downloads the current track.
ReloadAsync Task Loads the current track again, e.g. after a network error.
Name Typ Default Description
Source string? null Address of the audio file: absolute, relative to the page, or a data: / blob: address. Ignored while Playlist has tracks.
Base64Source string? null The audio file itself, base64 encoded, played when Source is empty: plain base64 of type AudioType or a complete data: address. Keep it for short clips; it travels inside the page.
AudioType string "mpeg" Audio type of Base64Source: a MIME sub-type (mpeg, ogg, wav) or a complete MIME type. Also picks the extension of a downloaded base64 file.
Title string? null Title of Source, shown above the controls and in the operating system's media controls. Left empty, the file name is shown.
Artist string? null Artist of Source, shown under the title.
Album string? null Album of Source, shown under the title.
ArtworkUrl string? null Address of a cover image for Source.
DownloadFileName string? null File name the download button saves Source under. Left empty, it comes from the address.
Playlist IReadOnlyList<DwsAudioTrack>? null The tracks to play, in order. With more than one track the player shows previous/next buttons and the track list. When set and not empty it replaces Source and the other single-file parameters.
CurrentTrackIndex int 0 Index of the loaded track, two-way bindable (CurrentTrackIndexChanged). An index outside the playlist is corrected to the nearest track and reported back.
AutoAdvance bool true Starts the next track of the playlist when one ends.
ReadMetadataTags bool false Reads title, artist, album and cover from the file's ID3 tag (MP3) where the track has no values of its own. One extra request for the start of the file; same-origin, base64 or CORS-enabled files only.
CrossOrigin DwsAudioCrossOrigin DwsAudioCrossOrigin.None CORS mode for cross-origin files. Only for servers that send CORS headers (other servers' files then fail to load); lets the visualizer and tag reading work for them.
AutoPlay bool false Starts playing as soon as a track is loaded. A browser that blocks it raises OnError with PlaybackBlocked and the player stays paused.
Preload DwsAudioPreload DwsAudioPreload.Metadata How much of a track the browser loads before playback: None, Metadata (length) or Auto.
Volume double 1 Volume from 0 to 1, two-way bindable (VolumeChanged). Values outside the range are clamped.
Muted bool false Mutes the sound without changing Volume, two-way bindable (MutedChanged).
PlaybackRate double 1 Playback speed (1 = normal), two-way bindable (PlaybackRateChanged). Clamped to 0.25-4.
PlaybackRates IReadOnlyList<double>? 0.5, 0.75, 1, 1.25, 1.5, 2 The speeds the speed button cycles through. Values outside 0.25-4 are skipped.
LoopMode DwsAudioLoopMode DwsAudioLoopMode.None What happens when a track ends: None, Track (repeat the track) or Playlist (start the playlist again after the last track), two-way bindable (LoopModeChanged).
EnableMediaSession bool true Shows the playing track in the operating system's media controls and lets media keys play, pause, seek and skip.
Headless bool false Renders no UI, only the invisible audio element; control it with the public methods and events.
ShowBackground bool true Draws the player on a themed panel (surface, border, rounded corners).
ShowControls bool true Shows the row of playback controls. Without it the metadata, seek bar and playlist remain.
ShowStopButton bool true Shows the stop button.
ShowSkipButtons bool? null Shows the previous/next buttons. Left null, they appear for playlists with more than one track.
ShowMuteButton bool true Shows the mute/unmute button.
ShowVolumeSlider bool true Shows the volume slider (hidden automatically when the player is narrower than 360px).
ShowPlaybackRate bool true Shows the playback speed button.
ShowLoopButton bool true Shows the repeat button.
ShowDownloadButton bool false Shows a button that downloads the current track. Cross-origin files without CORS open in a new tab instead.
Haptic DwsHapticFeedback Selection Touch feedback (when haptics are switched on) of a tap on play/pause, stop, previous/next, mute, speed, repeat, a chapter or a playlist entry. None switches it off; nothing plays while the controls are disabled.
ShowProgress bool true Shows the playback position as a bar: a seek slider while Seekable, otherwise a progress bar with the buffered part.
Seekable bool true Lets the user drag the position bar. Live streams are never seekable.
ShowTime bool true Shows the current time and the length of the track.
ShowMetadata bool true Shows cover, title, artist and album of the current track.
ShowPlaylist bool true Shows the track list for playlists with more than one track.
Visualizer DwsAudioVisualizer DwsAudioVisualizer.None Draws the sound while it plays: Bars (frequency spectrum) or Waveform. Needs a same-origin, base64 or CORS-enabled source; for others it stays flat.
VisualizerHeight int? null Height of the visualizer in px (default 64px).
ShowVisualizerNotice bool true Says below the visualizer when it cannot read the current source (cross-origin without CORS headers or without CrossOrigin). The audio plays either way.
Chapters IReadOnlyList<DwsMediaChapter>? null Named positions of the single Source (start + title). In a playlist each DwsAudioTrack has its own Chapters, which win.
ShowChapters bool true Lists the chapters of the current track below the controls; the one being played is marked, a click jumps to it.
ShowChapterMarks bool true Marks every chapter start of the current track on the seek bar (DwsSlider.Marks); the title is the tooltip, a click jumps there. Nothing is drawn without chapters, before the length is known or for a live stream.
Color DwsColor DwsColor.Primary Accent of the play button, bars, visualizer and current track, resolved through the theme's CSS variables.
BackgroundColor DwsColor DwsColor.Undefined Tints the panel with a theme color (a light wash over the surface, so text keeps its contrast). Undefined: the theme's surface color.
Width int? null Width in px. Left null, the player fills its container.
MaxWidth int? null Maximum width in px.
Name Typ Description
CurrentTrackIndexChanged EventCallback<int> Raised when another track is loaded, or when CurrentTrackIndex had to be corrected.
VolumeChanged EventCallback<double> Raised when the volume changes (slider, SetVolumeAsync).
MutedChanged EventCallback<bool> Raised when the sound is muted or unmuted.
PlaybackRateChanged EventCallback<double> Raised when the playback speed changes.
LoopModeChanged EventCallback<DwsAudioLoopMode> Raised when the loop mode changes.
OnPlay EventCallback<DwsAudioTrackEventArgs> Raised when playback starts or resumes, with the track, its index, position and length.
OnPause EventCallback<DwsAudioTrackEventArgs> Raised when playback is paused or stopped - not when a track simply ends.
OnEnded EventCallback<DwsAudioTrackEventArgs> Raised when a track played to its end, before the player moves on. Not raised while a track repeats itself.
OnTrackChanged EventCallback<DwsAudioTrackEventArgs> Raised when another track of the playlist is loaded.
OnLoaded EventCallback<DwsAudioTrackEventArgs> Raised once per track when its metadata (length) has loaded.
OnTimeUpdate EventCallback<TimeSpan> Raised when the playback position changes, at most four times a second.
OnError EventCallback<DwsAudioErrorEventArgs> Raised when a track can not be loaded or played, with the reason (Network, Decode, SourceNotSupported, PlaybackBlocked, ...).
OnChapterChanged EventCallback<DwsMediaChapter?> Raised when playback enters another chapter (by playing on, seeking or the list); null before the first chapter.
OnVisualizerUnavailable EventCallback<DwsAudioTrackEventArgs> Raised once per source when the visualizer cannot read it.
Name Typ Default Description
Element ElementReference The associated web component. May be null if accessed before the component is rendered.
ComponentGuid Guid Unique identifier for the component.
TypeString string The name of the component type, obtained from reflection.
Authorized_RegisterEnabled bool false Indicates whether this component is enabled through a permission registry.
Authorized_RegisterSelected bool false Indicates whether this component is selected in permission selection mode.
GetInitializedState bool false Returns whether the component is initialized.
GetRenderModeState DwsRenderMode Returns the current render mode.
GetComponentState DwsComponentStateType Returns the current component state.
GetIsInteractiveState bool false Returns whether the component is interactive.
GetIsPrerenderingState bool false Returns whether the component is prerendering.
GetComponentLoadingState bool false Returns whether the component is loading.
IsFormBusy bool false Whether the DwsForm (or DwsFormBusyRegion) around the component is locked because its submit handler is running. The state itself is the cascaded FormBusyState (IDwsFormBusyState).
Name Typ Parameters Description
DebugInfo void Logs debug information about the component.
UpdateState void Updates the component's state and triggers StateHasChanged.
UpdateStateAsync Task Asynchronously updates the component's state and triggers StateHasChanged.
Dispose void Disposes the component and releases resources.
FocusAsync ValueTask bool containedInScrollableList Sets focus to the component's element.
Name Typ Default Description
Name string Required unique identifier for the component within its container.
Visible bool true Determines if the component is visible in the UI.
Disabled bool false Disables the form control, ensuring it doesn't participate in form submission.
ComponentNameSpace string The namespace for permission-based access control.
PermissionKey string? null A stable key that takes the place of Name in the generated permission namespace (Page.PermissionKey): the stored permission survives a rename, and components that share a key share one permission entry. Null: keyed by Name. Read once, when the component registers; an explicit ComponentNameSpace wins.
Class string Optional CSS class names.
Style string Optional in-line styles.
Tag object An optional user-defined object to store any additional data with the component.
BackReference DwsReference A reference to the enclosing component.
ID string The HTML ID attribute for the component.
AdditionalAttributes Dictionary<string, object> Additional HTML attributes for the component's root element.
IgnorePermissionChecks bool false Bypasses all permission checks for this component.
IgnorePermissionSelection bool false Ignore permission selection mode for this component.
IgnoreFormBusy bool false Takes the component out of the submit lock of the DwsForm (or DwsFormBusyRegion) around it: IsFormBusy stays false for it.
Name Typ Description
OnInitializedCallbackStarted EventCallback Callback when OnInitialized starts.
OnInitializedCallback EventCallback Callback during OnInitialized.
OnInitializedCallbackCompleted EventCallback Callback when OnInitialized completes.
OnInitializedAsyncCallbackStarted EventCallback Callback when OnInitializedAsync starts.
OnInitializedAsyncCallback EventCallback Callback during OnInitializedAsync.
OnInitializedAsyncCallbackCompleted EventCallback Callback when OnInitializedAsync completes.
OnIsComponentLoadingChanged EventCallback<bool> Callback when IsComponentLoading changes.
OnCurrentRenderModeChanged EventCallback<DwsRenderMode> Callback when CurrentRenderMode changes.
OnComponentStateChanged EventCallback<DwsComponentStateType> Callback when ComponentState changes.
An error has occurred. This app may no longer respond until reloaded.