### Full Quick Start Example Source: https://github.com/canalplus/rx-player/blob/dev/doc/Getting_Started/Tutorials/Quick_Start.md A comprehensive example demonstrating RxPlayer instantiation, content loading, error handling, and basic playback control (play/pause) triggered by user interaction. ```javascript import RxPlayer from "rx-player"; // take the first video element on the page const videoElement = document.querySelector("video"); const player = new RxPlayer({ videoElement }); player.addEventListener("error", (err) => { console.log("the content stopped with the following error", err); }); player.addEventListener("playerStateChange", (state) => { if (state === "LOADED") { console.log("the content is loaded"); // toggle between play and pause when the user clicks on the video videoElement.onclick = function () { if (player.getPlayerState() === "PLAYING") { player.pause(); } else { player.play(); } }; } }); player.loadVideo({ url: "http://vm2.dashif.org/livesim-dev/segtimeline_1/testpic_6s/Manifest.mpd", transport: "dash", autoPlay: true, }); ``` -------------------------------- ### Example: Getting Text Tracks for the First Period Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Track_Selection/getAvailableTextTracks.md Demonstrates how to get the list of available text tracks for the first period of the content. This involves first retrieving all available periods and then selecting the first one. ```javascript // example: getting the text track list for the first Period const periods = rxPlayer.getAvailablePeriods(); console.log(rxPlayer.getAvailableTextTracks(periods[0].id); ``` -------------------------------- ### Complete Example: Minimal RxPlayer with DASH and SMOOTH Source: https://github.com/canalplus/rx-player/blob/dev/doc/Getting_Started/Minimal_Player.md A complete example demonstrating the import of MinimalRxPlayer and the addition of DASH and SMOOTH features. ```javascript import MinimalRxPlayer from "rx-player/minimal"; import { DASH, SMOOTH } from "rx-player/features"; MinimalRxPlayer.addFeatures([DASH, SMOOTH]); ``` -------------------------------- ### Example: Getting Locked Representations for the First Period Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Representation_Selection/getLockedAudioRepresentations.md This example demonstrates how to retrieve locked audio representations for a specific period by first getting available periods and then passing the ID of the first period to the `getLockedAudioRepresentations` method. ```javascript // example: getting Representations locked for the first Period const periods = rxPlayer.getAvailablePeriods(); console.log(rxPlayer.getLockedAudioRepresentations(periods[0].id); ``` -------------------------------- ### Start Local Development Server Source: https://github.com/canalplus/rx-player/blob/dev/CONTRIBUTING.md Builds the demo page and starts a local HTTP server on port 8000. It automatically rebuilds when RxPlayer or demo files change. Manual page refresh is required. ```sh npm run start ``` -------------------------------- ### Complete Event Handling Example Source: https://github.com/canalplus/rx-player/blob/dev/doc/Getting_Started/Tutorials/EventStream_Handling.md A comprehensive example demonstrating how to listen for 'streamEvent' and 'streamEventSkip' events. It logs event details, checks for DASH EventStream types, and sets up `onExit` callbacks for events with durations. ```javascript rxPlayer.addEventListener("streamEvent", (evt) => { console.log("An event has been reached:", evt); console.log("This is an event of type:", evt.data.type); if (evt.data.type === "dash-event-stream") { console.log("This is a DASH EventStream's Event element."); console.log("schemeIdUri:", evt.data.schemeIdUri); console.log(" element:", evt.data.element); } if (evt.end !== undefined) { evt.onExit = () => { console.log("An event has been exited:", evt); }; } }); rxPlayer.addEventListener("streamEventSkip", (evt) => { console.log("We just 'skipped' an event:", evt); console.log("This was an event of type:", evt.data.type); // ... }); ``` -------------------------------- ### Install Dependencies Source: https://github.com/canalplus/rx-player/blob/dev/README.md Install project dependencies using npm. This is a prerequisite for running development scripts. ```bash npm install ``` -------------------------------- ### Log Current Position and Duration Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Basic_Methods/getMediaDuration.md This example demonstrates how to get both the current playback position and the media duration, then log them to the console. Use this to understand the current state of playback relative to the total content duration. ```javascript const pos = player.getPosition(); const dur = player.getMediaDuration(); console.log(`current position: ${pos} / ${dur}`); ``` -------------------------------- ### Player State Example Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Basic_Methods/getPlayerState.md This example demonstrates how to use a switch statement to handle all possible player states returned by getPlayerState. It logs a message to the console for each state. ```javascript switch (player.getPlayerState()) { case "STOPPED": console.log("No content is/will be playing"); break; case "LOADING": console.log("A new content is currently loading"); break; case "LOADED": console.log("The new content is loaded and ready to be played"); break; case "PLAYING": console.log("The player is currently playing"); break; case "PAUSED": console.log("The player is currently paused"); break; case "BUFFERING": console.log("The player is paused while buffering new data"); break; case "FREEZING": console.log("The player is frozen"); break; case "SEEKING": console.log("The player is still seeking, waiting for new data"); break; case "ENDED": console.log("The player has reached the end of the content."); break; case "RELOADING": console.log("The player is currently reloading the content"); break; default: console.log("This is impossible!"); break; } ``` -------------------------------- ### Canal Release Versioning Example Source: https://github.com/canalplus/rx-player/blob/dev/doc/contributing/releases.md Example of versioning for RxPlayer 'canal' releases, which follow the same pattern as 'dev' releases but use '-canal' instead of '-dev'. ```plaintext 3.30.2-canal.2023042500 ``` -------------------------------- ### Get Audio Representation for the First Period Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Representation_Selection/getAudioRepresentation.md This example demonstrates how to retrieve the audio representation for the first available period by first getting all available periods and then accessing the first one's ID. ```javascript const periods = rxPlayer.getAvailablePeriods(); console.log(rxPlayer.getAudioRepresentation(periods[0].id); ``` -------------------------------- ### Play Closer to Live Edge Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Miscellaneous/Low_Latency.md To play a low-latency content even closer to the live edge, use the `startAt` option with `fromLivePosition`. This example sets the playback to start 2 seconds from the live edge. Be aware that this may increase the risk of rebuffering. ```javascript rxPlayer.loadVideo({ url: "https://www.example.com/content.mpd", transport: "dash", lowLatencyMode: true, startAt: { fromLivePosition: 2 }, // Play 2 seconds from the live edge instead // (beware of much more frequent rebuffering // risks) }); ``` -------------------------------- ### Alpha, Beta, and RC Release Versioning Examples Source: https://github.com/canalplus/rx-player/blob/dev/doc/contributing/releases.md Examples of versioning for RxPlayer alpha, beta, and release candidate (rc) pre-releases, indicating the target official version and release type. ```plaintext v5.0.0-alpha.0 v5.0.0-alpha.2 v5.0.0-beta.1 v5.0.0-rc.1 ``` -------------------------------- ### Dev Release Versioning Examples Source: https://github.com/canalplus/rx-player/blob/dev/doc/contributing/releases.md Examples of versioning for RxPlayer 'dev' releases, including patches, date, and daily increment. These are pre-releases for testing. ```plaintext 3.30.2-dev.2023042500 3.30.2-dev.2023042501 3.36.0-dev.2023060100 ``` -------------------------------- ### Official Release Versioning Examples Source: https://github.com/canalplus/rx-player/blob/dev/doc/contributing/releases.md Examples of versioning for official RxPlayer releases following semantic versioning (MAJOR.MINOR.PATCH). ```plaintext 3.30.1 1.2.1 4.0.0 ``` -------------------------------- ### Load Video from First Position Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Loading_a_Content.md Use `startAt.fromFirstPosition` to start playback a specified number of seconds after the beginning of the available buffer. This is useful for live content or when precise VOD start times are not critical. ```javascript // using fromFirstPosition player.loadVideo({ // ... startAt: { fromFirstPosition: 30, // 30 seconds after the beginning of the buffer }, }); ``` -------------------------------- ### Install RxPlayer with npm Source: https://github.com/canalplus/rx-player/blob/dev/doc/Getting_Started/Tutorials/Quick_Start.md Use this command to add RxPlayer as a dependency to your project using npm. ```bash npm install --save rx-player ``` -------------------------------- ### Install RxPlayer with yarn Source: https://github.com/canalplus/rx-player/blob/dev/doc/Getting_Started/Tutorials/Quick_Start.md Use this command to add RxPlayer as a dependency to your project using yarn. ```bash yarn add rx-player ``` -------------------------------- ### Audio Adaptation Object Example Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Miscellaneous/Local_Manifest_v0.1.md Represents an audio track. Includes 'language' and 'audioDescription' properties. ```javascript { type: "audio", language: "fra", // language code for this audio track audioDescription: false, // if `true`, that audio track is a track adapted for // the visually impaired representations: [ /* ... */ ] } ``` -------------------------------- ### Example: Getting Representations Locked for the First Period Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Representation_Selection/getLockedVideoRepresentations.md This example demonstrates how to retrieve locked video representations for a specific period by first getting available periods and then passing the ID of the first period to the getLockedVideoRepresentations method. ```javascript // example: getting Representations locked for the first Period const periods = rxPlayer.getAvailablePeriods(); console.log(rxPlayer.getLockedVideoRepresentations(periods[0].id); ``` -------------------------------- ### Subpart Extraction Example Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Miscellaneous/presentationTimeOffset.md Visualizes a subpart of content being extracted, indicating the start time offset. ```text 00:00:00.000 02:00:00.000 |====|------|========================================================| ^ Subpart going from 00:05:24 to 00:12:54.000 ``` -------------------------------- ### Example Key System Configuration Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Playback_Information/getKeySystemConfiguration.md Illustrates how a `keySystems` option in `loadVideo` might map to a specific `keySystem` string returned by `getKeySystemConfiguration`. For instance, 'widevine' might be reported as 'com.widevine.alpha'. ```javascript rxPlayer.loadVideo({ keySystems: [ { type: "widevine", // ... }, ], // ... }); ``` -------------------------------- ### Example loadInitSegment Callback Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Miscellaneous/Local_Manifest_v0.1.md Illustrates how to implement the `loadInitSegment` callback to fetch and resolve an initialization segment. It includes error handling and a placeholder for abort functionality. ```javascript async function loadInitSegment(callbacks) { try { const initSegment = await getStoredInitSegmentForTheCurrentRepresentation(); callbacks.resolve(initSegment); } catch (e) { callbacks.reject(e); } // Note: in this example, there is no mean to abort the operation, as a result // we do not return a function here // // Here is how it would look like if we could: // return function abort() { // abortStoredInitSegmentRequest(); // } } ``` -------------------------------- ### Initialize RxPlayer with Multi-threading Source: https://github.com/canalplus/rx-player/blob/dev/doc/Getting_Started/MultiThreading.md This snippet demonstrates how to import and add the MULTI_THREAD feature, instantiate the player, attach a WebWorker, and load video content. It also shows how to check if the player is currently using the WebWorker. ```javascript import RxPlayer from "rx-player/minimal"; import { MULTI_THREAD } from "rx-player/experimental/features"; import { EMBEDDED_WORKER } from "rx-player/experimental/features/embeds"; RxPlayer.addFeatures([MULTI_THREAD]); const player = new RxPlayer(/* your usual options */); player.attachWorker({ workerUrl: EMBEDDED_WORKER }).catch((err) => { console.error("An error arised while initializing the worker", err); }); player.loadVideo({ /* ... */ }); const currentModeInfo = player.getCurrentModeInformation(); if (currentModeInfo === null) { console.info("No content loaded."); } else if (currentModeInfo.useWorker) { console.info("We're running the RxPlayer's main logic in a WebWorker!"); } else { console.info("We're running completely in main thread."); } ``` -------------------------------- ### Example Metaplaylist Output Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Tools/createMetaplaylist.md The structure of a metaplaylist object generated by createMetaplaylist, including content URLs, transport types, and calculated start and end times. ```javascript { type: "MPL", version: "0.1", dynamic: false, contents: [ { url: "https://somedashcontent.mpd", transport: "dash", startTime: 1000, endTime: 1600, }, { url: "https://somesmoothcontent.ism", transport: "smooth", startTime: 1600, endTime: 1635, }, { url: "https://somemetaplaylistcontent", transport: "metaplaylist", startTime: 1635, endTime: 7635, }, ], } ``` -------------------------------- ### Local Manifest with Multiple Periods Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Miscellaneous/Local_Contents.md An example of a local manifest object containing multiple consecutive periods, each with defined start and end times and adaptation tracks. ```javascript { type: "local", version: "0.2", minimumPosition: 0, maximumPosition: 60, isFinished: true, periods: [ // Here we have 3 consecutive periods: { start: 0, end: 10, adaptations: [ /* ... */ ] }, { start: 10, end: 30, adaptations: [ /* ... */ ] }, { start: 30, end: 60, adaptations: [ /* ... */ ] }, ], } ``` -------------------------------- ### Import and Check HDCP 1.1 Support Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Tools/MediaCapabilitiesProber.md Import the MediaCapabilitiesProber and check for HDCP 1.1 support. This example demonstrates the basic usage pattern for checking HDCP compatibility. ```javascript import { mediaCapabilitiesProber } from "rx-player/experimental/tools"; mediaCapabilitiesProber.getStatusForHDCP("1.1").then((hdcp11Status) => { if (hdcp11Status === "Supported") { console.log("HDCP 1.1 is supported"); } }); ``` -------------------------------- ### Initialize MediaSource and Load Content Source: https://github.com/canalplus/rx-player/blob/dev/tests/conformance/initial_seek_after_segment_push.html Sets up the MediaSource, attaches it to the video element, and initiates the loading of media segments. This function is called once to start the test. ```javascript var videoElement = document.querySelector("video"); loadContent(); function loadContent() { console.info("Creating MediaSource"); var mediaSource = new MediaSource(); var objectURL = URL.createObjectURL(mediaSource); mediaSource.addEventListener("sourceopen", onSourceOpen); mediaSource.addEventListener("webkitsourceopen", onSourceOpen); videoElement.src = objectURL; } ``` -------------------------------- ### Replace getVideoLoadedTime with custom function Source: https://github.com/canalplus/rx-player/blob/dev/doc/Getting_Started/Migration_From_v3/Player_Methods.md The `getVideoLoadedTime` method has been removed. This example shows how to replicate its functionality by getting the current position and video element, then calculating the buffered range. ```javascript function getVideoLoadedTime() { const position = rxPlayer.getPosition(); const mediaElement = rxPlayer.getVideoElement(); if (mediaElement === null) { console.error("The RxPlayer is disposed"); } else { const range = getRange(mediaElement.buffered, currentTime); return range !== null ? range.end - range.start : 0; } } /** * Get range object of a specific time in a TimeRanges object. * @param {TimeRanges} timeRanges * @returns {Object} */ function getRange(timeRanges, time) { for (let i = timeRanges.length - 1; i >= 0; i--) { const start = timeRanges.start(i); if (time >= start) { const end = timeRanges.end(i); if (time < end) { return { start, end }; } } } return null; } ``` -------------------------------- ### Initialize and Play Video with RxPlayer Source: https://github.com/canalplus/rx-player/blob/dev/README.md Import RxPlayer, initialize it with a video element, and load a video stream using its URL and transport type. The player can be configured to auto-play. ```js import RxPlayer from "rx-player"; const player = new RxPlayer({ videoElement: document.querySelector("video"), }); // play a video player.loadVideo({ url: "http://vm2.dashif.org/livesim-dev/segtimeline_1/testpic_6s/Manifest.mpd", transport: "dash", autoPlay: true, }); ``` -------------------------------- ### VOD MetaPlaylist Example Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Miscellaneous/MetaPlaylist.md Defines a Video On Demand (VOD) MetaPlaylist structure, specifying a sequence of DASH and Smooth streaming contents with their respective start and end times. ```json { "type": "MPL", "version": "0.1", "contents": [ { "url": "http://url.to.some/DASH/first_content.mpd", "startTime": 0, "endTime": 100.38, "transport": "dash" }, { "url": "http://url.to.some/DASH/second_content.Manifest", "startTime": 100.38, "endTime": 372, "transport": "smooth" }, { "url": "http://url.to.some/Smooth/third_content.mpd", "startTime": 372, "endTime": 450.787, "transport": "dash" } ] } ``` -------------------------------- ### Media Segment Array Example Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Miscellaneous/Local_Contents.md An array of objects, each describing a media segment with its start time, duration, and an optional timestamp offset. This structure is part of the representation's index. ```javascript [ { time: 0, duration: 2, }, { time: 2, duration: 2, }, { time: 4, duration: 2, }, { time: 6, duration: 2, }, ]; ``` -------------------------------- ### Test MediaKeySystemAccess and setServerCertificate Source: https://github.com/canalplus/rx-player/blob/dev/tests/conformance/set_server_certificate.html This snippet tests the creation of MediaKeySystemAccess and MediaKeys, then proceeds to download and set server certificates using fetch. It checks for the availability of the `setServerCertificate` API before attempting to use it. Errors during download or setting are logged. ```javascript const keySystem = "com.widevine.alpha"; const configuration = [ { initDataTypes: ["cenc"], audioCapabilities: [ { robustness: "", contentType: 'audio/mp4; codecs="mp4a.40.2"', }, ], videoCapabilities: [ { robustness: "", contentType: 'video/mp4;codecs="avc1.640028"', }, ], sessionTypes: ["temporary"], }, ]; const URL_CERTIFICATE_B = "http://127.0.0.1:8080/service-cert"; const URL_CERTIFICATE_A = "http://127.0.0.1:8080/cert_license_widevine_com.bin"; console.log("Calling requestMediaKeySystemAccess..."); navigator .requestMediaKeySystemAccess(keySystem, configuration) .then((mediaKeySystemAccess) => { console.log( "MediaKeySystemAccess created!", mediaKeySystemAccess.getConfiguration(), ); console.log("Creating MediaKeys..."); return mediaKeySystemAccess.createMediaKeys(); }) .then((mediaKeys) => { console.log("MediaKeys created!"); console.log("Checking setServerCertificate availability..."); if (!("setServerCertificate" in mediaKeys)) { console.error("`setServerCertificate` API not available."); return; } return fetch(URL_CERTIFICATE_A) .then((res) => res.arrayBuffer()) .catch((err) => { console.error("Error while downloading server certificate A", err); throw err; }) .then((ab) => { console.log("Server certificate A downloaded!"); return mediaKeys.setServerCertificate(ab); }) .catch((err) => { console.error("Error while setting server certificate A", err); throw err; }) .then((ab) => { console.log("Server certificate A set with success!"); return fetch(URL_CERTIFICATE_B); }) .then((res) => res.arrayBuffer()) .catch((err) => { console.error("Error while downloading server certificate B", err); throw err; }) .then((ab) => { console.log("Server certificate B downloaded!"); return mediaKeys.setServerCertificate(ab); }) .catch((err) => { console.error("Error while setting server certificate B", err); throw err; }) .then((ab) => { console.log("Server certificate B set with success!"); return mediaKeys.setServerCertificate(ab); }); }); ``` -------------------------------- ### Create MediaKeySystemAccess Source: https://github.com/canalplus/rx-player/blob/dev/tests/conformance/media_key_system_access.html Requests and creates a MediaKeySystemAccess object for a given key system and configuration. Handles success and error logging. ```javascript /** * @param {string} keySystem * @param {MediaKeySystemConfiguration} mediaKeySystemAccessConfig * @returns {Promise.} */ function createMediaKeySystemAccess(keySystem, mediaKeySystemAccessConfig) { console.log("Creating MediaKeySystemAccess"); return navigator .requestMediaKeySystemAccess(keySystem, mediaKeySystemAccessConfig) .then( (mediaKeySystemAccess) => { console.log( "MediaKeySystemAccess created.", mediaKeySystemAccess.getConfiguration(), ); return mediaKeySystemAccess; }, (err) => { console.error( "Failed to create MediaKeySystemAccess", keySystem, mediaKeySystemAccessConfig, err, ); throw err; }, ); } ``` -------------------------------- ### Get Current Period Information Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Basic_Methods/getCurrentPeriod.md Call this method to retrieve details about the current period being played. It returns an object with `start`, `end`, and `id` properties, or `null` if no content is active. ```javascript const currentPeriod = rxPlayer.getCurrentPeriod(); ``` -------------------------------- ### Instantiate RxPlayer with a video element Source: https://github.com/canalplus/rx-player/blob/dev/doc/Getting_Started/Tutorials/Quick_Start.md Create a new RxPlayer instance and link it to a video HTML element. This is the first step to using the player. ```javascript import RxPlayer from "rx-player"; const videoElement = document.querySelector("video"); const player = new RxPlayer({ videoElement }); ``` -------------------------------- ### Get Available Periods in RxPlayer Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Basic_Methods/getAvailablePeriods.md Call this method to retrieve an array of Period objects. Each object contains details like start, end, and id, which can be used for track and representation selection. ```javascript const periods = rxPlayer.getAvailablePeriods(); ``` -------------------------------- ### Get Audio Tracks with Period ID and Filter Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Track_Selection/getAvailableAudioTracks.md This example demonstrates how to retrieve audio track metadata for a specific period, including representations that are not playable. It's useful for debugging or device capability detection. ```javascript const periods = rxPlayer.getAvailablePeriods(); console.log(rxPlayer.getAvailableAudioTracks({ periodId: periods[0].id, filterPlayableRepresentations: false, })); ``` -------------------------------- ### Get Video Track for Specific Period (using rxPlayer) Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Track_Selection/getVideoTrack.md Retrieves metadata for the video track of a specific period, including non-playable representations. This example demonstrates fetching the video track for the first available period. ```javascript const periods = rxPlayer.getAvailablePeriods(); console.log(rxPlayer.getVideoTrack({ periodId: periods[0].id, filterPlayableRepresentations: false, })); ``` -------------------------------- ### Setting Video Track on New Available Periods Event Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Track_Selection/setVideoTrack.md This example shows how to set an initial video track as soon as new periods become available. ```APIDOC ```js rxPlayer.addEventListener("newAvailablePeriods", (periods) => { for (const period of periods) { const periodId = period.id; const firstVideoTrack = rxPlayer.getAvailableVideoTracks(periodId)[0]; if (firstVideoTrack !== undefined) { rxPlayer.setVideoTrack({ trackId: firstVideoTrack.id, periodId, }); } } }); ``` ``` -------------------------------- ### Get Last Stored Content Position Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Playback_Information/getLastStoredContentPosition.md Returns the last stored position of the last played content, in seconds. Returns `undefined` if no content was previously loaded. This method can be useful if you want to reload using `player.loadVideo()` and not `player.reload()`, after an error for example. It can also be used to retrieve the position where the player was at when the error arised. ```APIDOC ## getLastStoredContentPosition ### Description Returns the last stored position of the last played content, in seconds. Returns `undefined` if no content was previously loaded. This method can be useful if you want to reload using `player.loadVideo()` and not `player.reload()`, after an error for example. It can also be used to retrieve the position where the player was at when the error arised. ### Syntax ```js const lastStoredContentPosition = player.getLastStoredContentPosition(); ``` ### Return Value `number|undefined` - The last stored content position in seconds, or undefined if no content was previously loaded. ### Example ```js const lastStoredContentPosition = player.getLastStoredContentPosition(); if (lastStoredContentPosition !== undefined) { player.loadVideo({ // ... startAt: { position: lastStoredContentPosition, }, }); } ``` ``` -------------------------------- ### Stop Video Example Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Basic_Methods/stop.md An example of how to use the stop method within a function. ```js const stopVideo = () => { player.stop(); }; ``` -------------------------------- ### Initialize and Use VideoThumbnailLoader Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Tools/VideoThumbnailLoader.md Demonstrates how to import, initialize, and use the VideoThumbnailLoader with an RxPlayer instance. Ensure the appropriate loader (e.g., DASH_LOADER) is added before creating the loader instance. ```javascript import VideoThumbnailLoader, { DASH_LOADER, } from "rx-player/experimental/tools/VideoThumbnailLoader"; import RxPlayer from "rx-player"; const player = new RxPlayer({ /* some options */ }); // Link logic to handle DASH segments VideoThumbnailLoader.addLoader(DASH_LOADER); // Video element used to display thumbnails. const thumbnailVideoElement = document.createElement("video"); // Link VideoThumbnailLoader to the RxPlayer instance const videoThumbnailLoader = new VideoThumbnailLoader(thumbnailVideoElement, player); player.loadVideo({ /* some options */ }); // Ask for the VideoThumbnailLoader to fetch a thumbnail for the current // content that should be displayed at presentation time = 200 seconds. videoThumbnailLoader.setTime(200); ``` -------------------------------- ### Live MetaPlaylist Example Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Miscellaneous/MetaPlaylist.md Defines a live MetaPlaylist structure, including dynamic playback settings like 'dynamic' and 'pollInterval', along with a sequence of DASH contents and their time ranges. ```json { "type": "MPL", "version": "0.1", "dynamic": true, "pollInterval": 5, "contents": [ { "url": "http://url.to.some/DASH/content.mpd", "startTime": 1545845950.176, "endTime": 1545845950.176, "transport": "dash" }, { "url": "http://url.to.some/other/DASH/content.mpd", "startTime": 1545845985.571, "endTime": 1545845998.71, "transport": "dash" }, { "url": "http://url.to.some/Smooth/content.Manifest", "startTime": 1545845998.71, "endTime": 1545845117, "transport": "smooth" } ] } ``` -------------------------------- ### Instantiate RxPlayer Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Creating_a_Player.md Instantiate a new RxPlayer. This is necessary before loading any content. You can optionally pass configuration options. ```javascript import RxPlayer from "rx-player"; const player = new RxPlayer(options); ``` -------------------------------- ### Get Content URLs Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Playback_Information/getContentUrls.md Call `getContentUrls` to get the URLs for the current content. Check if the result is defined and not empty before using it. ```javascript const urls = player.getContentUrls(); if (urls !== undefined && urls.length > 0) { console.log("We are playing a content reachable through the following URLs:", urls); } ``` ```javascript const urls = player.getContentUrls(); ``` -------------------------------- ### Check DRM Configuration Support Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Tools/MediaCapabilitiesProber.md Probe the support for a given key system and MediaKeySystemConfiguration. This example checks for Widevine with specific video capabilities and robustness levels. It logs whether the configuration is compatible or not. ```javascript import { mediaCapabilitiesProber } from "rx-player/experimental/tools"; const mksConfiguration = { initDataTypes: ["cenc"], videoCapabilities: [ { contentType: 'video/mp4;codecs="avc1.4d401e"', // standard mp4 codec robustness: "HW_SECURE_CRYPTO", }, { contentType: 'video/mp4;codecs="avc1.4d401e"', robustness: "SW_SECURE_DECODE", }, ], }; mediaCapabilitiesProber.checkDrmConfiguration( "com.widevine.alpha", mksConfiguration, ).then( // On success: (config) => { console.log("This device is compatible with the given configuration:", config); console.log("Source configuration:", mksConfiguration); }, // On failure (err) => { console.log("This device is not compatible with the given configuration!", err); }, }); ``` -------------------------------- ### Example: Removing a specific listener callback Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Basic_Methods/removeEventListener.md This example demonstrates how to remove a specific listener callback function named 'listenerCallback' for the 'playerStateChange' event. ```javascript player.removeEventListener("playerStateChange", listenerCallback); ``` -------------------------------- ### Period Adaptations Integration Example Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Miscellaneous/Local_Manifest_v0.1.md Shows how multiple adaptations (video, audio, text) are integrated within a given period. ```javascript { start: 0, end: 10000, adaptations: [ { type: "video", representations: [ /* ... */ ], }, { type: "audio", language: "eng", audioDescription: false, representations: [ /* ... */ ] }, { type: "audio", language: "fra", audioDescription: false, representations: [ /* ... */ ] }, { type: "audio", language: "fra", audioDescription: true, representations: [ /* ... */ ] }, { type: "text", language: "fra", closedCaption: false, representations: [ /* ... */ ] }, { type: "text", language: "fra", closedCaption: true, representations: [ /* ... */ ] } ] }, ``` -------------------------------- ### Get Available Audio Tracks (Default) Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Track_Selection/getAvailableAudioTracks.md Call this to get a list of available audio tracks for the currently playing Period. By default, only playable representations are included. ```javascript const audioTracks = player.getAvailableAudioTracks(); ``` -------------------------------- ### Get thumbnail tracks for the first Period Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Thumbnails/getAvailableThumbnailTracks.md Retrieve thumbnail tracks for a specific period by first getting all available periods and then filtering by the ID of the first period. ```javascript const periods = rxPlayer.getAvailablePeriods(); console.log(rxPlayer.getAvailableThumbnailTracks({ periodId: periods[0].id })); ``` -------------------------------- ### Import Minimal RxPlayer Source: https://github.com/canalplus/rx-player/blob/dev/doc/Getting_Started/Minimal_Player.md Import the minimal RxPlayer to start with a base player that has no features enabled. This is the first step to customizing your player. ```javascript import MinimalRxPlayer from "rx-player/minimal"; // This player has the same API than the RxPlayer, but with no feature // (e.g. no DASH, Smooth or Directfile playback) const player = new MinimalRxPlayer(); // use the regular APIs... player.setVolume(0.5); ``` -------------------------------- ### DASH EventStream MPD Example Source: https://github.com/canalplus/rx-player/blob/dev/doc/Getting_Started/Tutorials/EventStream_Handling.md An example of a DASH MPD file containing EventStream elements with associated events. These elements are parsed by RxPlayer to trigger stream events. ```xml 1 800 10101010 1 800 10101011 1 800 10101012 1 800 10101013 ``` -------------------------------- ### ContentInitializer Workflow Diagram Source: https://github.com/canalplus/rx-player/blob/dev/src/main_thread/init/README.md Illustrates the sequence of operations when loading a video, from API call to ContentInitializer instantiation and event emission. ```text +-----------+ 1. loadVideo | | 2. Instanciate ---------------> | API | -------------------+ | | | +-----------+ | ^ v | +--------------------+ | 3. Emit events | | +------------------- | ContentInitializer | | | +--------------------+ ``` -------------------------------- ### getVideoRepresentation Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Representation_Selection/getVideoRepresentation.md Retrieves information about the currently loaded video representation. This method can be called without arguments to get information for the current period, or with a periodId to get information for a specific period. ```APIDOC ## getVideoRepresentation ### Description Get information about the video Representation currently loaded. Note that this only returns the video Representation that is _loaded_ which may be different to the one that is _played_. The returned value can either be an object or: - `null` if no video track is enabled right now. - `undefined` if no video content has been loaded yet or if its information is unknown. In case it a video track is set and its properties is known, the `getVideoRepresentation` method will return an object with the following properties: - `id` (`string`): The id used to identify this Representation. No other video Representation for the same [Period](../../Getting_Started/Glossary.md#period) will have the same `id`. This can be useful when locking the Representation through the [`lockVideoRepresentations`](./lockAudioVideoRepresentations.md) method. - `bitrate` (`Number|undefined`): The bitrate of this Representation, in bits per seconds. `undefined` if unknown. - `width` (`Number|undefined`): The width of this video Representation, in pixels. - `height` (`Number|undefined`): The height of this video Representation, in pixels. - `codec` (`string|undefined`): The video codec the Representation is in, as announced in the corresponding Manifest. - `frameRate` (`number|undefined`): The video frame rate, in frames per second. - `hdrInfo` (`Object|undefined`) Information about the hdr characteristics of the Representation. (see [HDR support documentation](.././Miscellaneous/hdr.md#hdrinfo)) - `contentProtections` (`Object|undefined`): Encryption information linked to this Representation. If set to an Object, the Representation is known to be encrypted. If unset or set to `undefined` the Representation is either unencrypted or we don't know if it is. When set to an object, it may contain the following properties: - `keyIds` (`Array.|undefined`): Known key ids linked to that Representation. You can also get the information on the loaded video Representation for another Period by calling `getVideoRepresentation` with the corresponding Period's id in argument. Such id can be obtained through the `getAvailablePeriods` method, the `newAvailablePeriods` event or the `periodChange` event. ```js // example: getting Representation information for the first Period const periods = rxPlayer.getAvailablePeriods(); console.log(rxPlayer.getVideoRepresentation(periods[0].id); ```
In DirectFile mode (see loadVideo options), this method returns "undefined".
### Syntax ```js // Get information about the currently-loaded video Representation const videoRepresentation = player.getVideoRepresentation(); // Get information about the loaded video Representation for a specific Period const videoRepresentation = player.getVideoRepresentation(periodId); ``` ### Parameters #### Arguments - `periodId` (`string|undefined`): The `id` of the Period for which you want to get information about its currently loaded video Representation. If not defined, the information associated to the currently-playing Period will be returned. ### Return Value `Object|null|undefined` ``` -------------------------------- ### Initialize and Use TextTrackRenderer with SRT Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Tools/TextTrackRenderer.md This example demonstrates a complete usage scenario, including importing necessary parsers, initializing the TextTrackRenderer with video and text track elements, and setting a subtitle track. Ensure the video and text track elements exist in your HTML. ```javascript // import TextTrackRenderer and the parsers we want import TextTrackRenderer, { TTML_PARSER, VTT_PARSER, SRT_PARSER, SAMI_PARSER, } from "rx-player/tools/TextTrackRenderer"; // Add the needed parsers to the TextTrackRenderer TextTrackRenderer.addParsers([TTML_PARSER, VTT_PARSER, SRT_PARSER, SAMI_PARSER]); // get video element the subtitles has to be synchronized to const videoElement = document.querySelector("video"); // get HTML element in which the text track will be displayed // Should generally be on top of the video, with the same size than it (but can // also be in any shape, corresponding to your UI needs). const textTrackElement = document.querySelector(".text-track-container"); const textTrackRenderer = new TextTrackRenderer({ videoElement, textTrackElement, }); // example: a ".srt" track const exampleSRT = `1 00:00:01,600 --> 00:00:04,200 English (US) 2 00:00:05,900 --> 00:00:07,999 This is a subtitle in American English 3 00:00:10,000 --> 00:00:14,000 Adding subtitles is very easy to do `; try { textTrackRenderer.setTextTrack({ data: exampleSRT, type: "srt", // or "ttml" / "vtt" / "sami" // timeOffset: 2.3, // optional offset in seconds to add to the subtitles }); } catch (e) { console.error(`Could not parse the subtitles: ${e}`); } ``` -------------------------------- ### Get Currently Loaded Audio Representation Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Representation_Selection/getAudioRepresentation.md Call this method without arguments to get information about the audio Representation currently loaded for the active Period. Ensure the player instance is available. ```javascript const audioRepresentation = player.getAudioRepresentation(); ``` -------------------------------- ### Example loadSegment Callback Source: https://github.com/canalplus/rx-player/blob/dev/doc/api/Miscellaneous/Local_Manifest_v0.1.md Demonstrates the implementation of the `loadSegment` callback for fetching media segments. It handles segment retrieval, resolution, and error rejection, with a note on abort functionality. ```javascript async function loadSegment(segment, callbacks) { try { const segmentData = await getStoredSegment(segment); callbacks.resolve(segmentData); } catch (e) { callbacks.reject(e); } // Note: in this example, there is no mean to abort the operation, as a result // we do not return a function here // // Here is how it would look like if we could: // return function abort() { // abortStoredSegmentRequest(); // } } ```