DeepWorks Studios Blazor Component Library

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

DwsVideo

A themed video player for one video or a playlist, from a URL or base64 data. It brings its own controls - play / pause, stop, a playback slider with the time, mute and volume, speed, loop, subtitles, picture-in-picture, fullscreen and download - each of which can be switched off, down to a headless player driven only through its public methods.

API Reference

Basic

Source plays a URL. Title, Artist and Album are shown under the player together with the duration once it is known; Poster is shown until playback starts. A click on the picture plays or pauses the video; the playback slider seeks when its thumb is released and moves the picture along while it is dragged. On the focused slider the arrow keys move by SeekStep (5 s), Page Up / Page Down by a tenth.

Show Code
Video.razor
<DwsVideo Name='VideoDemo_Basic'
          Source='video/local-sample.mp4'
          Poster='images/blackhole_black.png'
          Title='Local sample'
          Artist='DeepWorks Studios'
          Album='Demo clips'
          MaxWidth='720' />

Playlist

Playlist takes a list of DwsVideoItem, each with its own source, metadata, poster and tracks. The playlist under the player and the previous / next buttons switch videos; AutoAdvance plays the next one when a video ends and LoopPlaylist starts over after the last. @bind-PlaylistIndex follows and sets the current video.

Show Code
Video.razor
<DwsSwitch Name='VideoDemo_Playlist_AutoAdvance' Label='AutoAdvance' @bind-Value='@_autoAdvance' />
<DwsSwitch Name='VideoDemo_Playlist_LoopPlaylist' Label='LoopPlaylist' @bind-Value='@_loopPlaylist' />

<DwsVideo Name='VideoDemo_Playlist'
          Playlist='@_playlist'
          @bind-PlaylistIndex='@_playlistIndex'
          AutoAdvance='@_autoAdvance'
          LoopPlaylist='@_loopPlaylist'
          CrossOrigin='DwsVideoCrossOrigin.Anonymous'
          MaxWidth='720' />
<p>PlaylistIndex: @_playlistIndex (@_playlist[_playlistIndex].Title)</p>
Video.razor.cs
private int _playlistIndex;
private bool _autoAdvance = true;
private bool _loopPlaylist;

private readonly IReadOnlyList<DwsVideoItem> _playlist =
[
    new DwsVideoItem { Source = "video/local-sample.mp4", Title = "Local sample", Artist = "DeepWorks Studios",
                       Album = "Demo clips", Poster = "images/blackhole_black.png" },
    new DwsVideoItem { Source = "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm", VideoType = "webm",
                       Title = "Flower", Artist = "MDN sample (CC0)", Album = "Nature" },
    new DwsVideoItem { Source = "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/friday.mp4",
                       Title = "Friday", Artist = "MDN sample (CC0)", Tracks = _fridayTracks },
];

Subtitles and captions

Tracks lists WebVTT files. With one subtitle or caption track the CC button turns it on and off; with more it opens a menu. Default marks the track shown first; @bind-CaptionTrackIndex follows and sets the choice (null: off). Here the English track comes from another origin, so CrossOrigin is Anonymous; the German one is a data: URL. A .vtt file served by your own app needs a text/vtt MIME mapping, which ASP.NET Core's static files middleware lacks.

Show Code
Video.razor
<DwsVideo Name='VideoDemo_Captions'
          Source='https://interactive-examples.mdn.mozilla.net/media/cc0-videos/friday.mp4'
          Title='Friday'
          Artist='MDN sample (CC0)'
          Tracks='@_fridayTracks'
          CrossOrigin='DwsVideoCrossOrigin.Anonymous'
          @bind-CaptionTrackIndex='@_captionTrackIndex'
          MaxWidth='720' />

<DwsButton Name='VideoDemo_Captions_Off' OnClick='() => _captionTrackIndex = null'>Off</DwsButton>
<DwsButton Name='VideoDemo_Captions_English' OnClick='() => _captionTrackIndex = 0'>English</DwsButton>
<DwsButton Name='VideoDemo_Captions_German' OnClick='() => _captionTrackIndex = 1'>Deutsch</DwsButton>
Video.razor.cs
private int? _captionTrackIndex = 0;

// A track can be a data: URL too. A .vtt file in wwwroot needs a MIME mapping first - ASP.NET Core's static files
// middleware does not know .vtt:
//     var types = new FileExtensionContentTypeProvider();
//     types.Mappings[".vtt"] = "text/vtt";
//     app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = types });
private const string FridayGermanVtt = """
    WEBVTT

    00:00:00.000 --> 00:00:00.999 line:80%
    Hildy!
    ...
    """;

private static readonly string FridayGermanTrack = "data:text/vtt;charset=utf-8," + Uri.EscapeDataString(FridayGermanVtt);

private static readonly IReadOnlyList<DwsVideoTrack> _fridayTracks =
[
    new DwsVideoTrack { Source = "https://mdn.github.io/shared-assets/misc/friday.vtt", Label = "English", Language = "en",
                        Kind = DwsVideoTrackKind.Captions, Default = true },
    new DwsVideoTrack { Source = FridayGermanTrack, Label = "Deutsch", Language = "de",
                        Kind = DwsVideoTrackKind.Subtitles },
];

No source

Without Source, Base64Source or Playlist the player shows a localised message that there is nothing to play.

No video to play.
Show Code
Video.razor
<DwsVideo Name='VideoDemo_Empty' Title='Nothing selected yet' />

Sizing and aspect ratio

Width / MaxWidth / Height take px; AspectRatio reserves the picture's shape before the video loads (16 / 9 by default) and letterboxes the video inside it. Here a square picture of at most 360px without the background panel.

Show Code
Video.razor
<DwsVideo Name='VideoDemo_Theme_Square'
          Source='https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm'
          VideoType='webm'
          Title='Square picture, no panel'
          Color='DwsColor.Warning'
          AspectRatio='1'
          MaxWidth='360'
          ShowBackgroundPanel='false' />

Autoplay

Autoplay starts the video as soon as it can. Browsers allow that only for a muted video until the user has interacted with the page, so Autoplay usually goes with Muted; a start the browser refuses raises OnError with PlaybackBlocked and leaves the play button showing. With Loop it becomes a silent background clip.

Show Code
Video.razor
<DwsVideo Name='VideoDemo_Autoplay'
          Source='https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm'
          VideoType='webm'
          Title='Muted autoplay, looping'
          Autoplay='true'
          Muted='true'
          Loop='true'
          MaxWidth='480'
          OnPlay='@(() => _autoplayStatus = "playing")'
          OnPause='@(() => _autoplayStatus = "paused")'
          OnEnded='@(() => _autoplayStatus = "ended")'
          OnError='@(error => _autoplayStatus = $"{error.Code}: {error.Message}")' />
<p>Status: @_autoplayStatus</p>

@code {
    private string _autoplayStatus = "waiting";
}

Interface-Description

Name Typ Default Description
IsPlaying / IsEnded / IsBuffering bool false Whether the video plays, played to its end, or waits for data.
CurrentTime double 0 Playback position in seconds.
Duration double? null Length in seconds; null while unknown and for a live stream.
CurrentVolume / IsMuted / CurrentPlaybackRate / IsLooping / CurrentCaptionTrackIndex double / bool / double / bool / int? - The audio, speed, loop and subtitle settings in effect, whoever changed them.
IsFullscreen / IsPictureInPicture bool false Whether the player fills the screen / plays in a picture-in-picture window.
IsFullscreenSupported / IsPictureInPictureSupported bool false Whether the browser allows fullscreen / picture-in-picture; known once the player is interactive.
Items / CurrentIndex / CurrentItem IReadOnlyList<DwsVideoItem> / int / DwsVideoItem? - The videos played (Playlist, or the single video), and the one shown.
Metadata DwsVideoMetadata - Title, artist, album, duration and picture size of the current video.
Error DwsVideoError? null The last error of the current video.
Name Typ Parameters Description
PlayAsync Task Starts or resumes playback; before the player is interactive, it starts once it is.
PauseAsync Task Pauses playback.
TogglePlayAsync Task Plays a paused video, pauses a playing one.
StopAsync Task Pauses, returns to the start and raises OnStop.
SeekAsync Task double seconds Jumps to a position in seconds (clamped to the length); needs the duration to be known.
SkipAsync Task double seconds Jumps forwards, or backwards for a negative value.
SetVolumeAsync Task double volume Sets the volume (0 to 1) and raises VolumeChanged; a volume above 0 also unmutes.
SetMutedAsync Task bool muted Turns the sound off or on and raises MutedChanged.
ToggleMuteAsync Task Mutes an audible video, unmutes a muted one.
SetPlaybackRateAsync Task double rate Sets the playback speed and raises PlaybackRateChanged.
SetLoopAsync Task bool loop Turns looping on or off and raises LoopChanged.
ToggleLoopAsync Task Toggles looping.
SetCaptionTrackAsync Task int? trackIndex Shows a subtitle / caption track of the current video, or none for null, and raises CaptionTrackIndexChanged.
ToggleCaptionsAsync Task Turns subtitles off, or on with the default (else the first) track.
EnterFullscreenAsync / ExitFullscreenAsync / ToggleFullscreenAsync Task Lets the whole player fill the screen, or leaves it. Browsers only allow entering in response to a user action.
EnterPictureInPictureAsync / ExitPictureInPictureAsync / TogglePictureInPictureAsync Task Plays the video in a picture-in-picture window where supported, or closes it. Browsers only allow entering in response to a user action.
NextAsync / PreviousAsync Task Shows the next / previous playlist video (wrapping with LoopPlaylist), playing it if the current one played.
PlayItemAsync Task int index Shows the playlist video at the index and plays it.
DownloadAsync Task Downloads the current video (a video from another origin without CORS opens in a new tab).
ReloadAsync Task Loads the current video again, e.g. after an error.
Name Typ Default Description
Source string? null URL of the video, or a complete data: URL. With Base64Source, Title, Artist, Album, Tracks and DownloadFileName it describes a single video; ignored while Playlist has items.
VideoAttributes IReadOnlyDictionary<string, object>? null Attributes for the <video> element itself (AdditionalAttributes go to the outer frame): title, controlslist, disablepictureinpicture, data- hooks. Applied last. Under static SSR a player with controls uses the browser's own controls.
Base64Source string? null The video as base64 data (a complete data: URL is accepted too), played as a data: URL of VideoType. Used when Source is empty.
VideoType string "mp4" MIME type of the video: its subtype ("mp4", "webm") or the full type ("video/mp4"). Needed for Base64Source; also names the extension of a download.
Title string? null Title shown in the metadata; also the player's accessible name.
Artist string? null Artist or author shown in the metadata.
Album string? null Album, series or collection shown in the metadata.
Poster string? null Image shown before playback starts; the fallback for playlist items without their own poster.
Tracks IReadOnlyList<DwsVideoTrack>? null Subtitle, caption, description, chapter or metadata tracks (WebVTT) of the single video: Source, Label, Language, Kind, Default.
DownloadFileName string? null File name offered by the download button. Unset: the title or the URL's file name, with the type's extension.
Playlist IReadOnlyList<DwsVideoItem>? null Videos played one after another, each with Source / Base64Source, VideoType, Title, Artist, Album, Poster, Tracks and DownloadFileName. DwsVideoItem.FromUrl / FromBase64 / FromBytes / FromStreamAsync create items. With items, the single-video parameters are ignored.
PlaylistIndex int 0 Index of the playlist video to show; two-way bindable (@bind-PlaylistIndex). Clamped to the playlist.
AutoAdvance bool true Plays the next playlist video when one ends.
LoopPlaylist bool false Starts the playlist over after its last video, and lets previous / next wrap around.
ShowPlaylist bool true Shows the playlist under the player when it has two or more videos.
Autoplay bool false Starts playing as soon as possible. Browsers allow it only for a muted video until the user interacted with the page; a refused start raises OnError (PlaybackBlocked) and leaves the play button showing.
Muted bool false Whether the sound is off; two-way bindable (@bind-Muted).
Volume double 1 Volume from 0 to 1 (clamped); two-way bindable (@bind-Volume).
PlaybackRate double 1 Playback speed (clamped to 0.0625..16); two-way bindable (@bind-PlaybackRate). Carries over to the next playlist video.
PlaybackRates IReadOnlyList<double>? 0.5, 0.75, 1, 1.25, 1.5, 2 Speeds offered by the speed menu.
Loop bool false Repeats the current video instead of ending; two-way bindable (@bind-Loop).
CaptionTrackIndex int? the Default track Index into the current video's tracks of the subtitle / caption track shown, null for none; two-way bindable (@bind-CaptionTrackIndex). A new playlist video keeps the language if it has it.
Preload DwsVideoPreload DwsVideoPreload.Metadata How much the browser loads before playback: None, Metadata or Auto.
PlaysInline bool true Plays inline on phones instead of switching to their fullscreen player.
CrossOrigin DwsVideoCrossOrigin DwsVideoCrossOrigin.None The crossorigin attribute. Tracks from another origin need Anonymous (and a server that sends CORS headers).
TimeUpdateInterval int 250 Least time in ms between two position updates from the browser (slider, time, OnTimeUpdate). Raise it to save round trips on Blazor Server. Clamped to 50..5000.
SeekStep double 5 Seconds the arrow keys move the playback slider. Page Up / Page Down move a tenth of the video, Home / End jump to its ends.
ShowControls bool true Shows the built-in control bar.
Controls DwsVideoControls DwsVideoControls.Default The controls of the bar (flags): Play, Stop, Progress, Time, Mute, Volume, Speed, Loop, Captions, PictureInPicture, Fullscreen, Download, Playlist. Default is all but Download; All adds it.
NativeControls bool false Uses the browser's own video controls instead of the built-in bar.
Headless bool false Renders only the video element - no controls, overlays, panel, metadata or playlist. Drive it through the public methods and events.
ClickToPlay bool true A click on the picture plays or pauses the video (with the built-in controls).
Haptic DwsHapticFeedback Selection Touch feedback (when haptics are switched on) of a tap on a player control, a speed or caption choice or a playlist entry (not Retry, Download or the speed menu button). None switches it off; nothing plays while disabled.
ShowBackgroundPanel bool true Draws the player on a background panel (surface colour, padding, rounded corners, shadow).
ShowMetadata bool true Shows title, artist, album and duration under the player when there is any.
Color DwsColor DwsColor.Primary Theme colour of the sliders, active buttons and focus rings.
ControlColor DwsColor DwsColor.Undefined Theme colour of the control icons and texts. Undefined uses the theme's text colour.
BackgroundColor DwsColor DwsColor.Undefined Theme colour of the background panel. Undefined uses the theme's surface colour.
Width int? null Width in px. Unset fills the container.
MaxWidth int? null Maximum width in px; the player shrinks with a narrower container.
Height int? null Height of the picture in px. Unset follows AspectRatio.
AspectRatio double? 16 / 9 Width-to-height ratio of the picture area, reserved before the video loads; the video is letterboxed inside it. Ignored while Height is set.
Name Typ Description
PlaylistIndexChanged EventCallback<int> Raised when another playlist video is shown (playlist panel, previous / next, AutoAdvance, PlayItemAsync).
MutedChanged EventCallback<bool> Raised when the sound is turned off or on.
VolumeChanged EventCallback<double> Raised when the volume changes.
PlaybackRateChanged EventCallback<double> Raised when the playback speed changes.
LoopChanged EventCallback<bool> Raised when looping is turned on or off.
CaptionTrackIndexChanged EventCallback<int?> Raised when another subtitle / caption track is shown, or none.
OnPlay EventCallback Raised when playback starts or resumes.
OnPause EventCallback Raised when playback pauses (also right before OnEnded).
OnStop EventCallback Raised by StopAsync and the stop button.
OnEnded EventCallback Raised when a video plays to its end (never while Loop is on).
OnTimeUpdate EventCallback<double> Raised with the position in seconds while playing, at most every TimeUpdateInterval.
OnSeeked EventCallback<double> Raised with the new position in seconds after a seek.
OnLoadedMetadata EventCallback<DwsVideoMetadata> Raised when the duration and size of a video are known (Title, Artist, Album, Duration, VideoWidth, VideoHeight).
OnFullscreenChanged EventCallback<bool> Raised when fullscreen is entered (true) or left (false).
OnPictureInPictureChanged EventCallback<bool> Raised when picture-in-picture is entered (true) or left (false).
OnTrackError EventCallback<DwsVideoTrack> Raised when a text track could not be loaded: a missing file, a .vtt file the server does not serve (ASP.NET Core needs Mappings[".vtt"] = "text/vtt"), or another origin without CORS. The video plays on; the log names the reason once per track.
OnError EventCallback<DwsVideoError> Raised when a video cannot be loaded or played: Code (Aborted, Network, Decode, SourceNotSupported, PlaybackBlocked, Unknown), the localised Message, the browser's Detail, ItemIndex, Item and IsFatal.
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.