Giter VIP home page Giter VIP logo

api.video-player-sdk's Introduction

badge Β  badge Β  badge

api.video player SDK

api.video is the video infrastructure for product builders. Lightning fast video APIs for integrating, scaling, and managing on-demand & low latency live streaming features in your app.

Table of contents

<!--<documentation_only>

title: api.video Player SDK meta: description: The official api.video Player SDK for api.video. api.video is the video infrastructure for product builders. Lightning fast video APIs for integrating, scaling, and managing on-demand & low latency live streaming features in your app.


api.video Player SDK

api.video is the video infrastructure for product builders. Lightning fast video APIs for integrating, scaling, and managing on-demand & low latency live streaming features in your app.

</documentation_only>-->

Project description

SDK to control and interact with the api.video HTML5 Player

Getting started

Installation

Method #1: requirejs

If you use requirejs you can add the SDK as a dependency to your project with

$ npm install --save @api.video/player-sdk

You can then use the SDK in your script:

var { PlayerSdk } = require("@api.video/player-sdk");

var sdk = new PlayerSdk("#target", {
  id: "<VIDEO_ID>",
  // ... other optional options
});

Method #2: typescript

If you use Typescript you can add the SDK as a dependency to your project with

$ npm install --save @api.video/player-sdk

You can then use the SDK in your script:

import { PlayerSdk } from "@api.video/player-sdk";

const sdk = new PlayerSdk("#target", {
  id: "<VIDEO_ID>",
  // ... other optional options
});

Method #2: simple include in a javascript project

Include the SDK in your HTML file like so:

<head>
  ...
  <script src="https://unpkg.com/@api.video/player-sdk" defer></script>
</head>

Then, once the window.onload event has been triggered, create your player using new PlayerSdk():

<script type="text/javascript">
  window.player = new PlayerSdk("#target", {
    id: "<VIDEO_ID>",
    // ... other optional options
  });
</script>

Documentation

Instantiation

The PlayerSdk constructor takes 2 parameters:

  • targetSelector: string | Element a CSS selector targeting the DOM element in which you want to create the player (eg. "#target"), or the DOM element itself
  • options: SdkOptions an object containing the player options. The available options are the following:
Option name Mandatory Type Description
id yes string the id of the video (videoId or liveStreamId)
token yes for private video string the private video url token
privateSession no string the private video session id if needed
live no (default: false) boolean indicate that the video is a live one
autoplay no (default: false) boolean start playing the video as soon as it is loaded
muted no (default: false) boolean the video is muted
metadata no (default: empty) object object containing metadata (see Full example below)
hideControls no (default: false) boolean the controls are hidden (except unmute button if the video starts muted)
chromeless no (default: false) boolean chromeless mode: all controls are hidden
hideTitle no (default: false) boolean the video title is hidden
hidePoster no (default: false) boolean the poster image isn't displayed
showSubtitles no (default: false) boolean the video subtitles are shown by default
loop no (default: false) boolean once the video is finished it automatically starts again
playbackRate no (default: 1) number the playback rate of the video: 1 for normal, 2 for x2, etc.
sequence no {start: number, end: number} define a sequence of the video to play. The video will start at the start timecode and end at the end timecode. The timecodes are in seconds.
ads no {adTagUrl: string} see below ads
customDomain no string if you've enabled Custom Domains for your account, the complete 'embed' domain (eg. embed.mydomain.com)
hotkeys no (default: true) boolean if false, deactivate the player's hotkeys to prevent it from capturing focus, which can be beneficial in certain scenarios

The sdk instance can be used to control the video playback, and to listen to player events.

Ads

Ads can be displayed in the player. To do so, you need to pass the ads option to the sdk constructor. In the ads object, pass the adTagUrl property with the url of the ad tag. The ad tag must be a VAST 2.0 or 3.0 url. For more information about VAST, check the IAB documentation.

Note: ads are displayed using the Google IMA SDK.

Methods

The sdk instance has the following methods:

loadConfig(options: SdkOptions)

Load a new video in the same instance of the player. Available options are the same as the ones passed to the SDK constructor (see available).

Example:

player.loadConfig({
  id: "<VIDEO_ID>",
  hideTitle: true,
  hideControls: true,
});

play()

Start playing the video.

pause()

Pause the video playback.

mute()

Mute the video.

unmute()

Unmute the video.

hideControls(controls?: ControlName[])

Hide the player controls.

controls parameter type definition:

type ControlName =
  | "play"
  | "seekBackward"
  | "seekForward"
  | "playbackRate"
  | "volume"
  | "fullscreen"
  | "subtitles"
  | "chapters"
  | "pictureInPicture"
  | "progressBar"
  | "chromecast"
  | "download"
  | "more";

If no value is provided for the "controls" parameter, all controls will be hidden.

Note: the only control that can still be visible is the unmute button if the video as started muted. To hide all controls, including this one, use the setChromeless() method

Example:

player.hideControls();

If a list of control names if provided, the associated controls will be hidden.

Example:

player.showControls(); // display all controls ...
player.hideControls(["download", "subtitles"]); // ... except "download" and "subtitles"

showControls(controls?: ControlName[])

Show the player controls.

controls parameter type definition:

type ControlName =
  | "play"
  | "seekBackward"
  | "seekForward"
  | "playbackRate"
  | "volume"
  | "fullscreen"
  | "subtitles"
  | "chapters"
  | "pictureInPicture"
  | "progressBar"
  | "chromecast"
  | "download"
  | "more";

If no value is provided for the "controls" parameter, all controls will be displayed.

Example:

player.showControls();

If a list of control names if provided, the associated controls will be displayed.

Example:

player.hideControls(); // hide all controls ...
player.showControls(["download", "subtitles"]); // ... except "download" and "subtitles" ...
// ...
player.showControls(["progressBar"]); // ... and the progress bar

setChromeless(chromeless: boolean)

Define if the player should be in chromeless mode (all controls hidden).

hideSubtitles()

Hide the player subtitles.

showSubtitles()

Show the player subtitles.

hideTitles()

Hide the video title at the top of the video.

showTitles()

Show the video title at the top of the video.

setLoop(loop: boolean)

Define if the video should be played in loop.

setAutoplay(autoplay: boolean)

Define if the video should start playing as soon as it is loaded

seek(time: number)

Add/substract the given number of seconds to/from the playback time.

setPlaybackRate(rate: number)

Set the current playback rate.

Example:

player.setPlaybackRate(2); // Play at 2x rate

setCurrentTime(time: number)

Set the current playback time (seconds).

Example:

player.setCurrentTime(24); // Go the 24th second

setVolume(volume: number)

Change the audio volume to the given value. From 0 to 1 (0 = muted, 1 = 100%).

Example:

player.setVolume(0.75); // Set the volume to 75%

setVideoStyleObjectFit(value: "contain" | "cover" | "fill" | "none" | "scale-down")

Change the object-fit CSS value of the video tag.

Example:

player.setVideoStyleObjectFit("cover"); // Set the object-fit to cover

setVideoStyleTransform(value: string)

Change the transform CSS value of the video tag.

Example:

player.setVideoStyleTransform("rotateY(180deg)"); // Apply a 180deg rotation around the Y axis (mirroring)

setTheme(theme: PlayerTheme)

Change the appearance of the player.

theme parameter type definition:

type PlayerTheme = {
  text?: string;
  link?: string;
  linkHover?: string;
  trackPlayed?: string;
  trackUnplayed?: string;
  trackBackground?: string;
  backgroundTop?: string;
  backgroundBottom?: string;
  backgroundText?: string;
  linkActive?: string;
};

Example:

player.setTheme({
  link: "red",
  linkHover: "rgba(0, 255, 0, 1)",
  backgroundBottom: "#0000ff",
});

requestFullscreen()

Request fullscreen mode (this may not work in some cases depending on browser restrictions)

exitFullscreen()

Leave fullscreen mode

requestPictureInPicture()

Request picture in picture mode (this may not work in some cases depending on browser restrictions)

exitPictureInPicture()

Leave picture in picture mode

getPaused(callback?: (paused: boolean) => void): Promise<boolean>

Check weither the video is paused.

getPlaying(callback?: (playing: boolean) => void): Promise<boolean>

Check weither the video is playing.

getMuted(callback?: (muted: boolean) => void): Promise<boolean>

Check weither the video is muted.

getDuration(callback?: (duration: number) => void): Promise<number>

Retrieve the duration of the video.

getCurrentTime(callback?: (currentTime: number) => void): Promise<number>

Retrieve the current playback time of the video.

getVolume(callback?: (volume: number) => void): Promise<number>

Retrieve the current volume.

getLoop(callback?: (loop: boolean) => void): Promise<boolean>

Check whether the video is in loop mode.

getPlaybackRate(callback?: (rate: number) => void): Promise<number>

Retrieve the playback rate.

isLiveStream(callback?: (live: boolean) => void): Promise<boolean>

Check whether the video is a live stream.

destroy()

Destroy the player instance.

addEventListener(event: string, callback: () => void)

Define a callback function that will be called when the given event is triggered by the player.

Available events are the following:

Event name Description Parameter
airplayConnected Started to play on an airplay device -
airplayDisconnected Stopped to play on an airplay device -
chromecastConnected Started to play on a chromecast device -
chromecastDisconnected Stopped to play on a chromecast device -
controlsdisabled Controls are now disabled -
controlsenabled Controls are now enabled -
ended The playback as reached the ended of the video -
error An error occured -
firstplay The video started to play for the first time -
fullscreenchange The player goes to (or goes back from) full screen -
mouseenter The user's mouse entered the player area -
mouseleave The user's mouse leaved the player area -
pause The video has been paused -
play The video started to play (for the first time or after having been paused) -
playerresize The player size has changed -
qualitychange The video quality has changed { resolution: { height: number, width: number } }
ratechange The playback rate has changed -
ready The player is ready to play -
resize The video size has changed
seeking The player is seeking -
timeupdate The playback time has changed { currentTime: number }
useractive The user is active -
userinactive The user is inactive -
volumechange The volume has changed { volume: number }

Examples:

// listen to the 'play' event
player.addEventListener("play", function () {
  console.log("play event received");
});

player.addEventListener("qualitychange", function (ev) {
  console.log(
    `quality has changed: ${ev.resolution.width}x${ev.resolution.height}`
  );
});

Full example

<html>
  <head>
    ...
    <script src="/index.js" defer></script>
  </head>

  <body>
    <div id="target"></div>

    <!-- buttons that call player methods to control the video playback -->
    <button onclick="javascript:player.play()" id="play-btn">play</button>
    <button onclick="javascript:player.pause()" id="pause-btn" disabled>
      pause
    </button>
    <button onclick="javascript:player.mute()">mute</button>
    <button onclick="javascript:player.unmute()">unmute</button>
  </body>

  <script type="text/javascript">
    window.onload = function () {
      // create the player in the #target element
      window.player = new PlayerSdk("#target", {
        id: "123456",
        metadata: {
          dogcat: "dog",
        },
      });

      // when the 'play' event is received, disable the 'play' button and enable the 'pause' button
      player.addEventListener("play", function () {
        document.getElementById("play-btn").disabled = true;
        document.getElementById("pause-btn").disabled = false;
      });

      // when the 'pause' event is received, disable the 'pause' button and enable the 'play' button
      player.addEventListener("pause", function () {
        document.getElementById("play-btn").disabled = false;
        document.getElementById("pause-btn").disabled = true;
      });
    };
  </script>
</html>

Control an existing embedded player using the SDK

It's also possible to integrate the SDK in a page that already contains an embedded player in order to control it and to listen to its events. Let's consider the following page :

<html>
  <head>
    ...
  </head>

  <body>
    ...
    <!-- my embedded player -->
    <iframe
      src="//embed.api.video/vod/vi54sj9dAakOHJXKrUycCQZp"
      width="100%"
      height="100%"
      frameborder="0"
      allowfullscreen
    ></iframe>
    ...
  </body>
</html>

To attach the SDK to this player, you'll have to make the following changed in your page:

  • import the sdk.js script in your page,
  • create a PlayerSdk instance once the page is loaded.

Here is how the page will look like with these changes :

<html>
  <head>
    ...
    <script src="/index.js" defer></script>
  </head>

  <body>
    ...
    <!-- my embedded player -->
    <iframe
      id="myPlayer"
      src="//embed.api.video/vod/vi54sj9dAakOHJXKrUycCQZp"
      width="100%"
      height="100%"
      frameborder="0"
      allowfullscreen
    ></iframe>
    ...
  </body>

  <script type="text/javascript">
    window.onload = function () {
      // attach the sdk to the existing player
      window.player = new PlayerSdk("#myPlayer");

      // window.player can now be used to control the player as described above
    };
  </script>
</html>

api.video-player-sdk's People

Contributors

anthony-dantard avatar dependabot[bot] avatar dougsillars avatar erikkai avatar lexoyo avatar olivierapivideo avatar olivierlando avatar thibaultbee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

api.video-player-sdk's Issues

Consider open sourcing the Player SDK

At the moment, the player SDK feel very akward to use, especially in modern Js frameworks.

For now I gave up using this library and I'll stick to the iframe version of the player for now that suits our basic needs. Well, in the end, I'm still using this library, but in an iframe, which I have no control over.

Here are the pros of open-sourcing this library :

  • Can be published on npm and install as a normal project dependency
  • Can be built and shipped with the Js bundle of the project
  • Can be adapted to suit any Js environments (see my foot note on using this with React)
  • Trust. I don't trust a minified Js library.
  • The community can do many things for you -> reducing cost
  • ...

There are plenty of other reasons to do so, but I'll let you, other fellow developers do the rest.

As a foot note, here's my twisted take of using this SDK in React :

import { useCallback } from "react";

export default function Video({ id }) {
  const playerRef = useCallback((node) => {
    if (node !== null) {
      try {
        const myNode = document.getElementById(node.id);
        myNode.textContent = "";
        apiVideoSdk.create(`#${node.id}`, {
          id,
        });
      } catch (e) {
        console.log(
          "You must activate third party cookies."
        );
      }
    }
  }, []);

  return (
      <div id="player" ref={playerRef} />
  );
}

Feel free to contact me if you want to discuss this further.

How to get private video token?

Hi, thank you for open sourcing this SDK! πŸ™Œ

I've been trying to use this SDK to show private videos, but I wasn't able to find a way to get one-time private video token besides from parsing one of the URLs returned as assets map in GET /videos/:videoId endpoint response.

Is there a way to get this token seamlessly / did I miss something in the documentation? πŸ˜…
If not, does it make sense to add this token to the mentioned endpoint response so it can be easily passed to the PlayerSdk constructor?

Video quality / dimensions

thanks for a great player API!
I added api.video to my player benchmark over at https://dev.playerx.io/demo/api.video/

one thing that would be a nice addition is to have an idea what quality or video dimension is playing. is there a way to retrieve that information?

the native html5 video element has a resize event that fires and the .videoWidth and .videoHeight properties.

Add setting to flip video Horizontally in player without flipping controls

Is your feature request related to a problem? Please describe.
When we record a person we flip the camera so that it will look to the user that they are looking into a mirror. but when we switch to the recorded video it flips back the other way around.

Describe the solution you'd like
So we want a setting we can give the player sdk to mirror/flip the video horizontally to play the video as if the user is watching them self in the mirror.

Player doesn't work when third-party cookies are blocked

When third party cookies are blocked, the player doesn't work when embedded on a page.
Either using the player-sdk or the iframe URL, the same error occurs.

Error in Chrome :

Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
    at oc (https://embed.api.video/player.238c9e4.js:2:458345)
    at lc.value (https://embed.api.video/player.238c9e4.js:2:460299)
    at new lc (https://embed.api.video/player.238c9e4.js:2:468024)
    at Object.handleSource (https://embed.api.video/player.238c9e4.js:2:469227)
    at a.r.setSource (https://embed.api.video/player.238c9e4.js:2:82860)
    at u.<anonymous> (https://embed.api.video/player.238c9e4.js:2:192777)
    at u.e.ready (https://embed.api.video/player.238c9e4.js:2:23542)
    at u.e.techCall_ (https://embed.api.video/player.238c9e4.js:2:192576)
    at u.<anonymous> (https://embed.api.video/player.238c9e4.js:2:201254)
    at u.e.ready (https://embed.api.video/player.238c9e4.js:2:23542)

Third party cookies are well known practices in the advertising industry, I wouldn't recommend to rely on it for the player to be functional. Or at least do something to fail silently and not break everything else.

In Chrome the Block third-party cookies option is described as follow :

When on, sites can’t use your browsing activity across different sites to personalize ads. Some sites may not work properly.

When third party cookies are enabled, it works properly, but the following warning appears in console:

A cookie associated with a cross-site resource at http://embed.api.video/ was set without the SameSite attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.

Having issue while trying to import via webpack

Hello,

I'm struggling while trying to import apivideo player with webpack. My code looks like this:

import(/* webpackChunkName: "ApiVideoPlayer" */ '@api.video/player-sdk').then(({ default: ApiVideoPlayer }) => {
   const PlayerSDK = ApiVideoPlayer.PlayerSdk;
// error ApiVideoPlayer return undefined
});

I guess it is related with your webpack configuration not using libraryExport: 'default', but you may have your reasons. Maybe you have a clue about how to make it work like this.

Best regards,

Timeupdate event

Hi, and thanks for your work!

Is there a way to have access to the current time during playing, maybe with the timeupdate event of the HTML5 video player?

Seen here : https://dev.playerx.io/demo/api.video/ working, but when I try :

player.addEventListener('timeupdate', () => { console.log('timeupdate event received') })

nothing is displayed

Support for DOM events on the player

Since the player is an iframe, it might be useful to enable listening to the native DOM events such as click and focus to avoid the iframe focus detection workarounds.
For example, one such use case could be if the developer wants to expose additional controls somewhere within the app once the video is focused.

I'm suggesting this assuming it would be easy to do in the same manner that the other events are exposed from the iframe (using the Window.postMessage() method).
Thoughts?

Cannot hide custom controls

Describe the bug
A clear and concise description of what the bug is.
After instantiating the player, when trying to call the method hideControls(["download"]) or any other type of controls, an error exception gets thrown because the visibleControls array is undefined therefor it can't be filtered.
To Reproduce
Steps to reproduce the behavior:

  1. instantiate the player :
    let player = new PlayerSdk('#videoplayer', {
    id: videoId,
    token: token,
    autoplay: true,
    hideTitle: true,
    });
  2. Try hiding a control:
    player.hideControls(["download"]);

Expected behavior
A clear and concise description of what you expected to happen.
the control should become hidden and no exception should be thrown
Screenshots
If applicable, add screenshots to help explain your problem.
e1

image

image

e2

Environment (please complete the following information):

  • OS: [e.g. iOS] linux
  • Browser [e.g. chrome, safari] chrome, safari, mozilla firefox
  • Version [e.g. 22] all versions

Additional context
Add any other context about the problem here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.