Spark Player v1.1.0 Live demo README Troubleshooting
Documentation

Spark Player, end to end.

A vanilla-JavaScript video player for progressive files, HLS and four embedded providers — with three switchable themes, paged playlists, chapters, sprite hover previews and automatic provider artwork. No framework, no runtime dependencies, one stylesheet and one generated script.

Quick start

Create a mount element, load two files, and pass a config object. That is the whole setup.

<!-- 1. Styles -->
<link rel="stylesheet" href="assets/css/spark-player.css">

<!-- 2. Mount point -->
<div id="player"></div>

<!-- 3. Player -->
<script src="assets/js/spark-player.js"></script>
<script>
  const player = SparkPlayer.create('#player', {
    playlist: [
      { src: 'assets/media/sintel-trailer.mp4', title: 'Sintel' },
      { src: 'https://vimeo.com/1084537', title: 'Big Buck Bunny' }
    ],
    theme: 'glass',
    autoplayNext: true
  });
</script>

Serve the page over HTTP with npm run serve (a range-capable static server) or npx serve. Opening the file with file:// blocks HLS, sprite sheets and provider SDKs.

A single-source player works too: pass src (and optionally type) instead of playlist. The playlist sidebar hides itself when there is only one item.

Global API

MemberTypeDescription
SparkPlayer.create(target, options)functionAccepts a selector or an element. Returns the player instance.
SparkPlayer.versionstringBundled version, e.g. 1.1.0.

Options

Every option is optional. Defaults are tuned for a dark, glass-first page.

OptionDefaultNotes
src''Single video source. Ignored when playlist is present.
type'auto'auto, video, hls, youtube, vimeo, dailymotion, facebook.
title''Title for a single source. Falls back to the file name.
poster''Single-source poster. Playlist items carry their own.
playlist[]Array of items — see Playlist schema.
startIndex0Item to load first.
autoplayfalseBrowsers usually require muted: true for this to succeed.
mutedfalseInitial mute state.
volume0.80–1.
loopfalseLoop the current item.
playbackRate10.25–3.
startTime0Single-source resume point in seconds.
theme'glass'glass, neon or desert. See Themes.
accent / accent2''Optional per-instance accent override on top of the theme.
chapters[]Single-source chapter list.
subtitles[]Single-source text tracks.
thumbnails''WebVTT sprite sheet for hover previews.
playlistTitle'Up next'Sidebar heading.
playlistOpentrueSidebar starts open on desktop, closed below 980px.
showTopBarfalseShow the title/theme bar over the video. Also toggleable from Settings; remembered per visitor.
autoplayNexttrueAdvance when an item ends.
loopPlaylistfalseWrap after the last item.
hideDelay2600Idle milliseconds before the controls fade.
keyboardtrueKeyboard shortcuts while the player has focus.
persisttrueRemember volume, mute, rate, autoplay, top bar and theme in localStorage.
autoMetadatatrueFetch missing posters and runtimes. See below.
readyTimeout18000Milliseconds before a slow source becomes a recoverable error. 0 disables.
leadingSkip10Seconds for the skip-back/forward buttons.
doubleClickFullscreentrueDouble-click the stage to toggle fullscreen.
crossoriginfalseAdds crossorigin="anonymous" to native video.
dailymotionPlayerId''Required for Dailymotion. Create one in Dailymotion Studio.
facebookAppId / facebookAccessToken''Optional; improves Facebook embed reliability. A Graph token also enables automatic Facebook artwork and runtime lookup ahead of the public fallbacks.
facebookThumbnailProxy''Optional CORS relay for the public-page Facebook thumbnail. Use {url} for an encoded target or {rawurl} for the raw embed URL. Empty uses the built-in relays.
hls{}Merged into the hls.js config object.
youtube{}Merged into the YouTube IFrame player vars.
onReady / onErrornullConvenience callbacks; on() is preferred for multiple listeners.

Playlist schema

Each item is a plain object. Everything except src is optional.

{
  src: 'assets/media/sintel-trailer.mp4',  // required
  type: 'video',                            // optional hint
  title: 'Sintel — Blender Open Movie',
  poster: 'assets/posters/sintel.png',      // wins over auto-fetch
  duration: 52,                             // seconds; wins over auto-fetch
  startTime: 0,
  thumbnails: 'assets/media/sintel-thumbnails.vtt',
  subtitles: [
    { src: 'assets/media/sintel-en.vtt', label: 'English', srclang: 'en' }
  ],
  chapters: [
    { start: 0,  title: 'The hunt' },
    { start: 10, title: 'The old storyteller' }
  ]
}

Items without a poster get a deterministic gradient placeholder immediately, so the sidebar never shows empty boxes while metadata loads.

Themes

Three complete visual identities ship in one stylesheet. The frosted segmented switch in the top bar — next to the Chapters button — swaps them live; the top bar is hidden by default and can be enabled from the Settings sheet. Each option carries a two-colour swatch dot: teal/violet for Glass, cyan/magenta for Neon, amber/terracotta for Desert.

Glass Apple-visionOS glass. Translucent white at 12%, strong blur, cyan→violet progress, Inter.
Neon Synthwave. Near-black #05060f, cyan→magenta gradient border, pulsing play ring, monospace timecode, Space Grotesk.
Desert Warm and golden. Sand-beige glass at 18%, amber→terracotta progress, golden active rows, Poppins.
// At init
const player = SparkPlayer.create('#player', { playlist, theme: 'desert' });

// At runtime
player.setTheme('neon');
player.on('themechange', ({ theme, label }) => {
  console.log(theme, label);   // 'neon', 'Neon'
});

The choice is written to localStorage under spark-player:prefs when persist is on, so a visitor keeps their theme across pages. Set persist: false to opt out, or theme at init to force a starting point for new visitors only.

Theme tokens

Themes are plain CSS custom properties on the .spk root, exposed via data-theme. Override them in your own stylesheet when the three built-ins are not enough:

VariableRole
--spk-accentPrimary accent — progress start, active states, focus ring.
--spk-accent-2Secondary accent — progress end, glows.
--spk-grad-1 / -2 / -3Play button and solid-button gradient stops.
--spk-progress-midMiddle stop of the timeline gradient.
--spk-inkText/icon colour drawn on accent-filled controls.
--spk-text / --spk-muted / --spk-faintText ramp.
--spk-glass / --spk-glass-strongSurface fills for the bar, sheets and popups.
--spk-stroke / --spk-stroke-softHairline borders.
--spk-radiusStage and sidebar corner radius.
/* Your own theme, layered on top of Neon */
.spk[data-theme="neon"] {
  --spk-accent: #ff7a18;
  --spk-accent-2: #ffd166;
}

Auto posters & runtimes

Spark fills in missing playlist artwork and durations before the visitor clicks anything. The rule is simple and absolute: a demo-supplied poster or duration always wins. Only gaps are requested, and only once per src. A partial cache entry is completed later if another item with the same source still needs the missing field.

ProviderArtworkRuntime
YouTubehqdefault CDN thumbnail (always present, 480×360)Hidden 16:9 IFrame player reads getDuration() through the official API, one probe at a time and cached per video ID
DailymotionPublic Data API thumbnail (1080p preferred)Public Data API duration
VimeooEmbed thumbnail (requested at 1280px)oEmbed duration
FacebookoEmbed title only; thumbnail scraped from the public plugin page through a CORS relay, or Graph with a tokenHidden Facebook SDK plugin (getDuration()), or Graph length with a token
MP4 / WebMGradient placeholderDetached <video> metadata probe
HLS / M3U8Gradient placeholderPlaylist fetch; master playlists resolve to the first variant and #EXTINF values are summed

Requests run one at a time with a small gap, so a 30-item playlist does not open 30 connections at once. YouTube probes are serialised behind a single hidden player and time-boxed to nine seconds, so an unembeddable video cannot stall the queue. Facebook probes wait for the SDK for at most 14 seconds. Any failure is silent: the placeholder stays and playback is never blocked. A runtime learned during playback is written back to that playlist card, so the list becomes more accurate as the visitor watches.

Facebook has no public artwork/runtime endpoint. Spark scrapes the public plugin page through the CORS relays built into the player; they are best-effort and can rate-limit. Set facebookThumbnailProxy to your own relay for production, or supply facebookAccessToken for Graph lookups. Set autoMetadata: false to make no requests at all.

Playlist pagination

A short playlist scrolls. A playlist with more than nine items pages instead, so the sidebar stays a fixed, scannable height. At nine items or fewer the pager is not rendered — and it never appears for single-source players. On desktop the rail is pinned to the stage's 16:9 height, so a long playlist scrolls inside the sidebar instead of stretching the video frame; the pager and Previous/Next controls stay docked at the bottom. Below 980px the sidebar lifts out of the stage into a fixed, viewport-anchored glass sheet (capped at 74vh) that slides in from the right, so paging stays usable on a phone. Tapping the dimmed stage or anywhere outside the sheet closes it, and the pinned height is cleared.

ViewportRows per page
> 980px8
561–980px6
≤ 560px4

The pager shows a compact page window (1 … 4 5 6 … 12), a range readout (9–16 of 24) and prev/next arrows that disable at the ends. Loading an item from anywhere — autoplay advance, goTo(), keyboard N — jumps to the page that contains it. Resizing the window recalculates the page size and re-renders without losing the active item.

// Replace the whole playlist; pagination recalculates automatically
player.setPlaylist(nextItems, 0, { autoplay: false });

Providers

MP4 / WebM

Full custom control layer: seek, volume, rate, captions, PiP, fullscreen, poster and sprite previews. Quality selection appears when the item lists qualities; otherwise the browser decides.

HLS / M3U8

hls.js is loaded from assets/vendor/hls.min.js with a CDN fallback. Safari and iOS use native HLS. Adaptive levels are normalised into the quality menu as auto plus per-height entries.

YouTube

The IFrame API is loaded from YouTube. Playback, seeking, volume, rate and captions are proxied through the official SDK. YouTube removed programmatic quality selection in 2019 (setPlaybackQuality is a documented no-op), so the player works around it: it resizes the hidden embed to the requested resolution and scales it back down to the stage. YouTube chooses its stream from the iframe's own width, so 720p, 1080p and 4K now switch for real. YouTube still enforces a floor of roughly 480p in the embed and can lower the stream when bandwidth is insufficient; in that case the menu shows the requested level and the level actually playing, for example 1080p · playing 720p.

Vimeo

The Vimeo Player SDK is vendored at assets/vendor/vimeo-player.js. Quality values are passed through as the SDK reports them (never doubling a p suffix), and automatic selection is preserved. Text tracks are enabled with the correct track kind.

Dailymotion

Dailymotion requires a Player ID from Dailymotion Studio — pass it as dailymotionPlayerId or the embed will not initialise. The SDK is always fetched from https://geo.dailymotion.com/libs/player/{id}.js. Dailymotion does not permit self-hosting, which is why it is the one dependency that cannot live in assets/vendor/.

Facebook

Facebook's plugin keeps its own controls, but Spark uses the Embedded Video Player API. It embeds the official XFBML plugin, starts playback from its own poster overlay, reads the real duration (and writes it back to the playlist card) and follows play/pause/buffering events. Once playback begins the frame is handed to Facebook's native controls. Facebook may autoplay muted under browser autoplay rules; Spark restores its saved volume and mute state as soon as playback starts. Adding facebookAppId improves embed reliability. Public oEmbed returns a title but no artwork or runtime, so Spark scrapes the public plugin page through a CORS relay for the thumbnail and reads the runtime from the same SDK plugin. Set facebookThumbnailProxy to your own relay for production, or supply facebookAccessToken to use Graph lookups instead.

Provider artwork and runtimes are fetched from public oEmbed/metadata endpoints, which need CORS. If a proxy or strict CSP blocks them, the playlist falls back to placeholders and still plays.

Chapters

Chapters produce three things at once: tick marks on the timeline, a Chapters dropdown in the top bar, and an active row that tracks playback. Clicking a row seeks to that chapter.

chapters: [
  { start: 0,  title: 'The hunt' },
  { start: 10, title: 'The old storyteller' },
  { start: 20, title: 'Firelight' }
]

Plain numbers are accepted as a shorthand (chapters: [0, 10, 20]) and get autogenerated titles. Entries are sorted by start time, so order in the array does not matter.

Sprite previews

Hover previews use the standard WebVTT thumbnail-sprite format: each cue spans a time range and its payload is an image URL with an #xywh= fragment describing one cell.

WEBVTT

00:00:00.000 --> 00:00:05.220
../posters/sintel-sprite.jpg#xywh=0,0,160,90

00:00:05.220 --> 00:00:10.440
../posters/sintel-sprite.jpg#xywh=160,0,160,90

Subtitles

Native files use <track> elements. Provider tracks are mapped to the same menu.

subtitles: [
  { src: 'assets/media/sintel-en.vtt', label: 'English (SDH)', srclang: 'en', default: true }
]

Toggle with the CC button, the C key, or player.toggleCaptions(). Headerless YouTube tracks are listed by language code.

Keyboard

Shortcuts are active while the player has focus. Modifier combinations are ignored so browser and OS shortcuts keep working, and shortcuts never fire while you are typing in a form field.

KeyAction
Space / KPlay / pause
← / →Seek 5 seconds
J / LSeek 10 seconds back / forward
↑ / ↓Volume ±5%
MMute / unmute
FFullscreen
CCaptions
PPicture-in-picture
NNext item
Home / EndStart / end of the timeline
0–9Jump to 0–90%
EscClose menu, chapters or mobile sidebar

API

All chainable mutators return the instance.

MethodDescription
play()Start or resume. Retries automatically after an error.
pause()Pause playback.
toggle()Play / pause, or replay when ended.
seek(seconds)Absolute seek.
seekBy(delta)Relative seek.
goTo(index, autoplay)Load a playlist index. autoplay defaults to true.
next(userInitiated)Next item, wrapping when loopPlaylist is on.
previous(userInitiated)Previous item. If playback is past three seconds it restarts the current item first — the familiar media-player behaviour. Wired to the “Previous” button under the playlist.
setPlaylist(items, index, options)Replace the playlist, reset pagination, prefetch the new metadata and load index.
setVolume(0–1)Set volume and unmute if necessary.
setMuted(bool) / toggleMute()Mute controls.
setRate(rate)Playback speed, 0.25–3.
setQuality(value)'auto' or a provider-specific level. YouTube applies it best-effort; providers without quality control show an informational toast.
setCaption(value) / toggleCaptions()'off' or a track value.
setTheme('glass'|'neon'|'desert')Change the visual theme, persist it and emit themechange.
getState()Snapshot of playback state plus index, item, items and playlistOpen.
retry()Reload the current item at its last position.
toggleFullscreen()Enter or exit fullscreen.
requestPiP()Picture-in-picture, when the source supports it.
toast(message, kind)Show the built-in glass toast. kind: info, warn.
on(event, fn) / off(event, fn)Listeners. off(event) removes all.
destroy()Tear down adapters, listeners and timers; removes the DOM.
player
  .setTheme('desert')
  .setPlaylist(episodes, 3, { autoplay: true })
  .setRate(1.25);

console.log(player.getState().theme);   // 'desert'

Events

Register with player.on(name, handler), or listen on the mount element for spark:name custom events. The handler receives (detail, player).

EventDetail
ready{ index, item, duration, provider }
startedFirst frame of the first play.
timeupdate{ currentTime, duration }, throttled.
play / pause / endedPlayback transitions.
itemchange{ index, item } — emitted once per load.
load{ index, item } — emitted once per load, after itemchange.
playlistchange{ items, index } after setPlaylist().
themechange{ theme, label }
volumechange / ratechange / loopchangeSettings changes.
qualitychange / actualqualitychangeSelected and observed quality.
captionschange / captiontracksCaption selection and discovery.
fullscreenchange / pipchangePresentation changes.
error{ code, message } — not_found, unsupported, format, playback, provider, timeout.
destroyInstance torn down.
player.on('themechange', ({ label }) => {
  document.body.dataset.playerTheme = label.toLowerCase();
});

document.querySelector('#player').addEventListener('spark:itemchange', (event) => {
  document.title = event.detail.item.title;
});

Files & build

The shipped player is one file: assets/js/spark-player.js. It is assembled from the readable fragments in build/, in filename order, by a small Node script.

spark_audio_player/
├── index.html                 // demo landing page
├── documentation.html         // this page
├── README.md
├── package.json
├── build/                     // source fragments, concatenated in order
│   ├── 01-core.js
│   ├── 02-media-adapter.js
│   ├── 03-youtube.js
│   ├── 04-iframes.js
│   ├── 05-player-core.js
│   ├── 06-state.js
│   ├── 07-ui.js
│   ├── 08-interaction.js
│   └── 09-api.js
├── tools/build.js             // bundle builder
├── tools/serve.js             // range-capable preview server
├── assets/css/spark-player.css
├── assets/js/spark-player.js  // generated — do not edit
├── assets/js/demo.js
└── assets/vendor/             // hls.min.js, vimeo-player.js
CommandWhat it does
npm run buildRegenerate assets/js/spark-player.js from build/.
npm run checkExit non-zero if the bundle is stale — use it in CI or a pre-commit hook.
npm run serveStart the dependency-free range-capable preview server on localhost:8080. php -S does not support Range, so local MP4 seeking needs this server (or Apache/Nginx).

Editing assets/js/spark-player.js directly is a dead end — the next build overwrites it. Change the matching file in build/ and run npm run build.

Troubleshooting

The player is blank or the sidebar has no artwork

YouTube stays on “Loading”

Dailymotion shows an error card

Hover preview is missing

Runtimes show --:--

The pager never appears

Theme resets on reload

Autoplay is blocked