A simple, accessible and customizable HTML5, YouTube and Vimeo media player.
We wanted a lightweight, accessible and customizable media player that supports modern browsers. Sure, there are many other players out there but we wanted to keep things simple, using the right elements for the job.
- Accessible - full support for VTT captions and screen readers
- Lightweight - under 10KB minified and gzipped
- Customisable - make the player look how you want with the markup you want
- Semantic - 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 - as you'd expect these days
- HTML Video & Audio - support for both formats
- Embedded Video - support for YouTube and Vimeo video playback
- API - toggle playback, volume, seeking, and more
- Universal events - no messing around with Vimeo and YouTube APIs, all events are universal across formats
- Fullscreen - supports native fullscreen with fallback to "full window" modes
- i18n support - support for internationalization of controls
- No dependencies - written in "vanilla" JavaScript, no jQuery required
- SASS and LESS provided - If you like these over plain CSS
Oh and yes, it works with Bootstrap.
Check out the changelog to see what's new with Plyr.
- Streaming
- Playback speed
- Playlists
- Multiple language captions (with selection)
- Audio captions ... and whatever else has been raised in issues
If you have any cool ideas or features, please let me know by creating an issue or, of course, forking and sending a pull request.
Check docs/index.html
and docs/src/js/docs.js
for an example setup.
Heads up: the example index.html
file needs to be served from a webserver (such as Apache, Nginx, IIS or similar) unless you change the file sources to include http or https. e.g. change //cdn.plyr.io/1.6.18/plyr.js
to https://cdn.plyr.io/1.6.18/plyr.js
Using npm
, you can grab Plyr:
npm install plyr
https://www.npmjs.com/package/plyr
If bower is your thing, you can grab Plyr using:
bower install plyr
http://bower.io/search/?q=plyr
More info on setting up dependencies can be found in the Bower Docs
The awesome @louisrudner has created an ember component, available by running:
ember addon:install ember-cli-plyr
More info is on npm and GitHub
If you want to use our CDN, you can use the following:
<link rel="stylesheet" href="https://cdn.plyr.io/1.6.18/plyr.css">
<script src="https://cdn.plyr.io/1.6.18/plyr.js"></script>
The SVG sprite/defs file can be found here: https://cdn.plyr.io/1.6.18/plyr.svg
.
If you want to use the default css, add the plyr.css
file from /dist
into your head, or even better use plyr.less
or plyr.scss
file included in /src
in your build to save a request.
<link rel="stylesheet" href="dist/plyr.css">
The default setup uses the BEM methodology with plyr
as the block, e.g. .plyr__controls
. You can change the class hooks in the options. Check out the source for more on this.
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).
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/
The only extra markup that's needed to use plyr is a <div>
wrapper. Replace the source, poster and captions with urls for your media.
<div class="plyr">
<video poster="/path/to/poster.jpg" controls>
<!-- Video files -->
<source src="/path/to/video.mp4" type="video/mp4">
<source src="/path/to/video.webm" type="video/webm">
<!-- Text track file -->
<track kind="captions" label="English captions" src="/path/to/captions.vtt" srclang="en" default>
<!-- Fallback for browsers that don't support the <video> element -->
<a href="/path/to/movie.mp4">Download</a>
</video>
</div>
And the same for <audio>
<div class="plyr">
<audio controls>
<!-- Audio files -->
<source src="/path/to/audio.mp3" type="audio/mp3">
<source src="/path/to/audio.ogg" type="audio/ogg">
<!-- Fallback for browsers that don't support the <audio> element -->
<a href="/path/to/audio.mp3">Download</a>
</audio>
</div>
For YouTube and Vimeo, Plyr uses the standard YouTube API markup (an empty <div>
):
<div class="plyr">
<div data-video-id="bTqVqk7FSmY" data-type="youtube"></div>
</div>
<div class="plyr">
<div data-video-id="143418951" data-type="vimeo"></div>
</div>
You'll notice the crossorigin
attribute on the example <video>
and <audio>
elements. This is because the media is loaded from another domain. If your media is hosted on another domain, you may need to add this attribute.
More info on CORS here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
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
Here's an example of a default setup:
<script src="https://cdn.plyr.io/1.6.18/plyr.js"></script>
<script>plyr.setup();</script>
This will look for all elements with the specified container classname (default is plyr
) and setup plyr on each element found. You can specify other options, including a different selector hook below. The container classname will be added to the specified element(s) if it is not already present (for the CSS).
You can initialize the player a few other ways:
Passing a NodeList:
plyr.setup(document.querySelectorAll('.js-plyr'), options);
Passing a HTMLElement:
plyr.setup(document.querySelector('.js-plyr'), options);
Passing a string selector:
plyr.setup('.js-plyr', options);
Passing just the options object:
plyr.setup(options);
Some touch browsers (particularly Mobile Safari on iOS) seem to have issues with <input type="range">
elements whereby touching the track to set the value doesn't work and sliding the thumb can be tricky. To combat this, I've created RangeTouch which I'd recommend including in your solution. It's a tiny script with a nice benefit for users on touch devices.
Options must be passed as an object to the setup()
method as above or as JSON in data-plyr
attribute on each of your target elements:
<div class="plyr" data-plyr='{ title: "testing" }'>
Note the single quotes encapsulating the JSON and double quotes on the object keys.
Option | Type | Default | Description |
---|---|---|---|
enabled |
Boolean | true |
Completely disable Plyr. This would allow you to do a User Agent check or similar to programmatically enable or disable Plyr for a certain UA. Example below. |
html |
String | See controls.md |
See controls.md for more info on how the html needs to be structured. |
controls |
Array | ['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'captions', 'fullscreen'] |
Toggle which control elements you would like to display when using the default controls html. If you specify a html option, this is redundant. The default value is to display everything. |
i18n |
Object | See controls.md |
Used for internationalization (i18n) of the tooltips/labels within the buttons. |
loadSprite |
Boolean | true |
Load the SVG sprite specified as the iconUrl option (if a URL). If false , it is assumed you are handling sprite loading yourself. |
iconUrl |
String | null |
Specify a URL or path to the SVG sprite. See the SVG section for more info. |
iconPrefix |
String | plyr |
Specify the id prefix for the icons used in the default controls (e.g. "plyr-play" would be "plyr"). This is to prevent clashes if you're using your own SVG sprite but with the default controls. Most people can ignore this option. |
debug |
Boolean | false |
Display debugging information on what Plyr is doing. |
autoplay |
Boolean | false |
Autoplay the media on load. This is generally advised against on UX grounds. It is also disabled on iOS (an Apple limitation). |
seekTime |
Number | 10 |
The time, in seconds, to seek when a user hits fast forward or rewind. |
volume |
Number | 5 |
A number, between 1 and 10, representing the initial volume of the player. |
clickToPlay |
Boolean | true |
Click (or tap) of the video container will toggle pause/play. |
disableContextMenu |
Boolean | true |
Disable right click menu on video to help as very primitive obfuscation to prevent downloads of content. |
hideControls |
Boolean | true |
Hide video controls automatically after 2s of no mouse or focus movement, on control element blur (tab out), on playback start or entering fullscreen. As soon as the mouse is moved, a control element is focused or playback is paused, the controls reappear instantly. |
showPosterOnEnd |
Boolean | false |
This will restore and *reload* HTML5 video once playback is complete. Note: depending on the browser caching, this may result in the video downloading again (or parts of it). Use with caution. |
tooltips |
Object | { controls: false, seek: true } |
controls: Display control labels as tooltips on :hover & :focus (by default, the labels are screen reader only).
seek: Display a seek tooltip to indicate on click where the media would seek to. |
duration |
Number | null |
Specify a custom duration. |
displayDuration |
Boolean | true |
Displays the duration of the media on the "metadataloaded" event (on startup) in the current time display. This will only work if the `preload` attribute is not set to `none` (or is not set at all) and you choose not to display the duration (see controls option). |
selectors |
Object | — | See plyr.js in /src for more info. You probably don't need to change any of these. |
listeners |
Object | — | Allows early binding of event listeners to the controls. See controls above for list of controls and see plyr.js in /src for more info. |
classes |
Object | — | Similar to above, these are the classes added to the player when state changes occur. |
captions |
Object | — | One property defaultActive which toggles if captions should be on by default. The default value is false . |
fullscreen |
Object | — | See below |
storage |
Object | — | Two properties; enabled which toggles if local storage should be enabled (if the browser supports it). The default value is `true`. This enables storing user settings, currently it only stores volume but more will be added later. The second property key is the key used for the local storage. The default is plyr_volume until more settings are stored. |
Option | Type | Default | Description |
---|---|---|---|
enabled |
Boolean | true |
Toggles if fullscreen should be enabled (if the browser supports it). |
fallback |
Boolean | true |
Enable a full viewport view for older browsers. |
allowAudio |
Boolean | false |
Allow audio play to toggle fullscreen. This will be more useful later when posters are supported. |
A plyr
object is added to any element that Plyr is initialized on. You can then control the player by accessing methods in the plyr
object.
There are two ways to access the instance, firstly you re-query the element container you used for setup (e.g. .js-plyr
) like so:
var player = document.querySelector('.js-plyr').plyr;
Or you can use the returned object from your call to the setup method:
var player = plyr.setup('.js-plyr')[0];
This will return an array of plyr instances setup, so you need to specify the index of the instance you want. This is less useful if you are setting up multiple instances. You can listen for the setup
event documented below which will return each instance one by one, as they are setup (in the plyr
key of the event object).
Once you have your instance, you can use the API methods below on it. For example to pause it:
player.pause();
Here's a list of the methods supported:
Method | Parameters | Description |
---|---|---|
play() |
— | Plays the media |
pause() |
— | Pauses the media |
restart() |
— | Restarts playback |
rewind(...) |
Number | Rewinds by the provided parameter, in seconds. If no parameter is provided, the default seekInterval is used (10 seconds). |
forward(...) |
Number | Fast forwards by the provided parameter, in seconds. If no parameter is provided, the default seekInterval is used (10 seconds). |
seek(...) |
Number | Seeks the media to the provided parameter, time in seconds. |
setVolume(...) |
Number | Sets the player volume to the provided parameter. The value should be between 0 (muted) and 10 (loudest). If no parameter is provided, the default volume is used (5). Values over 10 are ignored. |
togglePlay() |
Boolean | Toggles playback for the player based on either the boolean argument or it's current state. |
toggleMute() |
— | Toggles mute for the player. |
toggleCaptions() |
— | Toggles whether captions are enabled. |
toggleFullscreen() |
Event | Toggles fullscreen. This can only be initiated by a user gesture due to browser security, i.e. a user event such as click. |
isFullscreen() |
— | Boolean returned if the player is in fullscreen. |
support(...) |
String | Determine if a player supports a certain MIME type. This is not supported for embedded content (YouTube). |
source(...) |
Object or undefined |
Get/Set the media source.
Object See below YouTube Currently this API method only accepts a YouTube ID when used with a YouTube player. I will add URL support soon, along with being able to swap between types (e.g. YouTube to Audio or Video and vice versa.) undefined Returns the current media source url. Works for both native videos and embeds. |
poster(...) |
String | Set the poster url. This is supported for the video element only. |
destroy() |
— | Destroys the plyr UI and any media event listeners, effectively restoring to the previous state before setup() was called. |
restore() |
— | Reverses the effects of the destroy() method, restoring the UI and listeners. |
This allows changing the plyr source and type on the fly.
Video example:
player.source({
type: 'video',
title: 'Example title',
sources: [{
src: '/path/to/movie.mp4',
type: 'video/mp4'
},
{
src: '/path/to/movie.webm',
type: 'video/webm'
}],
poster: '/path/to/poster.jpg',
tracks: [{
kind: 'captions',
label: 'English',
srclang:'en',
src: '/path/to/captions.vtt',
default: true
}]
});
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',
title: 'Example title',
sources: [{
src: 'bTqVqk7FSmY',
type: 'youtube'
}]
});
Vimeo example
player.source({
type: 'video',
title: 'Example title',
sources: [{
src: '143418951',
type: 'vimeo'
}]
});
Some more details on the object parameters
Key | Type | Description |
---|---|---|
type |
String | Options are video , audio , youtube and vimeo |
title |
String | Title of the new media. Used for the aria labelling. |
sources |
Array | This is an array of sources. type is optional for YouTube and Vimeo when specifying an array. For YouTube and Vimeo media, only the video ID must be passed as the source as shown above. The keys of this object are mapped directly to HTML attributes so more can be added to the object if required. |
poster |
String | URL for the poster image (video only). |
tracks |
Array | An array of track objects. Each element in the array is mapped directly to a track element and any keys mapped directly to HTML attributes so as in the example above, it will render as ``. Booleans are converted to HTML5 value-less attributes. |
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.
Event name | HTML5 only | Description |
---|---|---|
canplay |
✔ | Sent when enough data is available that the media can be played, at least for a couple of frames. This corresponds to the HAVE_ENOUGH_DATA readyState . |
canplaythrough |
Sent when the ready state changes to CAN_PLAY_THROUGH , indicating that the entire media can be played without interruption, assuming the download rate remains at least at the current level. Note: Manually setting the currentTime will eventually fire a canplaythrough event in firefox. Other browsers might not fire this event. |
|
emptied |
✔ | The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it. |
ended |
Sent when playback completes. | |
error |
✔ | Sent when an error occurs. The element's error attribute contains more information. |
loadeddata |
✔ | The first frame of the media has finished loading. |
loadedmetadata |
✔ | The media's metadata has finished loading; all attributes now contain as much useful information as they're going to. |
loadstart |
✔ | Sent when loading of the media begins. |
pause |
Sent when playback is paused. | |
play |
Sent when playback of the media starts after having been paused; that is, when playback is resumed after a prior pause event. |
|
playing |
Sent when the media begins to play (either for the first time, after having been paused, or after ending and then restarting). | |
progress |
Sent periodically to inform interested parties of progress downloading the media. Information about the current amount of the media that has been downloaded is available in the media element's buffered attribute. |
|
seeked |
✔ | Sent when a seek operation completes. |
seeking |
✔ | Sent when a seek operation begins. |
stalled |
✔ | Sent when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. |
timeupdate |
The time indicated by the element's currentTime attribute has changed. |
|
volumechange |
Sent when the audio volume changes (both when the volume is set and when the muted attribute is changed). |
|
waiting |
✔ | Sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek). |
enterfullscreen |
User enters fullscreen (either the proper fullscreen or full-window fallback for older browsers) | |
exitfullscreen |
User exits fullscreen | |
captionsenabled |
Captions toggled on | |
captionsdisabled |
Captions toggled off | |
ready |
Triggered when initial setup is done or a source change has occurred. |
Details borrowed from: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events
Here's an example of binding an event listener:
document.querySelector('.js-plyr').addEventListener('ready', function(event) {
var player = event.target.plyr;
});
YouTube and Vimeo are currently supported and function much like a HTML5 video. Check the relevant documentation sections for any differences.
Plyr references a custom version of the Vimeo Froogaloop API as Vimeo have neglected to maintain the library and there were bugs with their version. You don't need to worry about including your own versions of the Vimeo or YouTube JavaScript APIs.
The native API's can be accessed through the embed
property of the plyr object. For example:
document.querySelector('.js-plyr').addEventListener('ready', function(event) {
var player = event.target.plyr;
// YouTube
console.log(player.embed.getVideoData());
// Vimeo
console.log(player.embed.api('getColor'));
});
More info on the respective API's here: YouTube API Reference Vimeo API Reference
Please note: not all API methods may work 100%. Your mileage may vary. It's better to use the universal plyr API where possible.
Fullscreen in Plyr is supported for all browsers that currently support it. If you're using the default CSS, you can also use a "full browser" mode which will use the full browser window by adding the plyr-fullscreen
class to your container.
Safari | Firefox | Chrome | Opera | IE9 | IE10+ |
✔¹ | ✔ | ✔ | ✔ | API² | ✔³ |
¹ Mobile Safari on the iPhone forces the native player for <video>
so no useful customization is possible. <audio>
elements have volume controls disabled.
² Native player used (no support for <progress>
or <input type="range">
) but the API is supported (v1.0.28+)
³ IE10 has no native fullscreen support, fallback can be used (see options)
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.
Any unsupported browsers will display links to download the media if the correct html is used.
There's an API method for checking support. You can call plyr.supported()
and optionally pass a type to it, e.g. plyr.supported("video")
. It will return an object with two keys; basic
meaning there's basic support for that media type (or both if no type is passed) and full
meaning there's full support for plyr.
If you find anything weird with Plyr, please let us know using the GitHub issues tracker.
Plyr is developed by @sam_potts / sampotts.me with help from the awesome contributors
- ProductHunt
- The Changelog
- HTML5 Weekly #177
- Responsive Design #149
- Web Design Weekly #174
- Hacker News
- Web Platform Daily
- LayerVault Designer News
- The Treehouse Show #131
- noupe.com
Let me know on Twitter I can add you to the above list. It'd be awesome to see how you're using Plyr :-)
Credit to the PayPal HTML5 Video player from which Plyr's caption functionality is ported from:
- PayPal's Accessible HTML5 Video Player
- The icons used in Plyr are Vicons plus some ones I made
- An awesome guide for Plyr in Japanese! by @arayutw
Also these links helped created Plyr: