Media Player
FreeKit chrome around a native `<video>` or `<audio>`: play / pause, a seek slider that speaks the time, volume and mute, playback speed, WebVTT captions and subtitles, full screen and picture in picture where the browser has them, and a playlist with previous / next that moves on when an item ends. One ARIA toolbar with a single tab stop, shortcuts scoped to the player, safe source URLs, a playback-error state with Try again, and the loading / error / empty states for the playlist. It never starts with sound.
Complexity tier: Interactive The primitive bar, plus: its async states are declared — none is an answer — it has a keyboard model and restores focus, and any destructive action it offers can be undone.
import { SvMediaPlayerComponent } from '@styloviz/display/media-player';Demo & usage
Basic usage
Usage example — open the gallery for the full interactive demo.
An interactive demo for this component lives in the gallery.
Open live demoMore examples
One video with captions and a poster
A single item is a playlist of one: no list, no previous / next. `sources` offers several encodings (best first); `tracks` are WebVTT files, and `captionLanguage` picks the one shown (null is off).
<sv-media-player [items]="[{ id: 'intro', title: 'Product tour', poster: '/media/tour.jpg', sources: [{ src: '/media/tour.webm', type: 'video/webm' }, { src: '/media/tour.mp4', type: 'video/mp4' }], tracks: [{ src: '/media/tour.en.vtt', srclang: 'en', label: 'English' }] }]" captionLanguage="en" />
Resume where the viewer stopped
`startTime` on an item seeks there when it loads, without emitting `seekComplete`. Save the place from `timeUpdate` (at most once per `timeUpdateInterval`, never mid-seek) and `paused`.
item = { id: lesson.id, title: lesson.title, src: lesson.url, startTime: bookmark() };
<sv-media-player [items]="[item]" (timeUpdate)="bookmark.set($event.currentTime)" (paused)="save($event)" />A podcast
`kind="audio"` drives a hidden `<audio>` and draws the artwork, title and subtitle; the active caption cue is shown as text.
<sv-media-player kind="audio" [items]="episodes" captionLanguage="en" />
A voice note
`layout="compact"` draws an audio clip as one row — play, seek, length / position and speed — for a voicemail, a dictated message or a call recording. `sinkId` (e.g. from `sv-audio-device-select`) routes it to a chosen speaker where `setSinkId` exists.
<sv-media-player kind="audio" layout="compact" [items]="[note]" [sinkId]="speaker() || null" (sinkError)="warn($event)" />
Demo media without files
`svDemoVideo`, `svDemoAudio` and `svDemoCaptions` make a WebM clip of any length, a WAV chime and a WebVTT file in the browser — for prototypes and tests. Create the object URLs after render and revoke them.
import { svDemoCaptions, svDemoVideo } from '@styloviz/display'; const src = URL.createObjectURL(svDemoVideo({ seconds: 754, scene: 'teal' })); const vtt = URL.createObjectURL(svDemoCaptions([{ start: 0, end: 4, text: 'Welcome.' }]));
When to use
Lesson videos in a course platform, product tours and recorded webinars in a SaaS app, or a podcast / voice-note player. Anywhere the browser's own controls look out of place, or you need events to save progress, count views or move to the next item. Use the Carousel for a set of still images, and a third-party player for adaptive streaming (HLS / DASH) or DRM — this one plays what a native element can.
Compare with
- Carousel — Carousel steps through still slides on a timer. Media Player plays time-based media — a native video or audio element with a seek bar, captions and a playlist.
- Transcript — Transcript shows the words of a recording — speakers, timestamps, search and export — and seeks a player. Media Player plays the recording; link the two with `[player]` and `[currentTime]`.
Async states
- loading
- error
- retry
Item identity & owned state
- Item key
itemKey— set this when your rows have noid, so selection survives a reorder.
Inputs
| Name | Type | Default | Description |
|---|---|---|---|
| items | readonly SvMediaItem[] | [] | What to play — one item for a single clip, several for a playlist. |
| index | number (two-way) | 0 | The item playing, as an index into `items` (two-way). Out-of-range values are clamped. |
| kind | SvMediaKind | 'video' | `video` draws the picture; `audio` draws the artwork and title, and shows captions as text. |
| layout | SvMediaLayout | 'default' | `compact` draws an audio clip as one row — play, seek, time, speed — for a voice note or a call recording. No artwork, volume slider or playlist (the M key still mutes). Ignored for `kind="video"`. |
| sinkId | string | null | null | The output device (`MediaDeviceInfo.deviceId`, e.g. from `sv-audio-device-select`'s `outputDeviceId`) the sound plays through. Applied with `setSinkId` where the browser has it, and ignored where it does not; null leaves the system default. |
| loading | boolean | false | True while the host is still fetching the playlist. |
| error | SvDataError | string | null | null | The playlist failed to load (a string or an `SvDataError`). Playback errors are not this — they show inside the player and emit `mediaError`. |
| itemKey | SvItemKey<SvMediaItem> | 'id' | Identity of an item, a property name or a function. |
| captionLanguage | string | null (two-way) | null | The caption / subtitle track shown, by `srclang`; null is off (two-way). |
| volume | number (two-way) | 1 | Volume from 0 to 1 (two-way). |
| muted | boolean (two-way) | false | Sound off (two-way). |
| playbackRate | number (two-way) | 1 | Playback speed (two-way). |
| playbackRates | readonly number[] | [0.5, 0.75, 1, 1.25, 1.5, 2] | The speeds the speed button steps through. |
| autoplay | boolean | false | Start playing as soon as the first item can play — always muted (a viewer turns the sound on), and never when the viewer prefers reduced motion. |
| autoAdvance | boolean | true | When an item ends, go on to the next one. |
| seekStep | number | 5 | Seconds the arrow keys skip. |
| preload | SvMediaPreload | 'metadata' | How much to fetch before play: `none`, `metadata` (length and first frame) or `auto`. |
| crossOrigin | 'anonymous' | 'use-credentials' | null | null | CORS mode for the media and its tracks — set it when the `.vtt` files live on another origin. |
| shortcuts | boolean | true | Keyboard shortcuts inside the player (Space/K, ←/→, M, F, C, `<`/`>`). |
| showPlaylist | boolean | true | Show the playlist when there is more than one item. |
| playlistPosition | SvMediaPlaylistPosition | 'bottom' | `bottom` stacks the playlist under the player; `end` puts it beside the player when there is room. |
| timeUpdateInterval | number | 1000 | Least time between two `timeUpdate` emissions, in milliseconds. |
| ariaLabel | string | null | null | The player's accessible name. Null derives "<title> — media player". |
| locale | string | svLocale() | BCP-47 locale for the speed figures. |
| labels | Partial<SvMediaPlayerLabels> | {} | Per-instance text, merged over the registry's `display` labels. |
Outputs
| Event | Payload type | Description |
|---|---|---|
| played | SvMediaTimeEvent | Playback started or resumed. |
| paused | SvMediaTimeEvent | Playback paused — by the viewer, by `pause()`, or at the end. |
| finished | SvMediaTimeEvent | The item played to its end (before any `autoAdvance`). |
| timeUpdate | SvMediaTimeEvent | The playhead moved while playing — at most once per `timeUpdateInterval`, never during a seek. |
| seekComplete | SvMediaSeekEvent | The viewer (or `seek()`) moved the playhead — `from` is where it was. Not emitted for an item's `startTime`. |
| trackChange | SvMediaTrackChange | The playlist moved to another item. `index` changes with it. |
| mediaError | SvMediaErrorEvent | The current item could not be played. The player shows the reason and a Try again button. |
| retry | void | The host should re-run the failed playlist request (`error`). |
| sinkError | SvMediaSinkError | `sinkId` could not be applied — the device was unplugged, or the page is not allowed to choose one. Playback carries on through the default device. |
| indexChange | number | Emits the new `index` whenever it changes — the output half of `[(index)]`. |
| captionLanguageChange | string | null | Emits the new `captionLanguage` whenever it changes — the output half of `[(captionLanguage)]`. |
| volumeChange | number | Emits the new `volume` whenever it changes — the output half of `[(volume)]`. |
| mutedChange | boolean | Emits the new `muted` whenever it changes — the output half of `[(muted)]`. |
| playbackRateChange | number | Emits the new `playbackRate` whenever it changes — the output half of `[(playbackRate)]`. |
Wire it to your API
This component is headless about transport: it renders what you give it and reports what the user asks for. Nothing below requires @styloviz/data — drive it from whatever you already use.
Template
Bound to the names this component actually exposes.
<sv-media-player [items]="items()" [loading]="loading()" [error]="error()" (retry)="load()" />
Host class
Drive the three async inputs from your own fetch.
import { signal } from '@angular/core'; import { toSvDataError, type SvDataError } from '@styloviz/core'; import type { SvMediaItem } from '@styloviz/display/media-player'; readonly items = signal<SvMediaItem[]>([]); readonly loading = signal(false); readonly error = signal<SvDataError | null>(null); async load(): Promise<void> { this.loading.set(true); this.error.set(null); try { const res = await fetch('/api/items'); if (!res.ok) throw res; this.items.set(await res.json()); } catch (e) { this.error.set(toSvDataError(e)); } finally { this.loading.set(false); } }
This component does not emit a query, so it renders what you give it. Call `load()` on your own trigger and bind `items`, `loading` and `error`. Normalize failures with `toSvDataError()` from `@styloviz/core`. It derives `retryable` from the status, so a 404 does not get a "Try again" button that can only fail again.
Full walkthrough: Connecting to a backend.
Customization & theming
Surfaces use the `gray` and `primary` tokens with `dark:` pairs; the picture area is always black. `playlistPosition="end"` puts the playlist beside the player when the player is wide enough (a container query), otherwise below. `playbackRates`, `seekStep`, `preload`, `crossOrigin`, `autoAdvance`, `showPlaylist`, `shortcuts` and `timeUpdateInterval` tune behaviour; `play()`, `pause()`, `togglePlay()`, `seek(seconds)`, `next()`, `previous()` and `select(index)` drive it from code. Every string comes from the `display` labels (`media*` keys) in 12 language packs — `provideSvLabels(SV_DISPLAY_LABELS_DE)` or the per-instance `labels` input. `layout="compact"` is the one-row voice-note shape for `kind="audio"` (video keeps the full player); `sinkId` picks the output device through `HTMLMediaElement.setSinkId`, feature-detected, and a refusal is reported through `sinkError` while playback carries on through the default device. Sources, tracks and posters pass `svIsSafeMediaUrl` / `svIsSafeUrl`: http(s), relative, `blob:` and media `data:` URIs play; `javascript:` and friends are never requested.
Best practices
Do: Give every video a captions track. Captions are an accessibility requirement (WCAG 1.2.2), not a feature. Do: Offer `sources` in two formats (WebM and MP4) with their `type`, so each browser picks one it can play. Do: Keep `loading` / `error` for the playlist request. A file that fails to play is reported inside the player and through `mediaError` — the two are different failures. Don't: Don't expect `autoplay` to start with sound. It always starts muted, and not at all for a viewer who prefers reduced motion. Don't: Don't count `timeUpdate` events as "watched" — a seek moves the playhead without watching. Record the stretches between `played` and `paused` / `finished` / `seekComplete`, as the LMS template does. Tip: Bind `[(captionLanguage)]`, `[(volume)]`, `[(muted)]` and `[(playbackRate)]` to remember a viewer's choices between items or sessions.
Accessibility
The controls are one `role="toolbar"` with a roving tab stop: Tab enters it once, ←/→ / Home / End move between controls, and on the volume slider ↑/↓ change the volume — so no control traps focus. This follows the WAI-ARIA toolbar pattern, built on the kit's own `svRovingTarget` rather than `@angular/aria`, which the kit does not depend on in 2.0. The seek slider is a native range with its own tab stop, an accessible name and `aria-valuetext` such as "1:02 of 3:00"; its arrow keys skip `seekStep` seconds and Page Up / Page Down a tenth. Shortcuts work only inside the player and never with Ctrl, Alt or Meta: Space or K play / pause (Space is left to a focused button), ←/→ on the picture skip, M mutes, F full screen, C cycles captions, < and > change the speed. They are described to screen readers and named in `aria-keyshortcuts`. Toggles say their state (`aria-pressed` on mute and captions; the full-screen and picture-in-picture buttons change their names); a caption or speed change is announced politely. The current playlist item has `aria-current` and "Now playing". A playback failure is a `role="alert"` with the reason in words and a Try again button; buttons are at least 40 px, with visible focus rings in both themes.
Feedback on Media Player
Spotted a gap in this page, or something that didn't work as described? Comments are GitHub Discussions in the public styloviz/community repo, so posting needs a GitHub account.