### Complete Utility Setup Example
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Utilities.md
Demonstrates usage of time formatting, capability checks, and file download utilities in a player context.
```typescript
import {
formatTime,
formatSpokenTime,
canPlayHLSNatively,
canUsePictureInPicture,
getDownloadFile,
} from 'vidstack';
// Format display time
const displayTime = formatTime(125); // "2:05"
const speakTime = formatSpokenTime(125); // "2 minutes, 5 seconds"
// Check device capabilities
const supportsNativeHLS = canPlayHLSNatively();
const supportsPiP = canUsePictureInPicture();
// Setup player based on capabilities
const player = new MediaPlayer({
preferNativeHLS: supportsNativeHLS,
src: 'video.mp4',
});
// Download feature
const downloadBtn = document.querySelector('.download-btn');
downloadBtn?.addEventListener('click', () => {
const { url, filename } = getDownloadFile('https://example.com/video.mp4');
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
});
```
--------------------------------
### Track Configuration Examples
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Tracks.md
Examples of configuring track elements with different formats.
```html
```
--------------------------------
### WebVTT File Example
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Tracks.md
A basic example of the WebVTT file format structure.
```text
WEBVTT
00:00:00.500 --> 00:00:07.000
Caption text appears here
00:00:08.000 --> 00:00:12.000
Next caption here
```
--------------------------------
### Play Media Example
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/MediaRemoteControl.md
Initiate playback on the media player instance.
```typescript
const player = document.querySelector('media-player');
await player.remoteControl.play();
```
--------------------------------
### play()
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/MediaPlayer.md
Starts media playback.
```APIDOC
### play()
#### Description
Start media playback.
#### Signature
`play(): Promise`
#### Returns
Promise that resolves when playback starts or rejects on error.
```
--------------------------------
### Implement FullscreenButton in HTML
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/UIComponents.md
Example usage of the FullscreenButton component.
```html
```
--------------------------------
### Initialize MediaPlayer
Source: https://github.com/vidstack/player/blob/main/_autodocs/INDEX.md
Basic setup for a new player instance with source and controls.
```typescript
const player = new MediaPlayer({
src: 'video.mp4',
title: 'My Video',
controls: true,
});
```
--------------------------------
### play()
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/MediaRemoteControl.md
Starts media playback. Returns a promise that resolves when playback begins.
```APIDOC
## play(request?: MediaPlayRequest | Event)
### Description
Starts media playback. Returns a promise that resolves when playback starts.
### Parameters
- **request** (MediaPlayRequest | Event) - Optional - Originating event for event chaining.
### Returns
- **Promise** - Resolves when playback starts.
### Throws
- **Error** - If playback cannot start (e.g., no source).
```
--------------------------------
### Implement CustomStorage
Source: https://github.com/vidstack/player/blob/main/_autodocs/types.md
Example implementation of the MediaStorage interface using browser localStorage.
```typescript
class CustomStorage implements MediaStorage {
setItem(key: string, value: string) {
localStorage.setItem(key, value);
}
getItem(key: string) {
return localStorage.getItem(key);
}
}
const player = new MediaPlayer({
storage: new CustomStorage(),
});
```
--------------------------------
### Complete Media Control Setup
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/MediaRemoteControl.md
Demonstrates basic playback control implementation including play, pause, seeking, volume, playback rate, and fullscreen toggling.
```typescript
const player = document.querySelector('media-player');
const { remote } = player.remoteControl;
// Play
document.getElementById('play-btn').addEventListener('click', () => {
remote.play();
});
// Pause
document.getElementById('pause-btn').addEventListener('click', () => {
remote.pause();
});
// Seek to 30 seconds
document.getElementById('seek-30').addEventListener('click', () => {
remote.seek(30);
});
// Set volume to 80%
document.getElementById('volume-80').addEventListener('click', () => {
remote.setVolume(0.8);
});
// Set 1.5x speed
document.getElementById('speed-15x').addEventListener('click', () => {
remote.setPlaybackRate(1.5);
});
// Toggle fullscreen
document.getElementById('fullscreen').addEventListener('click', async () => {
await remote.toggleFullscreen();
});
```
--------------------------------
### Audio Track Source Examples
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Tracks.md
Examples of how audio tracks are defined in HLS and DASH manifests.
```text
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",LANGUAGE="en",LABEL="English"
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",LANGUAGE="es",LABEL="Español"
```
```xml
...
...
```
--------------------------------
### Load Method Usage
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/MediaProvider.md
Example of initializing a provider by loading a video element into the media-provider component.
```typescript
const provider = document.querySelector('media-provider');
const videoElement = document.createElement('video');
provider.load(videoElement);
```
--------------------------------
### Initialize Basic MediaPlayer
Source: https://github.com/vidstack/player/blob/main/_autodocs/configuration.md
Basic setup for a standard media player instance with source, poster, and initial playback settings.
```typescript
import { MediaPlayer } from 'vidstack';
const player = new MediaPlayer({
src: 'https://example.com/video.mp4',
title: 'My Video',
poster: 'https://example.com/poster.jpg',
paused: true,
volume: 0.8,
controls: true,
});
```
--------------------------------
### Implement Tooltip Component
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/UIComponents.md
Example usage of a tooltip wrapping a trigger and content.
```html
Play (k)
```
--------------------------------
### Construct Media Player Layout
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/UIComponents.md
Full example of a media player structure including provider, controls, and buttons.
```html
```
--------------------------------
### Handle Media State Updates
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Events.md
Examples for tracking time, duration, and buffering changes.
```typescript
player.addEventListener('time-update', () => {
const time = player.$state.currentTime();
console.log(`Current time: ${time}s`);
});
```
```typescript
player.addEventListener('duration-change', () => {
const duration = player.$state.duration();
console.log(`Duration: ${duration}s`);
});
```
```typescript
player.addEventListener('buffered-change', () => {
const buffered = player.$state.buffered();
console.log(`Buffered to ${buffered.end(0)}s`);
});
```
--------------------------------
### Setup Complete Event Handling
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Events.md
Organizes event listeners and reactive state effects for comprehensive player monitoring.
```typescript
function setupEventHandling(player) {
// Playback
player.on('play', handlePlay);
player.on('pause', handlePause);
player.on('ended', handleEnded);
// Buffering
player.on('waiting', handleBuffering);
player.on('playing', handleBufferingResolved);
// Seeking
player.on('seeking', handleSeeking);
player.on('seeked', handleSeeked);
// Errors
player.on('error', handleError);
// State changes (better with effects)
effect(() => {
const state = {
paused: player.$state.paused(),
currentTime: player.$state.currentTime(),
duration: player.$state.duration(),
volume: player.$state.volume(),
};
updateUI(state);
});
}
function handlePlay() { /* ... */ }
function handlePause() { /* ... */ }
function handleEnded() { /* ... */ }
function handleBuffering() { /* ... */ }
function handleBufferingResolved() { /* ... */ }
function handleSeeking() { /* ... */ }
function handleSeeked() { /* ... */ }
function handleError(e) { /* ... */ }
function updateUI(state) { /* ... */ }
```
--------------------------------
### Pause Media Example
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/MediaRemoteControl.md
Halt playback on the media player instance.
```typescript
await player.remoteControl.pause();
```
--------------------------------
### Get Time Range Start
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Utilities.md
Retrieves the start time of the first range, useful for determining VOD or live stream start points.
```typescript
import { getTimeRangesStart } from 'vidstack';
const seekable = player.$state.seekable();
const startTime = getTimeRangesStart(seekable); // 0 for VOD, live start for live
```
--------------------------------
### Implement CaptionButton in HTML
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/UIComponents.md
Example usage of the CaptionButton component.
```html
```
--------------------------------
### Toggle Media Playback Example
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/MediaRemoteControl.md
Switch the current playback state of the media player.
```typescript
await player.remoteControl.togglePaused();
```
--------------------------------
### Configure Media Sources
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/MediaProvider.md
Examples of defining media sources for different formats and quality variants.
```typescript
// HTML5 video
{ src: 'video.mp4', type: 'video/mp4' }
// HLS stream
{ src: 'stream.m3u8', type: 'application/x-mpegURL' }
// DASH stream
{ src: 'stream.mpd', type: 'application/dash+xml' }
// YouTube
{ src: 'https://youtube.com/watch?v=VIDEO_ID' }
// Vimeo
{ src: 'https://vimeo.com/VIDEO_ID' }
// Quality variants
[
{ src: 'video-360p.mp4', type: 'video/mp4', height: 360 },
{ src: 'video-720p.mp4', type: 'video/mp4', height: 720 },
{ src: 'video-1080p.mp4', type: 'video/mp4', height: 1080 },
]
```
--------------------------------
### Implement PlayButton in HTML
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/UIComponents.md
Example usage of the PlayButton component within a media player container.
```html
```
--------------------------------
### Configure MediaPlayer keyboard shortcuts
Source: https://github.com/vidstack/player/blob/main/_autodocs/types.md
Example implementation of keyboard shortcut mapping within the MediaPlayer constructor.
```typescript
const player = new MediaPlayer({
keyShortcuts: {
togglePaused: 'k Space',
seekBackward: 'j ArrowLeft',
seekForward: 'l ArrowRight',
toggleMuted: 'm',
toggleFullscreen: 'f',
volumeUp: 'ArrowUp',
volumeDown: 'ArrowDown',
speedUp: '>',
slowDown: '<',
},
});
```
--------------------------------
### Handle Playback State Events
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Events.md
Examples for handling basic playback lifecycle events.
```typescript
player.addEventListener('play', () => {
console.log('Playback started');
});
```
```typescript
player.addEventListener('pause', () => {
console.log('Playback paused');
});
```
```typescript
player.addEventListener('playing', () => {
console.log('Actually playing (not just buffering)');
});
```
```typescript
player.addEventListener('ended', () => {
console.log('Playback finished');
// Show "Play Again" button
});
```
```typescript
player.addEventListener('started', () => {
console.log('Playback has been initiated');
// Track analytics event
});
```
--------------------------------
### Implement Controls Component
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/UIComponents.md
Example usage of the controls component with custom hide delay.
```html
```
--------------------------------
### Initialize Src object
Source: https://github.com/vidstack/player/blob/main/_autodocs/types.md
Example of creating a source object using the Src interface.
```typescript
const source: Src = {
src: 'video-1080p.mp4',
type: 'video/mp4',
height: 1080,
bitrate: 5000000,
};
```
--------------------------------
### Implement MuteButton in HTML
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/UIComponents.md
Example usage of the MuteButton component.
```html
```
--------------------------------
### Handle Seek Events
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Events.md
Examples for tracking seek operations.
```typescript
player.addEventListener('seeking', (e) => {
console.log(`Seeking preview to ${e.detail}s`);
});
```
```typescript
player.addEventListener('seeked', () => {
console.log('Seek completed, playback resumed');
});
```
--------------------------------
### Conditional UI Building Example
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Utilities.md
Uses capability check utilities to dynamically build and render player controls.
```typescript
import {
canChangeVolume,
canUsePictureInPicture,
canUseVideoPresentation,
} from 'vidstack';
// Build control bar conditionally
const controls = [];
if (canChangeVolume()) {
controls.push(createVolumeControl());
}
if (canUsePictureInPicture()) {
controls.push(createPipButton());
}
if (canUseVideoPresentation()) {
controls.push(createAdvancedSettings());
}
// Render controls
renderControlBar(controls);
```
--------------------------------
### Format time with FormatTimeOptions
Source: https://github.com/vidstack/player/blob/main/_autodocs/types.md
Configuration for time formatting and usage examples for the formatTime utility.
```typescript
interface FormatTimeOptions {
padHours?: boolean; // Always show hours (00:00:00 vs 00:00)
guide?: number; // Reference duration for zero-padding
firstZeroFilled?: boolean; // Pad first number segment
}
```
```typescript
import { formatTime } from 'vidstack';
formatTime(125); // "2:05"
formatTime(125, { padHours: true }); // "0:02:05"
formatTime(3661); // "1:01:01"
```
--------------------------------
### getTimeRangesStart()
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Utilities.md
Retrieves the start time of the first range in a TimeRange object.
```APIDOC
## getTimeRangesStart(ranges)
### Description
Returns the start time of the first range in the provided TimeRange object, or null if empty.
### Parameters
- **ranges** (TimeRange) - Required - The TimeRange object to query.
```
--------------------------------
### Implement ControlsGroup Component
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/UIComponents.md
Example usage of grouping controls within a controls container.
```html
```
--------------------------------
### Handle Buffering Events
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Events.md
Example for handling playback interruptions due to data loading.
```typescript
player.addEventListener('waiting', () => {
console.log('Buffering...');
// Show loading spinner
});
```
--------------------------------
### Implement SeekButton in HTML
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/UIComponents.md
Example usage of the SeekButton component for forward and backward seeking.
```html
```
--------------------------------
### Configure HLS Stream
Source: https://github.com/vidstack/player/blob/main/_autodocs/configuration.md
Setup for HLS live streams by specifying the MIME type and live-specific configuration options.
```typescript
const player = new MediaPlayer({
src: {
src: 'https://example.com/stream.m3u8',
type: 'application/x-mpegURL',
},
title: 'Live Stream',
streamType: 'live',
liveEdgeTolerance: 10,
});
```
--------------------------------
### Robust Media Loading Example
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Utilities.md
Filters a list of media sources based on browser playback support using utility functions.
```typescript
import { canPlayType, getMediaSourceType } from 'vidstack';
const sources = [
{ src: 'video.mp4', type: 'video/mp4' },
{ src: 'video.webm', type: 'video/webm' },
{ src: 'video.ogv', type: 'video/ogg' },
];
// Filter to supported formats
const supportedSources = sources.filter(src => {
const support = canPlayType(src.type);
return support !== '';
});
player.src = supportedSources;
```
--------------------------------
### Play media playback
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/MediaPlayer.md
Initiates media playback. Returns a promise that resolves when playback starts or rejects on error.
```typescript
play(): Promise
```
```typescript
const player = document.querySelector('media-player');
await player.play();
```
--------------------------------
### Selecting Audio Tracks
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Tracks.md
Provides examples for finding and setting the active audio track by language or kind, and disabling audio.
```typescript
// Get available audio tracks
const { audioTracks } = player.$state;
// Find track by language
const frenchTrack = audioTracks().find(t => t.language === 'fr');
if (frenchTrack) {
player.$state.audioTrack.set(frenchTrack);
}
// Find track by label
const descriptiveAudio = audioTracks().find(t => t.kind === 'description');
if (descriptiveAudio) {
player.$state.audioTrack.set(descriptiveAudio);
}
// Disable audio track (all tracks)
player.$state.audioTrack.set(null);
```
--------------------------------
### Chapter VTT Format
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Tracks.md
Standard WebVTT format for defining chapter markers with start and end timestamps.
```text
WEBVTT
00:00:00.000 --> 00:05:30.000
Introduction
00:05:30.000 --> 00:15:45.000
Getting Started
00:15:45.000 --> 00:28:00.000
Advanced Topics
00:28:00.000 --> 00:30:00.000
Conclusion
```
--------------------------------
### startLoading()
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/MediaPlayer.md
Triggers media loading.
```APIDOC
### startLoading()
#### Description
Trigger media loading (used with custom load strategy).
#### Signature
`startLoading(): void`
```
--------------------------------
### Define and Use AudioTrack
Source: https://github.com/vidstack/player/blob/main/_autodocs/types.md
Interface for audio track configuration and example usage for listing and selecting tracks.
```typescript
interface AudioTrack {
id: string; // Unique identifier
kind: string; // 'main', 'alternative', 'commentary', 'translation'
label: string; // User-readable label
language: string; // BCP 47 language code (e.g., 'en', 'es', 'fr')
default?: boolean; // Whether this track is default
}
```
```typescript
const { audioTracks, audioTrack } = player.$state;
// List available audio tracks
console.log(audioTracks());
// Select French audio
const frenchTrack = audioTracks().find(t => t.language === 'fr');
if (frenchTrack) {
player.$state.audioTrack.set(frenchTrack);
}
```
--------------------------------
### Define and Use VideoQuality
Source: https://github.com/vidstack/player/blob/main/_autodocs/types.md
Interface for video quality levels and example usage for selecting quality via player state.
```typescript
interface VideoQuality {
bitrate?: number; // Bitrate in bps
codec?: string; // Video codec
frameRate?: number; // Frames per second
width?: number; // Video width in pixels
height?: number; // Video height in pixels
label?: string; // User-friendly label (e.g., "1080p")
constructor?: Function; // Quality class constructor
}
```
```typescript
const { qualities, quality } = player.$state;
effect(() => {
const currentQuality = quality();
console.log(`Selected quality: ${currentQuality?.height}p`);
});
// Select specific quality
const hd1080 = qualities().find(q => q.height === 1080);
if (hd1080) {
player.$state.quality.set(hd1080);
}
```
--------------------------------
### Initialize MediaPlayer and MediaProvider
Source: https://github.com/vidstack/player/blob/main/_autodocs/00-START-HERE.md
Sets up the core player instance and configures the media provider with specific loaders.
```typescript
import { MediaPlayer, MediaProvider, VideoProviderLoader } from 'vidstack';
const player = new MediaPlayer({
src: 'video.mp4',
title: 'My Video',
controls: true,
volume: 0.8,
});
const provider = new MediaProvider({
loaders: [new VideoProviderLoader()],
});
```
--------------------------------
### Access and configure logger
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/Utilities.md
Demonstrates accessing the logger via media context and setting the log level during initialization.
```typescript
const { logger } = useMediaContext();
logger?.log('Custom log message');
logger?.error('Error occurred');
logger?.debug('Debug information');
```
```typescript
const player = new MediaPlayer({
logLevel: 'debug', // 'silent' | 'error' | 'warn' | 'info' | 'debug'
});
```
--------------------------------
### load()
Source: https://github.com/vidstack/player/blob/main/_autodocs/api-reference/MediaProvider.md
Initializes the provider loader with a target DOM element to begin media playback.
```APIDOC
## load()
### Description
Triggers the provider loader to initialize with the given target element. The loader will be selected based on the current media source.
### Method
load(target: HTMLElement | null | undefined): void
### Parameters
- **target** (HTMLElement | null | undefined) - Required - The DOM element to load the provider into (e.g.,