Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

openplayerjs

Package Overview
Dependencies
Maintainers
1
Versions
88
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

openplayerjs

HTML5 video and audio player

  • 1.16.8
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
3K
increased by15.47%
Maintainers
1
Weekly downloads
 
Created
Source

OpenPlayer.js

openplayerjs

NPM

Tweet JSDelivr Build Status

This awesome media player mimics the HTML5 video/audio methods/events/properties, and integrates the most popular libraries to play MP4/MP3, HLS and M(PEG)-DASH, among others.

It also has the ability to play VMAP, VAST and VPAID Ads in an effortless way!

To see the unleashed power of OpenPlayerJS, check our Demo folder and our Code Samples.

We are constantly looking to see if OpenPlayerJS meets your needs; if it does not, please submit an issue indicating what scenarios OpenPlayerJS it's lacking and we will add a sample to demonstrate the solution(s). Your feedback is always extremely valuable!

Advantages of using OpenPlayerJS

  • Supports IE11+ (Win8) and all modern browsers: its CSS and code is compatible with all modern browsers. IE11+ on Win7 requires an MP4/MP3 fallback to work correctly.
  • Lightweight library: Less than 20kb when gzipped.
  • Monetize video and audio content with video advertising using VAST, VPAID or VMAP Ads, supported by the amazing Interactive Media Ads SDK (IMA SDK) library.
  • Multi Ads: OpenPlayerJS is one of the few players that provides the ability to use a single VAST/VPAID source or a VAST/VPAID playlist from several different sources (including URLs and valid XML strings). Usually, advertisers take only part of the total traffic of a website. As a result, users view only 10% of the total advertising per day (besides, once the user has seen the Ad, the advertiser's cookie is set, so it will not perform a new request through the server. Therefore, a website benefits when connecting multiple Ads streams.
  • Play Ads indefinitely: OpenPlayerJS has the ability to set an ad and play it in an infinite loop; this is desired for ads that are in a heavy text page.
  • Enhance player controls: You can add your own buttons (see example above).
  • Accessibility is a priority: You can even create specific styling for high contrast mode, and support visually impaired people and improve accessibility. See High Contrast Proof CSS Sprites for more details.
  • Always up-to-date: Relying on Snyk, OpenPlayerJS uses the latest and greatest versions of the packages to ensure it is always updated; also, IMA SDK, hls.js and dash.js use even-green paths from their recommended CDN sources to they will be always providing the latest upgrades for OpenPlayerJS.
  • Smart autoplay algorithm: Have you ever worried to know if your browser will autoplay media correctly? Forget about it! OpenPlayerJS runs a simple but yet powerful algorithm to check your browser's autoplay capabilities.
  • Responsive: Always adapts to the screen size (and resize) by default, for both video/audio tags; a new fill mode is also included to scale and crop media relative to its parent container.
  • Support for local and remote captions for both video and audio, even without including the crossorigin attribute.
  • Use it without dependencies, since this player is written in Typescript, compiled and ready to be used!

Getting Started

OpenPlayerJS requires minimum steps to be installed.

Prerequisites

The dist folder contains the files you will need yo use this awesome library. To obtain it, you can download the repository from https://github.com/openplayerjs/openplayerjs.git or use NPM to get it:

npm install openplayerjs

CDN is also available for better performance. See next section for more details.

Installation

Since this player uses HTML5 markup, all the attributes for video/audio tags are available. The only 3 requirements to invoke the player are:

  • A valid media source, such as MP4, MP3, HLS or M(PEG)-DASH.
  • The controls and playsinline attributes to provide cross-browser support.
  • The op-player op-player__media class names to invoke the player.

That's it!

<html>
    <head>
        <link rel="stylesheet" href="/path/to/openplayer.css">
    </head>
    <body>
        <video class="op-player op-player__media" controls playsinline>
            <source src="/path/to/video.mp4" type="video/mp4">
        </video>
        <script src="/path/to/openplayer.js"></script>
    </body>
</html>

We encourage you to use a CDN service for optimal performance. To do it, in the snippet above, replace /path/to/openplayer.css and /path/to/openplayer.js with https://cdn.jsdelivr.net/npm/openplayerjs@[version]/dist/openplayer.min.css and https://cdn.jsdelivr.net/npm/openplayerjs@[version]/dist/openplayer.min.js.

NOTE: As stated at jsDeliver website, it is recommended to use a [version] number in the URL rather than @latest for production.

If you are planning to use OpenPlayer in a Node project, you can:

// Using as module
var openplayer = require('/path/to/openplayerjs');

// or importing the library (ES6)
import OpenPlayer from 'openplayerjs';

Adding Closed Captions

OpenPlayerJS supports the use of VTT closed captions by adding the track tag as indicated in the following snippet; you can also use the default attribute in the tag, but as a rule of thumb, all the attributes displayed below in the track tag MUST be there; otherwise, closed captions won't be displayed:

<html>
    <head>
        <link rel="stylesheet" href="/path/to/openplayer.css">
    </head>
    <body>
        <video class="op-player op-player__media" controls playsinline>
            <source src="/path/to/video.mp4" type="video/mp4">
            <track kind="subtitles" src="/path/to/video.vtt" srclang="en" label="English">
        </video>
        <script src="/path/to/openplayer.js"></script>
    </body>
</html>

Usage with Javascript

Sometimes you need more flexibility instantiating the player; for example, adding cache busting to the VAST/VPAID URL, having a list of Ads URLs, adding new controls, etc. So, for that case, remove the op-player class from the video/audio tag (leaving op-player__media to preserve styles), and, with Javascript, use the following setup:

var player = new OpenPlayer('[player ID]', [valid VAST/VPAID URL|List of VAST/VPAID URLs], [`true|false` for fullscreen effect by default], {
    // Controls configuration by default; `levels` can be added as well since it's an optional feature;
    // Each one of the items will have in their class name the `op-control__[left|middle|right]` according
    // to the controls' structure listed below
    controls: {
        left: ['play', 'time', 'volume'],
        middle: ['progress'],
        right: ['captions', 'settings', 'fullscreen'],
    },
    // Allow items to be contained in a different space outside of `Settings`
    detachMenus,
    // Number of ms that takes the player to hide the Play button once it starts playing (video only)
    // (bt default, `350`)
    hidePlayBtnTimer,
    // Number of seconds to rewind/forward media
    // (by default, player will rewind/forward 5% of the total duration of media)
    step,
    // Initial volume of media in decimal numbers (by default, `1`)
    startVolume,
    // Initial play time of media in seconds (by default, `0`)
    startTime,
    // Allow progress bar to be displayed when using live streamings (by default, `false`)
    showLiveProgress,
    // Allow loader to be displayed when loading video (by default, `false`)
    showLoaderOnInit,
    // Callback to be executed once an error is found (default, `console.error`)
    // Params passed: Custom event with `detail: { type: 'HTML5|Ads|M(PEG)-DASH|HLS', message, data },`
    onError,
    ads: {
        // If set to `false`, allows the user to overwrite the default mechanism to skip Ads
        autoPlayAdBreaks,
        // If set to `true`, load `ima3_debug.js` file for debugging purposes
        debug,
        // If set to `true`, play infintely an Ad
        loop,
        // Maximum number of redirects before the subsequent redirects will be denied (by default, `4`)
        numRedirects,
        // Custom path/URL to IMA SDK
        url,
    },
    hls: {
        // all HLS options available at https://github.com/video-dev/hls.js/blob/master/docs/API.md#fine-tuning.
    },
    dash: {
        // Possible values are SW_SECURE_CRYPTO, SW_SECURE_DECODE, HW_SECURE_CRYPTO, HW_SECURE_CRYPTO,
        // HW_SECURE_DECODE, HW_SECURE_ALL
        robustnessLevel,
        // object containing property names corresponding to key system name strings (e.g. "org.w3.clearkey") and
        // associated values being instances of ProtectionData
        // (http://vm2.dashif.org/dash.js/docs/jsdocs/MediaPlayer.vo.protection.ProtectionData.html)
        drm,
    },
});
// Don't forget to start the player
player.init();

NOTE: In order to use this setup, the video/audio tag(s) need a unique ID.

Usage with Next.js/React

Using OpenPlayerJS with React and Next.js is pretty straightforward, as you can see in the example below.

import React, { useEffect } from 'react';
import OpenPlayer from 'openplayerjs';

export default function Sample() {
    useEffect(() => {
        const player = new OpenPlayer('player');
        player.init();
    }, []);

    return (
        <div>
            <video id='player' className='op-player__media' controls playsInline>
                <source src='https://my.test.com/video.mp4' type='video/mp4' />
            </video>
        </div>
    );

API

If you need more control over the player, OpenPlayerJS stores an instance of each player in the document. To have access to a specific instance, use the media id and use OpenPlayer.instances element.

NOTE: if an id attribute is not detected, OpenPlayerJS will autogenerate one for you.

// Selects the first video/audio that uses OpenPlayer
var id = document.querySelector('.op-player').id;
var player = OpenPlayerJS.instances[id];

The methods supported by the OpenPlayer instance are:

MethodDescription
playPlay media. If Ads are detected, different methods than the native ones are triggered with this operation.
pausePause media. If Ads are detected, different methods than the native ones are triggered with this operation.
loadLoad media. HLS and M(PEG)-DASH perform more operations during loading if browser does not support them natively.
addCaptionsAppend a new <track> tag to the video/audio tag and dispatch event so it gets registered/loaded in the player, via controlschanged event.
addControlAppend a new button to the video/audio tag with the possibility dispatch a custom callback so it gets registered/loaded in the player, via controlschanged event. It requires an object with icon URL/path, title for the button, the position (right or left) of the button and a click callback to dispatch an action.
destroyDestroy OpenMedia Player instance (including all events associated) and return the video/audio tag to its original state.
getAdRetrieve an instance of the Ads object.
getMediaRetrieve an instance of the Media object.
activeElementRetrieve the current media object (could be Ads or any other media type).
getContainerRetrieve the parent element (with op-player class) of the native video/audio tag.
getControlsRetrieve an instance of the controls object used in the player instance.
getElementRetrieve the original video/audio tag.
getEventsRetrieve the events attached to the player.
initCreate all the markup and events needed for the player.
isAdCheck if current media is an instance of an Ad.
isMediaCheck if current media is an instance of a native media type.
idRetrieve current player's unique identifier.
srcRetrieve/set the current Source list associated with the player.

Events

Using the code below, you can attach/dispatch any valid event, using CustomEvent, like this:

player.getElement().addEventListener('ended', function() {
    console.log('Your code when media ends playing');
});

var event = new CustomEvent('ended');
player.getElement().dispatchEvent(event);

All HTML5 media events are supported by OpenPlayerJS, and it incorporates some custom ones, mostly related to Ads:

EventDescription
controlshiddenEvent executed when controls timer stops and hides control bar (video only).
controlschangedEvent triggered when an element modified the state of the controls and they regenerate (i.e., adding new caption).
captionschangedEvent triggered when user changes the current caption by selecting a new one from the Settings menu.
playererrorEvent executed when any error has occurred within the OpenPlayer instance; a response will be sent via onError config callback. See Usage with Javascript for more details.
playerdestroyedEvent executed when an instance of OpenPlayer is destroyed (useful to remove extra elements created with the player's help).
adsloadedEvent when Ads have been loaded successfully and can be played.
adsstartEvent when Ads start being played.
adsfirstquartileEvent triggered when Ad reached the first quarter of its length.
adsmidpointEvent triggered when Ad reached half of its length.
adsthirdquartileEvent triggered when Ad reached the third quarter of its length.
adscompleteEvent triggered when Ad reached the end of its length.
adsskippedEvent triggered when user skips the Ad.
adsvolumeChangeEvent triggered when user increases/decreases the volume of Ad.
adsallAdsCompletedEvent triggered when all Ads have been played.
adsmediaendedEvent executed when an Ad is going to be played after media has ended playing (currently used to change the Replay icon to Pause when playing a postroll Ad).

In addition to the list above, all HLS events and HLS error events are supported using the same approach described above, including all their details. For the error ones, they are classified as networkError, mediaError, muxError and otherError.

Code Samples

  1. No configuration (only DOM classes)
  2. Minimal configuration
  3. Using fill mode
  4. Using Ads
  5. Removing controls and using preload="none"
  6. Add source after initialization (useful for AJAX)
  7. Using Levels
  8. Playing HLS streaming with DRM (Encryption)
  9. M(PEG)-DASH with Ads
  10. Basic playlist (video and audio)
  11. Ads playlist (multiple URLs)
  12. Retrieve data from audio streaming (HLS)
  13. YouTube video (using plugin)
  14. Addition of a custom control
  15. OpenPlayerJS with Next.js

Built With

Authors

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License - see the LICENSE.md file for details.

Keywords

FAQs

Package last updated on 07 Jul 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc