Plyr is a simple, lightweight, accessible and customizable HTML5, YouTube and Vimeo media player that supports modern browsers.

Maintainers

Details

github.com/levmyshkin/plyr

Source

Fund package maintenance!
sampotts
Patreon
Open Collective

Installs: 414

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 2 935

Language:JavaScript

Type:drupal-library

v3.7.9 2024-11-14 10:56 UTC

This package is auto-updated.

Last update: 2024-11-14 10:57:35 UTC


README

Plyr is a simple, lightweight, accessible and customizable HTML5, YouTube and Vimeo media player that supports modern browsers.

Checkout the demo - Donate - Slack

npm version Gitpod Ready-to-Code Financial Contributors on Open Collective

Screenshot of Plyr

Features

  • πŸ“Ό HTML Video & Audio, YouTube & Vimeo - support for the major formats
  • πŸ’ͺ Accessible - full support for VTT captions and screen readers
  • πŸ”§ Customizable - make the player look how you want with the markup you want
  • 😎 Clean HTML - uses the right elements. <input type="range"> for volume and <progress> for progress and well, <button>s for buttons. There's no <span> or <a href="#"> button hacks
  • πŸ“± Responsive - works with any screen size
  • πŸ’΅ Monetization - make money from your videos
  • πŸ“Ή Streaming - support for hls.js, Shaka and dash.js streaming playback
  • πŸŽ› API - toggle playback, volume, seeking, and more through a standardized API
  • 🎀 Events - no messing around with Vimeo and YouTube APIs, all events are standardized across formats
  • πŸ”Ž Fullscreen - supports native fullscreen with fallback to "full window" modes
  • ⌨️ Shortcuts - supports keyboard shortcuts
  • πŸ–₯ Picture-in-Picture - supports picture-in-picture mode
  • πŸ“± Playsinline - supports the playsinline attribute
  • 🏎 Speed controls - adjust speed on the fly
  • πŸ“– Multiple captions - support for multiple caption tracks
  • 🌎 i18n support - support for internationalization of controls
  • πŸ‘Œ Preview thumbnails - support for displaying preview thumbnails
  • 🀟 No frameworks - written in "vanilla" ES6 JavaScript, no jQuery required
  • πŸ’β€β™€οΈ Sass - to include in your build processes

Demos

You can try Plyr in Codepen using our minimal templates: HTML5 video, HTML5 audio, YouTube, Vimeo. For Streaming we also have example integrations with: Dash.js, Hls.js and Shaka Player

Quick setup

HTML

Plyr extends upon the standard HTML5 media element markup so that's all you need for those types.

HTML5 Video

<video id="player" playsinline controls data-poster="/path/to/poster.jpg">
  <source src="/path/to/video.mp4" type="video/mp4" />
  <source src="/path/to/video.webm" type="video/webm" />

  <!-- Captions are optional -->
  <track kind="captions" label="English captions" src="/path/to/captions.vtt" srclang="en" default />
</video>

Note: The poster image should be specified using data-poster. This is to prevent it being downloaded twice. If you're sure the image will be cached, you can still use the poster attribute for true progressive enhancement.

HTML5 Audio

<audio id="player" controls>
  <source src="/path/to/audio.mp3" type="audio/mp3" />
  <source src="/path/to/audio.ogg" type="audio/ogg" />
</audio>

For YouTube and Vimeo players, Plyr uses progressive enhancement to enhance the default <iframe> embeds. Below are some examples. The plyr__video-embed classname will make the embed responsive. You can add the autoplay, loop, hl (YouTube only) and playsinline (YouTube only) query parameters to the URL and they will be set as config options automatically. For YouTube, the origin should be updated to reflect the domain you're hosting the embed on, or you can opt to omit it.

YouTube

We recommend progressive enhancement with the embedded players. You can elect to use an <iframe> as the source element (which Plyr will progressively enhance) or a bog standard <div> with two essential data attributes - data-plyr-provider and data-plyr-embed-id.

<div class="plyr__video-embed" id="player">
  <iframe
    src="https://www.youtube.com/embed/bTqVqk7FSmY?origin=https://plyr.io&amp;iv_load_policy=3&amp;modestbranding=1&amp;playsinline=1&amp;showinfo=0&amp;rel=0&amp;enablejsapi=1"
    allowfullscreen
    allowtransparency
    allow="autoplay"
  ></iframe>
</div>

Note: The plyr__video-embed classname will make the player a responsive 16:9 (most common) iframe embed. When plyr itself kicks in, your custom ratio config option will be used.

Or the <div> non progressively enhanced method:

<div id="player" data-plyr-provider="youtube" data-plyr-embed-id="bTqVqk7FSmY"></div>

Note: The data-plyr-embed-id can either be the video ID or URL for the media.

Vimeo

Much the same as YouTube above.

<div class="plyr__video-embed" id="player">
  <iframe
    src="https://player.vimeo.com/video/76979871?loop=false&amp;byline=false&amp;portrait=false&amp;title=false&amp;speed=true&amp;transparent=0&amp;gesture=media"
    allowfullscreen
    allowtransparency
    allow="autoplay"
  ></iframe>
</div>

Or the <div> non progressively enhanced method:

<div id="player" data-plyr-provider="vimeo" data-plyr-embed-id="76979871"></div>

JavaScript

You can use Plyr as an ES6 module as follows:

import Plyr from 'plyr';

const player = new Plyr('#player');

Alternatively you can include the plyr.js script before the closing </body> tag and then in your JS create a new instance of Plyr as below.

<script src="path/to/plyr.js"></script>
<script>
  const player = new Plyr('#player');
</script>

See initialising for more information on advanced setups.

You can use our CDN (provided by Cloudflare) for the JavaScript. There's 2 versions; one with and one without polyfills. My recommendation would be to manage polyfills separately as part of your application but to make life easier you can use the polyfilled build.

<script src="https://cdn.plyr.io/3.7.8/plyr.js"></script>

...or...

<script src="https://cdn.plyr.io/3.7.8/plyr.polyfilled.js"></script>

CSS

Include the plyr.css stylesheet into your <head>.

<link rel="stylesheet" href="path/to/plyr.css" />

If you want to use our CDN (provided by Cloudflare) for the default CSS, you can use the following:

<link rel="stylesheet" href="https://cdn.plyr.io/3.7.8/plyr.css" />

SVG Sprite

The SVG sprite is loaded automatically from our CDN (provided by Cloudflare). To change this, see the options below. For reference, the CDN hosted SVG sprite can be found at https://cdn.plyr.io/3.7.8/plyr.svg.

Self hosting

If you don't want to create a build system to include Plyr as an npm module, you can use the pre-built files. You have a few options:

  • Download the files from the CDN links above, they're already minified.
  • Download the files from unpkg or similar services.
  • Build the project yourself using npm i && npm run build, which installs the dependencies and spits out a build to dist.

Ads

Plyr has partnered up with vi.ai to offer monetization options for your videos. Getting setup is easy:

Any questions regarding the ads can be sent straight to vi.ai and any issues with rendering raised through GitHub issues.

If you do not wish to use Vi, you can set your own ads.tagUrl option.

Advanced

Customizing the CSS

If you want to change any design tokens used for the rendering of the player, you can do so using CSS Custom Properties.

Here's a list of the properties and what they are used for:

You can set them in your CSS for all players:

:root {
  --plyr-color-main: #1ac266;
}

...or for a specific class name:

.player {
  --plyr-color-main: #1ac266;
}

...or in your HTML:

<video class="player" style="--plyr-color-main: #1ac266;">...</video>

Sass

You can use plyr.scss file included in /src/sass as part of your build and change variables to suit your design. The Sass requires you to use autoprefixer (you should be already!) as all declarations use the W3C definitions.

The HTML markup uses the BEM methodology with plyr as the block, e.g. .plyr__controls. You can change the class hooks in the options to match any custom CSS you write. Check out the JavaScript source for more on this.

SVG

The icons used in the Plyr controls are loaded in an SVG sprite. The sprite is automatically loaded from our CDN by default. If you already have an icon build system in place, you can include the source plyr icons (see /src/sprite for source icons).

Using the iconUrl option

You can however specify your own iconUrl option and Plyr will determine if the url is absolute and requires loading by AJAX/CORS due to current browser limitations or if it's a relative path, just use the path directly.

If you're using the <base> tag on your site, you may need to use something like this: svgfixer.js

More info on SVG sprites here: http://css-tricks.com/svg-sprites-use-better-icon-fonts/ and the AJAX technique here: http://css-tricks.com/ajaxing-svg-sprite/

Cross Origin (CORS)

You'll notice the crossorigin attribute on the example <video> elements. This is because the TextTrack captions are loaded from another domain. If your TextTrack captions are also hosted on another domain, you will need to add this attribute and make sure your host has the correct headers setup. For more info on CORS checkout the MDN docs: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Captions

WebVTT captions are supported. To add a caption track, check the HTML example above and look for the <track> element. Be sure to validate your caption files.

JavaScript

Initializing

You can specify a range of arguments for the constructor to use:

Note: If a NodeList, Array, or jQuery object are passed, the first element will be used for setup. To setup multiple players, see multiple players below.

Single player

Passing a CSS string selector that's compatible with querySelector:

const player = new Plyr('#player');

Passing a HTMLElement:

const player = new Plyr(document.getElementById('player'));
const player = new Plyr(document.querySelector('.js-player'));

The HTMLElement or string selector can be the target <video>, <audio>, or <div> wrapper for embeds.

Multiple players

You have two choices here. You can either use a simple array loop to map the constructor:

const players = Array.from(document.querySelectorAll('.js-player')).map((p) => new Plyr(p));

...or use a static method where you can pass a CSS string selector, a NodeList, an Array of HTMLElement, or a JQuery object:

const players = Plyr.setup('.js-player');

Both options will also return an array of instances in the order of they were in the DOM for the string selector or the source NodeList or Array.

Options

The second argument for the constructor is the options object:

const player = new Plyr('#player', {
  title: 'Example Title',
});

Options can be passed as an object to the constructor as above or as JSON in data-plyr-config attribute on each of your target elements:

<video src="/path/to/video.mp4" id="player" controls data-plyr-config='{ "title": "Example Title" }'></video>

Note the single quotes encapsulating the JSON and double quotes on the object keys. Only string values need double quotes.

  1. Vimeo only
  2. Autoplay is generally not recommended as it is seen as a negative user experience. It is also disabled in many browsers. Before raising issues, do your homework. More info can be found here:
  1. YouTube does not support programatically toggling the native fullscreen player via it's API. This means on iOS you have two options, neither being perfect:
  • Use the fallback/faux fullscreen option which covers the whole viewport (this is the default)
  • Set playsinline to false and/or fullscreen.iosNative to true - either option hides the fullscreen toggle in the UI (because of the above API issue) and means iOS will play the video in it's native player.

API

There are methods, setters and getters on a Plyr object.

Object

The easiest way to access the Plyr object is to set the return value from your call to the constructor to a variable. For example:

const player = new Plyr('#player', {
  /* options */
});

You can also access the object through any events:

element.addEventListener('ready', (event) => {
  const player = event.detail.plyr;
});

Methods

Example method use:

player.play(); // Start playback
player.fullscreen.enter(); // Enter fullscreen
  1. For HTML5 players, play() will return a Promise for most browsers - e.g. Chrome, Firefox, Opera, Safari and Edge according to MDN at time of writing.

Getters and Setters

Example setters:

player.volume = 0.5; // Sets volume at 50%
player.currentTime = 10; // Seeks to 10 seconds

Example getters:

player.volume; // 0.5;
player.currentTime; // 10
player.fullscreen.active; // false;
  1. HTML5 only

The .source setter

This allows changing the player source and type on the fly.

Video example:

player.source = {
  type: 'video',
  title: 'Example title',
  sources: [
    {
      src: '/path/to/movie.mp4',
      type: 'video/mp4',
      size: 720,
    },
    {
      src: '/path/to/movie.webm',
      type: 'video/webm',
      size: 1080,
    },
  ],
  poster: '/path/to/poster.jpg',
  previewThumbnails: {
    src: '/path/to/thumbnails.vtt',
  },
  tracks: [
    {
      kind: 'captions',
      label: 'English',
      srclang: 'en',
      src: '/path/to/captions.en.vtt',
      default: true,
    },
    {
      kind: 'captions',
      label: 'French',
      srclang: 'fr',
      src: '/path/to/captions.fr.vtt',
    },
  ],
};

Audio example:

player.source = {
  type: 'audio',
  title: 'Example title',
  sources: [
    {
      src: '/path/to/audio.mp3',
      type: 'audio/mp3',
    },
    {
      src: '/path/to/audio.ogg',
      type: 'audio/ogg',
    },
  ],
};

YouTube example:

player.source = {
  type: 'video',
  sources: [
    {
      src: 'bTqVqk7FSmY',
      provider: 'youtube',
    },
  ],
};

Vimeo example

player.source = {
  type: 'video',
  sources: [
    {
      src: '76979871',
      provider: 'vimeo',
    },
  ],
};

Note: src property for YouTube and Vimeo can either be the video ID or the whole URL.

  1. HTML5 only

Events

You can listen for events on the target element you setup Plyr on (see example under the table). Some events only apply to HTML5 audio and video. Using your reference to the instance, you can use the on() API method or addEventListener(). Access to the API can be obtained this way through the event.detail.plyr property. Here's an example:

player.on('ready', (event) => {
  const instance = event.detail.plyr;
});

Standard Media Events

HTML5 only

YouTube only

Note: These events also bubble up the DOM. The event target will be the container element.

Some event details borrowed from MDN.

Embeds

YouTube and Vimeo are currently supported and function much like a HTML5 video. Similar events and API methods are available for all types. However if you wish to access the API's directly. You can do so via the embed property of your player object - e.g. player.embed. You can then use the relevant methods from the third party APIs. More info on the respective API's here:

Note: Not all API methods may work 100%. Your mileage may vary. It's better to use the Plyr API where possible.

Shortcuts

By default, a player will bind the following keyboard shortcuts when it has focus. If you have the global option to true and there's only one player in the document then the shortcuts will work when any element has focus, apart from an element that requires input.

Preview thumbnails

It's possible to display preview thumbnails as per the demo when you hover over the scrubber or while you are scrubbing in the main video area. This can be used for all video types but is easiest with HTML5 of course. You will need to generate the sprite or images yourself. This is possible using something like AWS transcoder to generate the frames and then combine them into a sprite image. Sprites are recommended for performance reasons - they will be much faster to download and easier to compress into a small file size making them load faster.

You can see the example VTT files here and here for how the sprites are done. The coordinates are set as the xywh hash on the URL in the order X Offset, Y Offset, Width, Height (e.g. 240p-00001.jpg#xywh=1708,480,427,240 is offset 1708px from the left, 480px from the top and is 427x240px. If you want to include images per frame, this is also possible but will be slower, resulting in a degraded experience.

Fullscreen

Fullscreen in Plyr is supported by all browsers that currently support it.

Browser support

Plyr supports the last 2 versions of most modern browsers.

  1. Mobile Safari on the iPhone forces the native player for <video> unless the playsinline attribute is present. Volume controls are also disabled as they are handled device wide.
  2. Native player used (no support for <progress> or <input type="range">) but the API is supported. No native fullscreen support, fallback can be used (see options).
  3. Polyfills required. See below.

Polyfills

Plyr uses ES6 which isn't supported in all browsers quite yet. This means some features will need to be polyfilled to be available otherwise you'll run into issues. We've elected to not burden the ~90% of users that do support these features with extra JS and instead leave polyfilling to you to work out based on your needs.

Checking for support

You can use the static method to check for support. For example

const supported = Plyr.supported('video', 'html5');

The arguments are:

  • Media type ('audio' | 'video')
  • Provider ('html5' | 'youtube' | 'vimeo')

Disable support programmatically

The enabled option can be used to disable certain User Agents. For example, if you don't want to use Plyr for smartphones, you could use:

{
  enabled: !/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
}

If a User Agent is disabled but supports <video> and <audio> natively, it will use the native player.

Plugins & Components

Some awesome folks have made plugins for CMSs and Components for JavaScript frameworks:

Issues

If you find anything weird with Plyr, please let us know using the GitHub issues tracker.

Author

Plyr is developed by @sam_potts / sampotts.me with help from the awesome contributors

Donate

Plyr costs money to run, not only my time. I donate my time for free as I enjoy building Plyr but unfortunately have to pay for domains, hosting, and more. Any help with costs is appreciated...

Mentions

Used by

If you want to be added to the list, open a pull request. It'd be awesome to see how you're using Plyr 😎

Useful links and credits

Thanks

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

Copyright and License

The MIT license