### Serve Demo Application
Source: https://github.com/peaberberian/wasp-hls/blob/main/README.md
Starts a local development server to serve the demo application, allowing it to be viewed and tested in a web browser. This is typically used after building the demo application.
```shell
npm run serve
```
--------------------------------
### Install Node.js Dependencies
Source: https://github.com/peaberberian/wasp-hls/blob/main/README.md
Installs all required Node.js dependencies for the project using npm. This command assumes npm is already installed, which is typically bundled with Node.js.
```shell
npm install
```
--------------------------------
### Build Documentation
Source: https://github.com/peaberberian/wasp-hls/blob/main/README.md
Builds the project's documentation, written in the `doc/` directory, to its final output directory (`build/doc`). The built documentation can then be served for browser viewing.
```shell
# Build the documentation
npm run doc
# Serve the documentation (e.g., http://localhost:port/doc)
npm run serve
```
--------------------------------
### Install WaspHlsPlayer with npm or yarn
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/Getting_Started/Welcome.md
This snippet shows how to install the WaspHlsPlayer library using either npm or yarn package managers. No specific inputs or outputs are directly associated with these commands, but they are prerequisites for using the library.
```sh
// With npm
npm install wasp-hls
// or with yarn
yarn add wasp-hls
```
--------------------------------
### Load Content with Starting Position (Number)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Loading_a_content.md
Demonstrates loading content with a specific starting time in seconds using the `startingPosition` option as a number. This is useful for VOD or live content playback at a defined point.
```javascript
player.load(playlistUrl, {
startingPosition: 10,
});
```
```javascript
// Unix timestamp, in seconds, corresponding to now minus 1 minute
const date = Date.now() / 1000 - 60;
player.load(playlistUrl, {
startingPosition: date,
});
```
--------------------------------
### Load Content with Starting Position (Object - Relative)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Loading_a_content.md
Shows how to specify a relative starting position for playback using the `startingPosition` option as an object. Supports 'FromEnd' and 'FromBeginning' types.
```javascript
player.load(playlistUrl, {
startingPosition: {
startType: "FromEnd",
position: 10,
},
});
```
```javascript
player.load(playlistUrl, {
startingPosition: {
startType: "FromBeginning",
position: 10,
},
});
```
--------------------------------
### Add Rust Target and Dependencies
Source: https://github.com/peaberberian/wasp-hls/blob/main/README.md
Adds the wasm32-unknown-unknown target for Rust, essential for WebAssembly compilation. It also installs the wasm-bindgen CLI for facilitating Rust-to-JavaScript interoperability. Optionally, clippy can be installed for Rust code analysis.
```shell
rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli
rustup component add clippy
```
--------------------------------
### Load Content with Starting Position (Object - Absolute)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Loading_a_content.md
Illustrates setting an absolute starting position using the `startingPosition` option as an object with `startType: "Absolute"`. This provides precise control over the playback start time.
```javascript
player.load(playlistUrl, {
startingPosition: {
startType: "Absolute",
position: 30,
},
});
```
--------------------------------
### Install Wasp-hls Player Package
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
Installs the Wasp-hls package using npm or yarn. This is the first step to integrate the HLS player into your web application.
```bash
npm install wasp-hls
# or
yarn add wasp-hls
```
--------------------------------
### Build All Wasp-HLS Components
Source: https://github.com/peaberberian/wasp-hls/blob/main/README.md
Builds all core Wasp-HLS components (WebAssembly, Worker, Main API) without the demo. Also provides commands to build all components including the demo, and build everything in release mode for production.
```shell
# Build all core components (without demo)
npm run build:all
# Build all core components AND the demo
npm run build:all && npm run build:demo
# Build all core components AND the demo (optimized script)
npm run build:all:demo
# Build all components in release mode (Wasm + Worker + Main)
npm run build:release
# Build all components and demo in release mode
npm run build:demo:release
```
--------------------------------
### Build Demo Application
Source: https://github.com/peaberberian/wasp-hls/blob/main/README.md
Builds the demo application code found in the `demo/` directory into a JavaScript file (`build/demo.js`). It includes options for debug, release, and watch modes, the latter automatically rebuilding on file changes.
```shell
# Build in debug mode
npm run build:demo
# Build in debug mode with watch
npm run build:demo:watch
# Build in release mode
npm run build:demo:release
```
--------------------------------
### Load Content into WaspHlsPlayer
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Loading_a_content.md
This snippet demonstrates the basic usage of the `load` method to start playing content with a given Multivariant Playlist URL. It's a fundamental step after player instantiation and initialization.
```javascript
player.load(MultivariantPlaylistUrl);
```
--------------------------------
### Build Rust WebAssembly Code
Source: https://github.com/peaberberian/wasp-hls/blob/main/README.md
Builds the Rust code in the `src/rs-core/` directory into a WebAssembly file (`build/wasp_hls_bg.wasm`). Supports both debug and release modes, with release mode providing optimized code for production.
```shell
# Build in debug mode
npm run build:wasm
# Build in release mode
npm run build:wasm:release
```
--------------------------------
### Check Rust Code Quality with Clippy
Source: https://github.com/peaberberian/wasp-hls/blob/main/README.md
Runs Clippy, a Rust linter, to check for common mistakes and style issues in the Rust code. This command checks all Rust files within the project.
```shell
npm run clippy
```
--------------------------------
### Initialize WaspHlsPlayer with Worker and WASM URLs (JavaScript)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Basic_Methods/initialize.md
Initializes the WaspHlsPlayer by providing the URLs for the worker and WebAssembly files. An optional `initialBandwidth` can be supplied to influence the starting playback quality. This method returns a Promise that indicates the success or failure of the initialization process.
```javascript
const initializationPromise = player.initialize({
workerUrl,
wasmUrl
});
```
```javascript
const initializationPromise = player.initialize({
workerUrl,
wasmUrl,
initialBandwidth
});
```
--------------------------------
### Build Main TypeScript API Code
Source: https://github.com/peaberberian/wasp-hls/blob/main/README.md
Builds the main thread TypeScript code in `src/ts-main` into a JavaScript file (`build/main.js`). Similar to the worker build, it offers both debug and release modes for development and production.
```shell
# Build in debug mode
npm run build:main
# Build in release mode
npm run build:main:release
```
--------------------------------
### Format Code Automatically
Source: https://github.com/peaberberian/wasp-hls/blob/main/README.md
Formats code across different languages to ensure consistent style. Commands are provided for formatting TypeScript, JavaScript, Markdown, HTML, and Rust code, with a combined command for both.
```shell
# Format TypeScript, JavaScript, Markdown, and HTML files
npm run fmtt
# Format Rust code
npm run fmtr
# Format all supported files (TS, JS, MD, HTML, Rust)
npm run fmt
```
--------------------------------
### Auto-Resume Playback After Loading
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Loading_a_content.md
This example shows how to automatically resume playback using the `resume` method once the content has been successfully loaded, indicated by the 'Loaded' player state.
```javascript
// Automatically play the content once it's loaded
player.addEventlistener("playerStateChange", (playerState) => {
if (playerState === "Loaded") {
player.resume();
}
});
```
--------------------------------
### Load HLS Content with Wasp-hls Player (JavaScript)
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
Demonstrates various methods for loading HLS content using the Wasp-hls player. It covers basic loading, starting playback at an absolute time, from the beginning, and near the live edge. It also includes event listeners for monitoring player state changes and errors.
```javascript
// Basic load
player.load("https://example.com/playlist.m3u8");
// Load at absolute position (30 seconds)
player.load("https://example.com/playlist.m3u8", {
startingPosition: 30,
});
// Load at position relative to beginning (+10 seconds from start)
player.load("https://example.com/playlist.m3u8", {
startingPosition: {
startType: "FromBeginning",
position: 10,
},
});
// Load near live edge (10 seconds before maximum position)
player.load("https://example.com/live.m3u8", {
startingPosition: {
startType: "FromEnd",
position: 10,
},
});
// Monitor loading state
player.addEventListener("playerStateChange", (state) => {
console.log(`State changed: ${state}`); // "Loading", "Loaded", "Error", "Stopped"
});
player.addEventListener("error", (error) => {
console.error("Playback error:", error.name, error.message);
if (error.code) {
console.error("Error code:", error.code);
}
});
```
--------------------------------
### Load Content with Wasp HLS Player (JavaScript)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Basic_Methods/load.md
Demonstrates how to use the `load` method of the Wasp HLS player. The method can be called with just a URL to load content, or with an additional options object to specify parameters like the starting position.
```javascript
player.load(url);
player.load(url, {
startingPosition: initialWantedPosition,
});
```
--------------------------------
### Handle WaspOtherError in JavaScript
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Player_Errors.md
This example illustrates how to catch generic WaspOtherError instances. These errors encompass various issues not covered by more specific error types, such as problems attaching MediaSource or playlist parsing failures.
```javascript
player.addEventlistener("error", (error) => {
if (error.name === "WaspOtherError") {
// An uncategorized error happened
console.error("An unknown error occurred:", error.code);
}
});
```
--------------------------------
### Get Player State (JavaScript)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Basic_Methods/getPlayerState.md
Retrieves the current playback state of the Wasp HLS player. This method returns a string that can be 'Stopped', 'Loading', 'Loaded', or 'Error'.
```javascript
const playerState = player.getPlayerState();
```
--------------------------------
### Build TypeScript Worker Code
Source: https://github.com/peaberberian/wasp-hls/blob/main/README.md
Builds the TypeScript worker code located in `src/ts-worker` into a JavaScript file (`build/worker.js`). This process supports both debug and release builds, with the release build producing minified code.
```shell
# Build in debug mode
npm run build:worker
# Build in release mode
npm run build:worker:release
```
--------------------------------
### Check TypeScript Code Quality
Source: https://github.com/peaberberian/wasp-hls/blob/main/README.md
Checks the TypeScript files in the project for type correctness and code style violations using ESLint. Specific commands are available to check the entire project or individual parts like the worker, main API, or demo.
```shell
# Check all TypeScript files
npm run check
# Check only worker code
npm run check:worker
# Check only main API code
npm run check:main
# Check only demo code
npm run check:demo
```
--------------------------------
### Detect Rebuffering Start
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Player_Events.md
Listens for the 'rebufferingStarted' event, indicating that the player has begun to pause playback to buffer more media. This event is useful for UI indications that playback is temporarily unavailable due to buffering.
```javascript
player.addEventListener("rebufferingStarted", () => {
console.log("Playback is now paused due to a started rebuffering period");
});
```
--------------------------------
### Listen for Playback Ended Event in JavaScript
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Player_Events.md
Provides an example of how to listen for the 'ended' event, which signifies that the content has finished playing. This allows for actions such as displaying completion messages or transitioning to the next content.
```javascript
player.addEventListener("ended", () => {
console.log("Playback is now ended.");
});
```
--------------------------------
### Get Playback Speed with WaspHlsPlayer
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Speed_Control/getSpeed.md
Retrieves the last applied playback speed of the currently loaded content. Returns 1 if no content is loaded. The returned value is a number representing the playback pace.
```javascript
const speed = player.getSpeed();
```
--------------------------------
### Get Media Offset in JavaScript
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Position_Control/getMediaOffset.md
Retrieves the media offset from the WaspHlsPlayer. This offset is used to synchronize playlist time with media element time. It returns a number representing the offset or undefined if no content is loaded.
```javascript
const mediaOffset = player.getMediaOffset();
```
--------------------------------
### JavaScript Variant (Quality) Selection for Wasp-HLS Player
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
Control adaptive bitrate streaming quality by automatically or manually selecting video variants. This includes getting available variants, creating UI selectors, and listening for variant change events.
```javascript
const variants = player.getVariantList();
variants.forEach((variant) => {
console.log(`Variant ${variant.id}:`, {
width: variant.width, // pixels
height: variant.height, // pixels
frameRate: variant.frameRate, // fps
bandwidth: variant.bandwidth, // bits per second
});
});
function createQualitySelector() {
const select = document.createElement("select");
const autoOption = document.createElement("option");
autoOption.value = "auto";
autoOption.textContent = "Auto";
select.appendChild(autoOption);
variants.forEach((variant) => {
const option = document.createElement("option");
option.value = variant.id;
option.textContent = `${variant.height}p - ${(variant.bandwidth / 1000000).toFixed(1)} Mbps`;
select.appendChild(option);
});
select.addEventListener("change", (e) => {
if (e.target.value === "auto") {
player.unlockVariant();
} else {
player.lockVariant(parseInt(e.target.value));
}
});
return select;
}
player.addEventListener("variantUpdate", (variant) => {
if (variant) {
console.log(`Now loading: ${variant.width}x${variant.height} @ ${variant.bandwidth} bps`);
updateQualityIndicator(variant);
}
});
player.addEventListener("variantLockUpdate", (variant) => {
if (variant) {
console.log(`Quality locked to: ${variant.height}p`);
} else {
console.log("Quality unlocked (auto)");
}
});
player.addEventListener("variantListUpdate", (variants) => {
console.log(`Available qualities updated: ${variants.length} options`);
rebuildQualitySelector(variants);
});
const currentVariant = player.getCurrentVariant();
if (currentVariant) {
console.log(`Current: ${currentVariant.width}x${currentVariant.height}`);
}
const lockedVariant = player.getLockedVariant();
if (lockedVariant) {
console.log(`Locked at: ${lockedVariant.height}p`);
}
```
--------------------------------
### Get Minimum Playable Position - JavaScript
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Position_Control/getMinimumPosition.md
Retrieves the minimum playlist position in seconds where playable data is currently available. This method is useful for determining the seekable range of the media content. It returns undefined if no content is loaded.
```javascript
const minimumPosition = player.getMinimumPosition();
```
--------------------------------
### Get Maximum Playable Position (JavaScript)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Position_Control/getMaximumPosition.md
Retrieves the maximum playlist position in seconds where playable data is currently available. Returns undefined if no content is loaded. This value represents the last reachable position in the media playlist.
```javascript
const maximumPosition = player.getMaximumPosition();
```
--------------------------------
### Get Audio Track List - JavaScript
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Audio_Track_Selection/getAudioTrackList.md
Retrieves a list of available audio tracks for the currently loaded media content. Each track object includes details such as ID, language, associated language, human-readable name, and channel count. Returns an empty array if no content is loaded or no audio tracks are available/identified.
```javascript
const audioTracks = player.getAudioTrackList();
```
--------------------------------
### Get Current Audio Track Information (JavaScript)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Audio_Track_Selection/getCurrentAudioTrack.md
Retrieves details about the currently selected audio track. This method returns an object containing the audio track's ID, language, associated language, name, and channel count. It returns undefined if no content is loaded, or if the content lacks audio tracks or their information is unknown.
```javascript
const currentAudioTrack = player.getCurrentAudioTrack();
```
--------------------------------
### Get Locked HLS Variant with JavaScript
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Variant_Selection/getLockedVariant.md
Retrieves the characteristics of the currently locked HLS variant from the WaspHlsPlayer. Returns an object with variant details (id, width, height, frameRate, bandwidth) or null if no variant is locked. This operation is asynchronous.
```javascript
const variant = player.getLockedVariant();
```
--------------------------------
### Get Current Playback Position (JavaScript)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Position_Control/getPosition.md
Retrieves the current playback position in seconds using playlist time. This value advances linearly with playback speed when not paused or rebuffering. Returns 0 if no content is loaded. This method is part of the WaspHlsPlayer API.
```javascript
const position = player.getPosition();
```
--------------------------------
### Get Current Buffer Gap in JavaScript
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Position_Control/getCurrentBufferGap.md
This JavaScript code snippet demonstrates how to retrieve the current buffer gap from a WaspHlsPlayer instance. The buffer gap represents the seconds of playback available before potential rebuffering occurs. It returns a number indicating seconds, or 0 if no data is buffered.
```javascript
const bufferGap = player.getCurrentBufferGap();
```
--------------------------------
### Get Media Duration with Wasp HLS Player
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Position_Control/getMediaDuration.md
This snippet demonstrates how to call the getMediaDuration method on a WaspHlsPlayer instance to retrieve the content's duration in playlist time. The returned value is a number representing seconds or NaN if no content is loaded.
```javascript
const duration = player.getMediaDuration();
```
--------------------------------
### Get HLS Variant List - JavaScript
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Variant_Selection/getVariantList.md
Retrieves the list of available HLS variants for the loaded content. This method is useful for inspecting variant characteristics and potentially locking a specific variant. It returns an empty array if no content is loaded or variant information is unknown.
```javascript
const variants = player.getVariantList();
```
--------------------------------
### Get Current HLS Variant Information (JavaScript)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Variant_Selection/getCurrentVariant.md
Retrieves an object containing details about the currently active HLS variant. This object includes properties like id, width, height, frameRate, and bandwidth. Returns undefined if no content is loaded or the variant is not yet known. This method is useful for inspecting or locking the current playback quality.
```javascript
const currentVariant = player.getCurrentVariant();
```
--------------------------------
### Initialize WaspHlsPlayer with Served Worker and WASM Files
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/Getting_Started/Creating_a_WaspHlsPlayer.md
Initializes the WaspHlsPlayer by providing URLs for the worker and WebAssembly files. This method requires these files to be served via HTTP(S). The initialization returns a Promise that resolves on success or rejects on error. Bandwidth estimation can also be provided.
```javascript
player
.initialize({
workerUrl: "https://www.example.com/worker.js",
wasmUrl: "https://www.example.com/wasp_hls_bg.wasm",
})
.then(
() => {
console.log("WaspHlsPlayer initialized with success!");
},
(err) => {
console.error("Could not initialize WaspHlsPlayer:", err);
},
);
```
--------------------------------
### Initialize WaspHlsPlayer with Hosted Files
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Initialization.md
Initializes the WaspHlsPlayer by providing URLs to externally hosted worker and WebAssembly files. This method allows for separate hosting of these essential components. It returns a promise that resolves on successful initialization or rejects on failure.
```javascript
player
.initialize({
// URL to the worker file
workerUrl: "https://www.example.com/worker.js",
// URL to the WebAssembly file
wasmUrl: "https://www.example.com/wasp_hls_bg.wasm",
// Optional initial bandwidth estimate, in bits per seconds.
// Will be relied on before the `WaspHlsPlayer` is able to produce its own
// precize estimate.
// Can be unset or undefined to let the `WaspHlsPlayer` define its own,
// poor, initial value.
initialBandwidth: 200000,
})
.then(
() => {
console.log("WaspHlsPlayer initialized with success!");
},
(err) => {
console.error("Could not initialize WaspHlsPlayer:", err);
},
);
```
--------------------------------
### Initialize and Load HLS Content
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
Demonstrates the usage of the VideoPlayer class, including initialization, content loading, and awaiting the initialization process. It selects the video and UI elements from the DOM.
```javascript
// Usage
const videoEl = document.querySelector("video");
const uiEl = document.querySelector(".player-ui");
const player = new VideoPlayer(videoEl, uiEl);
await player.initialize();
player.loadContent("https://example.com/playlist.m3u8");
```
--------------------------------
### Manage Audio Tracks with Wasp-HLS Player
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
Demonstrates how to retrieve, display, and select available audio tracks using the Wasp-HLS Player API. It covers fetching track information, creating a UI element for selection, and handling track change events. Dependencies include the player instance and DOM manipulation.
```javascript
// Get available audio tracks
const audioTracks = player.getAudioTrackList();
audioTracks.forEach((track) => {
console.log(`Track ${track.id}:`, {
name: track.name,
language: track.language, // e.g., "en", "es", "fr"
assocLanguage: track.assocLanguage,
channels: track.channels, // e.g., 2 for stereo, 6 for 5.1
});
});
// Create audio track selector
function createAudioSelector() {
const select = document.createElement("select");
// Default option
const defaultOption = document.createElement("option");
defaultOption.value = "default";
defaultOption.textContent = "Default";
select.appendChild(defaultOption);
// Track options
audioTracks.forEach((track) => {
const option = document.createElement("option");
option.value = track.id;
const channelInfo = track.channels ? ` (${track.channels}ch)` : "";
option.textContent = `${track.name}${channelInfo} [${track.language}]`;
select.appendChild(option);
});
select.addEventListener("change", (e) => {
if (e.target.value === "default") {
player.setAudioTrack(null); // Use content default
} else {
player.setAudioTrack(parseInt(e.target.value));
}
});
return select;
}
// Set audio track
player.setAudioTrack(2); // Set to track with id=2
player.setAudioTrack(null); // Revert to content default
// Monitor audio track changes
player.addEventListener("audioTrackUpdate", (track) => {
if (track) {
console.log(`Audio track changed to: ${track.name} (${track.language})`);
updateAudioIndicator(track);
} else {
console.log("No audio track active");
}
});
player.addEventListener("audioTrackListUpdate", (tracks) => {
console.log(`Available audio tracks updated: ${tracks.length} options`);
rebuildAudioSelector(tracks);
});
// Get current audio track
const currentTrack = player.getCurrentAudioTrack();
if (currentTrack) {
console.log(`Current audio: ${currentTrack.name} (${currentTrack.language})`);
}
```
--------------------------------
### Initialize WaspHlsPlayer with Embedded Worker and WASM
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/Getting_Started/Welcome.md
This JavaScript snippet demonstrates the basic initialization of the WaspHlsPlayer. It requires the video element, embedded worker URL, and embedded WASM URL. The primary output is a player instance ready to load HLS content, with error handling for initialization failures.
```js
import WaspHlsPlayer from "wasp-hls";
import EmbeddedWasm from "wasp-hls/wasm";
import EmbeddedWorker from "wasp-hls/worker";
const player = new WaspHlsPlayer(videoElement);
player
.initialize({
workerUrl: EmbeddedWorker,
wasmUrl: EmbeddedWasm,
})
.catch((err) => {
console.error("Could not initialize WaspHlsPlayer:", err);
});
player.load(HLS_MULTIVARIANT_PLAYLIST_URL);
```
--------------------------------
### Instantiate WaspHlsPlayer with Video Element
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/Getting_Started/Creating_a_WaspHlsPlayer.md
Creates a new instance of WaspHlsPlayer, requiring a video element as its primary argument. An optional second argument can be used to override initial configuration settings. Further details on the constructor can be found in the API documentation.
```javascript
const player = new WaspHlsPlayer(videoElement);
```
--------------------------------
### Initialize Wasp-hls Player with Separate Files (JavaScript)
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
Sets up the Wasp-hls player for production by specifying separate URLs for the Web Worker and WebAssembly files. This approach allows for better asset management and CDN integration. It also demonstrates advanced player configuration options like buffer goal and segment request timeouts.
```javascript
import WaspHlsPlayer from "wasp-hls";
const videoElement = document.querySelector("video");
const player = new WaspHlsPlayer(videoElement, {
bufferGoal: 20, // seconds of buffer to maintain
segmentRequestTimeout: 10000, // 10 seconds
segmentMaxRetry: 5,
});
await player.initialize({
workerUrl: "https://cdn.example.com/worker.js",
wasmUrl: "https://cdn.example.com/wasp_hls_bg.wasm",
initialBandwidth: 5000000, // 5 Mbps
});
player.load("https://example.com/master.m3u8", {
startingPosition: { startType: "FromEnd", position: 10 }, // 10s before live edge
});
```
--------------------------------
### Instantiate WaspHlsPlayer with Video Element and Configuration (JavaScript)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Instantiation.md
Instantiates a WaspHlsPlayer with both the HTMLVideoElement and an optional configuration object. The configuration allows customization of player behavior, such as buffer goals and segment request timeouts. Default values are applied if not all configuration keys are provided.
```javascript
const config = {
bufferGoal: 20,
segmentRequestTimeout: 10,
};
const player = new WaspHlsPlayer(videoElement, config);
```
--------------------------------
### Instantiate WaspHlsPlayer with Video Element (JavaScript)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Instantiation.md
Instantiates a WaspHlsPlayer by providing the HTMLVideoElement. This is the fundamental step to initialize the player for HLS content. No external dependencies are explicitly mentioned for this basic instantiation.
```javascript
import WaspHlsPlayer from "wasp-hls";
const videoElement = document.querySelector("video");
const player = new WaspHlsPlayer(videoElement);
```
--------------------------------
### Initialize WaspHlsPlayer with Embedded Worker and WASM Files
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/Getting_Started/Creating_a_WaspHlsPlayer.md
Initializes the WaspHlsPlayer using embedded JavaScript versions of the worker and WebAssembly files. This is convenient for development but can lead to larger file sizes and minor inefficiencies. The initialization returns a Promise that resolves on success or rejects on error.
```javascript
import EmbeddedWasm from "wasp-hls/wasm";
import EmbeddedWorker from "wasp-hls/worker";
player
.initialize({
workerUrl: EmbeddedWorker,
wasmUrl: EmbeddedWasm,
})
.then(
() => {
console.log("WaspHlsPlayer initialized with success!");
},
(err) => {
console.error("Could not initialize WaspHlsPlayer:", err);
},
);
```
--------------------------------
### Update Wasp-HLS Player Configuration at Runtime
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
Illustrates how to initialize the Wasp-HLS Player with specific configuration options and subsequently update these settings dynamically during playback. This is useful for adapting to network conditions or user preferences. The code requires a video element and the WaspHlsPlayer class.
```javascript
// Create player with initial config
const player = new WaspHlsPlayer(videoElement, {
bufferGoal: 15, // seconds
segmentMaxRetry: 5,
segmentRequestTimeout: 20000, // milliseconds
segmentBackoffBase: 300, // milliseconds
segmentBackoffMax: 2000, // milliseconds
multiVariantPlaylistMaxRetry: 2,
multiVariantPlaylistRequestTimeout: 15000,
multiVariantPlaylistBackoffBase: 300,
multiVariantPlaylistBackoffMax: 2000,
mediaPlaylistMaxRetry: 3,
mediaPlaylistRequestTimeout: 15000,
mediaPlaylistBackoffBase: 300,
mediaPlaylistBackoffMax: 2000,
});
// Update config at runtime
player.updateConfig({
bufferGoal: 30, // Increase buffer for unstable connections
segmentRequestTimeout: 30000, // More patient with slow servers
});
// Adaptive config based on network
function adjustForNetworkType(type) {
switch (type) {
case "slow-2g":
case "2g":
player.updateConfig({
bufferGoal: 10,
segmentRequestTimeout: 40000,
segmentMaxRetry: 10,
});
break;
case "3g":
player.updateConfig({
bufferGoal: 15,
segmentRequestTimeout: 25000,
segmentMaxRetry: 5,
});
break;
case "4g":
case "5g":
player.updateConfig({
bufferGoal: 20,
segmentRequestTimeout: 15000,
segmentMaxRetry: 3,
});
break;
}
}
// Get current config
const config = player.getConfig();
console.log("Current buffer goal:", config.bufferGoal);
console.log("Segment retry limit:", config.segmentMaxRetry);
```
--------------------------------
### Complete Wasp-HLS Player Implementation in JavaScript
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
This JavaScript code provides a comprehensive implementation of a video player using the Wasp-HLS library. It handles player initialization with WebAssembly and Worker support, content loading, playback controls (play, pause, seek), UI updates for state, buffering, content information, and adaptive streaming quality/audio track selection. It also includes error handling.
```javascript
import WaspHlsPlayer from "wasp-hls";
import EmbeddedWasm from "wasp-hls/wasm";
import EmbeddedWorker from "wasp-hls/worker";
class VideoPlayer {
constructor(videoElement, uiContainer) {
this.video = videoElement;
this.ui = uiContainer;
this.player = new WaspHlsPlayer(videoElement, {
bufferGoal: 20,
segmentMaxRetry: 5,
segmentRequestTimeout: 20000,
});
this.setupUI();
this.attachEventListeners();
}
async initialize() {
try {
await this.player.initialize({
workerUrl: EmbeddedWorker,
wasmUrl: EmbeddedWasm,
initialBandwidth: 3000000,
});
console.log("Player ready");
} catch (error) {
this.showError("Failed to initialize player", error);
throw error;
}
}
loadContent(url, startPosition = undefined) {
this.player.load(url, { startingPosition: startPosition });
}
attachEventListeners() {
// Playback state
this.player.addEventListener("playerStateChange", (state) => {
this.updateUIState(state);
if (state === "Loaded") {
this.onContentLoaded();
}
});
this.player.addEventListener("playing", () => {
this.playButton.textContent = "⏸";
});
this.player.addEventListener("paused", () => {
this.playButton.textContent = "▶";
});
this.player.addEventListener("ended", () => {
this.showReplayButton();
});
// Buffering
this.player.addEventListener("rebufferingStarted", () => {
this.spinner.style.display = "block";
});
this.player.addEventListener("rebufferingEnded", () => {
this.spinner.style.display = "none";
});
// Content info
this.player.addEventListener("contentInfoUpdate", (info) => {
this.updateSeekBar(info.minimumPosition, info.maximumPosition);
this.liveIndicator.style.display = info.isLive ? "block" : "none";
});
// Quality
this.player.addEventListener("variantUpdate", (variant) => {
if (variant) {
this.qualityLabel.textContent = `${variant.height}p`;
}
});
this.player.addEventListener("variantListUpdate", (variants) => {
this.populateQualityMenu(variants);
});
// Audio
this.player.addEventListener("audioTrackUpdate", (track) => {
if (track) {
this.audioLabel.textContent = track.language.toUpperCase();
}
});
this.player.addEventListener("audioTrackListUpdate", (tracks) => {
this.populateAudioMenu(tracks);
});
// Errors
this.player.addEventListener("error", (error) => {
this.showError("Playback error", error);
});
this.player.addEventListener("warning", (error) => {
console.warn("Warning:", error);
});
}
setupUI() {
this.playButton = this.ui.querySelector(".play-button");
this.seekBar = this.ui.querySelector(".seek-bar");
this.timeDisplay = this.ui.querySelector(".time-display");
this.qualityMenu = this.ui.querySelector(".quality-menu");
this.audioMenu = this.ui.querySelector(".audio-menu");
this.spinner = this.ui.querySelector(".spinner");
this.qualityLabel = this.ui.querySelector(".quality-label");
this.audioLabel = this.ui.querySelector(".audio-label");
this.liveIndicator = this.ui.querySelector(".live-indicator");
this.playButton.addEventListener("click", () => this.togglePlayPause());
this.seekBar.addEventListener("input", (e) => this.seek(e.target.value));
// Update time display periodically
setInterval(() => this.updateTimeDisplay(), 200);
}
togglePlayPause() {
if (this.player.isPaused()) {
this.player.resume().catch((e) => console.error("Resume failed:", e));
} else {
this.player.pause();
}
}
seek(position) {
const pos = parseFloat(position);
this.player.seek(pos);
}
updateTimeDisplay() {
if (this.player.getPlayerState() !== "Loaded") return;
const position = this.player.getPosition();
const duration = this.player.getMediaDuration();
this.timeDisplay.textContent = `${this.formatTime(position)} / ${this.formatTime(duration)}`;
this.seekBar.value = position;
this.seekBar.max = duration;
}
formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs.toString().padStart(2, "0")}`;
}
populateQualityMenu(variants) {
this.qualityMenu.innerHTML = '';
variants.forEach((v) => {
const option = document.createElement("option");
option.value = v.id;
option.textContent = `${v.height}p`;
this.qualityMenu.appendChild(option);
});
this.qualityMenu.addEventListener("change", (e) => {
if (e.target.value === "auto") {
this.player.unlockVariant();
} else {
this.player.lockVariant(parseInt(e.target.value));
}
});
}
}
```
--------------------------------
### Initialize Wasp-hls Player with Embedded Files (JavaScript)
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
Initializes the Wasp-hls player using embedded WebAssembly and Web Worker files. This method is suitable for quick integration and development, providing a straightforward way to set up the player with minimal configuration. It loads HLS content after successful initialization.
```javascript
import WaspHlsPlayer from "wasp-hls";
import EmbeddedWasm from "wasp-hls/wasm";
import EmbeddedWorker from "wasp-hls/worker";
const videoElement = document.querySelector("video");
const player = new WaspHlsPlayer(videoElement);
player
.initialize({
workerUrl: EmbeddedWorker,
wasmUrl: EmbeddedWasm,
initialBandwidth: 2000000, // optional: 2 Mbps initial estimate
})
.then(() => {
console.log("Player initialized successfully");
player.load("https://example.com/playlist.m3u8");
})
.catch((err) => {
console.error("Initialization failed:", err);
});
// Auto-play when loaded
player.addEventListener("playerStateChange", (state) => {
if (state === "Loaded") {
player.resume().catch(console.error);
}
});
```
--------------------------------
### Initialize WaspHlsPlayer with Embedded Files
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Initialization.md
Initializes the WaspHlsPlayer using embedded worker and WebAssembly files directly from the 'wasp-hls' package. This approach avoids the need to serve these files separately but may increase the initial file size and introduce minor initialization inefficiencies.
```javascript
import EmbeddedWasm from "wasp-hls/wasm";
import EmbeddedWorker from "wasp-hls/worker";
player
.initialize({
workerUrl: EmbeddedWorker,
wasmUrl: EmbeddedWasm,
initialBandwidth: 200000,
})
.then(
() => {
console.log("WaspHlsPlayer initialized with success!");
},
(err) => {
console.error("Could not initialize WaspHlsPlayer:", err);
},
);
```
--------------------------------
### Listen for Player State Changes
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Loading_a_content.md
This code illustrates how to subscribe to the `playerStateChange` event to monitor the loading progress and status of the content. It handles different states like 'Loading', 'Loaded', 'Error', and 'Stopped'.
```javascript
player.addEventlistener("playerStateChange", (playerState) => {
switch (playerState) {
case "Loading":
console.log("A new content is loading.");
break;
case "Loaded":
console.log("The last loaded content is currently loaded.");
break;
case "Error":
console.log(
"The last loaded content cannot play anymore due to an error.",
);
break;
case "Stopped":
console.log("No content is currently loaded nor loading.");
break;
}
});
```
--------------------------------
### Populate Audio Menu and Handle Selection
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
Dynamically populates an audio selection menu with available tracks from the player and adds an event listener to update the audio track on user selection. It handles the 'default' option to disable audio track selection.
```javascript
populateAudioMenu(tracks) {
this.audioMenu.innerHTML = '';
tracks.forEach((t) => {
const option = document.createElement("option");
option.value = t.id;
option.textContent = `${t.name} (${t.language})`;
this.audioMenu.appendChild(option);
});
this.audioMenu.addEventListener("change", (e) => {
const value = e.target.value;
this.player.setAudioTrack(value === "default" ? null : parseInt(value));
});
}
```
--------------------------------
### Update Player Configuration (JavaScript)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Configuration_Object.md
Demonstrates how to update a specific configuration property, such as 'bufferGoal', on an existing WaspHlsPlayer instance. This method allows dynamic adjustment of player settings while content is playing. Note that updates are not synchronous due to worker processing.
```javascript
player.updateConfig({
bufferGoal: 20,
});
```
--------------------------------
### Log Content Load Details
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
Logs the number of available video qualities (variants) and audio tracks after the content has been loaded. This is useful for debugging and understanding the loaded stream's capabilities.
```javascript
onContentLoaded() {
const variants = this.player.getVariantList();
const audioTracks = this.player.getAudioTrackList();
console.log(`Loaded: ${variants.length} qualities, ${audioTracks.length} audio tracks`);
}
```
--------------------------------
### Handle Player State Changes in JavaScript
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Player_Events.md
Illustrates how to listen for the 'playerStateChange' event to detect when a content is loaded and ready to play, subsequently triggering an automatic playback resume. This pattern is useful for implementing auto-play functionalities.
```javascript
player.addEventListener("playerStateChange", (state) => {
if (state === "Loaded") {
// auto-play when loaded
player.resume();
}
});
```
--------------------------------
### JavaScript Event Handling for Wasp-HLS Player
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
Implement comprehensive event listeners for various player states and updates. This includes handling playback start/pause/end, rebuffering events, content information changes, warnings, and variant updates.
```javascript
player.addEventListener("playing", () => {
console.log("Playback started");
updatePlayButton("pause");
});
player.addEventListener("paused", () => {
console.log("Playback paused");
updatePlayButton("play");
});
player.addEventListener("ended", () => {
console.log("Playback ended");
showReplayButton();
});
player.addEventListener("rebufferingStarted", () => {
showSpinner();
});
player.addEventListener("rebufferingEnded", () => {
hideSpinner();
});
player.addEventListener("contentInfoUpdate", (info) => {
console.log("Content info:", {
minimumPosition: info.minimumPosition,
maximumPosition: info.maximumPosition,
isLive: info.isLive,
isVod: info.isVod,
});
updateSeekBar(info);
});
player.addEventListener("warning", (error) => {
console.warn("Non-fatal error:", error.message);
});
```
--------------------------------
### WaspHlsPlayer addEventListener Syntax (JavaScript)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Basic_Methods/addEventListener.md
This snippet shows the basic syntax for the addEventListener method in JavaScript. It takes the event name as a string and a callback function as arguments. The callback receives the event payload. This method is part of the WaspHlsPlayer API.
```javascript
player.addEventListener(event, callback);
```
--------------------------------
### Resume playback with WaspHlsPlayer
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Basic_Methods/resume.md
Un-pauses the currently loaded content using the `resume` method. This method is equivalent to a video element's `play` method and can only be invoked when the `WaspHlsPlayer` instance is in the 'Loaded' state. The returned Promise may reject if playback is blocked.
```javascript
const promise = player.resume();
promise.catch((err) => {
console.warn("Impossible to play:", err);
});
```
--------------------------------
### Check WaspHlsPlayer Initialization Status
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Initialization.md
Provides a way to check the current initialization status of the WaspHlsPlayer instance. The `initializationStatus` property can be one of several states: 'Uninitialized', 'Initializing', 'Initialized', 'errored', or 'disposed'.
```javascript
switch (player.initializationStatus) {
case "Uninitialized":
console.log("The WaspHlsPlayer has never been initialized.");
break;
case "Initializing":
console.log("The WaspHlsPlayer is currently initializing.");
break;
case "Initialized":
console.log("The WaspHlsPlayer has been initialized with success.");
break;
case "errored":
console.log("The WaspHlsPlayer's initialization has failed.");
break;
case "disposed":
console.log("The WaspHlsPlayer's instance has been disposed.");
break;
}
```
--------------------------------
### Handle Wasp-HLS Player Errors and Warnings (JavaScript)
Source: https://context7.com/peaberberian/wasp-hls/llms.txt
This JavaScript code demonstrates how to handle fatal errors and non-fatal warnings from the Wasp-HLS player. It includes specific checks for different error types like multivariant playlist request errors, segment request errors, initialization errors, and source buffer errors. It also shows how to display user-friendly messages for these errors and warnings.
```javascript
// Fatal errors (stop playback)
player.addEventListener("error", (error) => {
console.error("Fatal error:", error);
// Check error type
if (error.name === "WaspMultivariantPlaylistRequestError") {
console.error("Failed to load playlist:", error.url);
console.error("HTTP status:", error.status);
showError("Cannot load video playlist");
} else if (error.name === "WaspSegmentRequestError") {
console.error("Segment request failed:", error.url);
showError("Video loading error");
} else if (error.name === "WaspInitializationError") {
console.error("Player initialization failed:", error.code);
showError("Player cannot start");
} else if (error.name === "WaspSourceBufferError") {
console.error("Media buffer error:", error.sourceBufferType);
showError("Media playback error");
}
// Get error from player
const storedError = player.getError();
console.log("Stored error matches:", storedError === error);
});
// Non-fatal warnings
player.addEventListener("warning", (error) => {
console.warn("Warning (playback continues):", error);
showWarningToast(error.message);
});
// Initialization error handling
player.initialize({
workerUrl: EmbeddedWorker,
wasmUrl: EmbeddedWasm,
}).catch((initError) => {
if (initError.code === 0) {
console.error("Unknown initialization error");
} else if (initError.code === 1) {
console.error("Worker loading failed");
} else if (initError.code === 2) {
console.error("WASM loading failed:", initError.wasmHttpStatus);
} else if (initError.code === 3) {
console.error("WASM compilation failed");
}
showError("Player initialization failed");
});
// Check initialization status
switch (player.initializationStatus) {
case "Uninitialized":
console.log("Not initialized yet");
break;
case "Initializing":
console.log("Initialization in progress");
break;
case "Initialized":
console.log("Ready to play");
break;
case "errored":
console.log("Initialization failed");
break;
case "disposed":
console.log("Player disposed");
break;
}
```
--------------------------------
### Update Configuration by Ignoring Properties using updateConfig (JavaScript)
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Basic_Methods/updateConfig.md
Illustrates updating a configuration property (segmentMaxRetry) while explicitly ignoring others (bufferGoal) by setting them to undefined. This method is useful when you only want to change specific settings and ensure others remain untouched. The player instance is the primary dependency.
```javascript
player.updateConfig({
bufferGoal: undefined,
segmentMaxRetry: 3,
});
```
--------------------------------
### Handle WaspSourceBufferCreationError in JavaScript
Source: https://github.com/peaberberian/wasp-hls/blob/main/doc/API/Player_Errors.md
This snippet demonstrates how to listen for and identify WaspSourceBufferCreationError events from the WaspHlsPlayer. This error occurs when the player fails to create a SourceBuffer, often due to unsupported media types.
```javascript
player.addEventlistener("error", (error) => {
if (error.name === "WaspSourceBufferCreationError") {
// An error happened when creating a SourceBuffer
console.error("SourceBuffer creation failed:", error.mediaType);
}
});
```