Socket
Socket
Sign inDemoInstall

@brightspace-ui-labs/media-player

Package Overview
Dependencies
29
Maintainers
3
Versions
152
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @brightspace-ui-labs/media-player

A reusable media player component.


Version published
Weekly downloads
1.1K
increased by69.75%
Maintainers
3
Created
Weekly downloads
 

Readme

Source

media-player

NPM version

Note: this is a "labs" component. While functional, these tasks are prerequisites to promotion to BrightspaceUI "official" status:

A Lit element based media player component, designed for similarity across browsers. Capable of playing video and audio content.

Displaying video Example of video

Displaying audio Example of audio

Installation

To install from NPM:

npm install @brightspace-ui-labs/media-player

d2l-labs-media-player

<script type="module">
    import '@brightspace-ui-labs/media-player/media-player.js';
</script>
<d2l-labs-media-player src="/video.webm"></d2l-labs-media-player>

Attributes:

AttributeTypeDefaultDescription
allow-downloadBooleanfalseIf set, will allow the media to be downloaded.
autoplayBooleanfalseIf set, will play the media as soon as it has been loaded.
crossoriginStringnullIf set, will set the crossorigin attribute on the underlying media element to the set value.
download-filenameStringnullIf set along with allow-download, will use the provided value as the base of the filename (the extension will be automatically appended)
duration-hintNumber1Measured in seconds. If set and the duration cannot be determined automatically, this value will be used instead.
hide-captions-selectionBooleanfalseIf set, the menu item to configure captions is hidden.
hide-seek-barBooleanfalseIf set, the seek bar will not be shown.
loopBooleanfalseIf set, once the media has finished playing it will replay from the beginning.
media-type["video", "audio"]nullWhether the video or audio player should be rendered. If not set, a loading indicator will be displayed until set.
metadataJSONfalseMetadata JSON of the video, contains chapters and cuts data.
posterStringnullURL of the image to display in place of the media before it has loaded.
srcStringURL of the media to play. If multiple sources are desired, use <source> tags instead (see below).
thumbnailsStringIf set, will show thumbnails on preview. See below for required format.
play-in-viewBooleanfalseIf set, will stop the media playback if not in view
<!-- Render a media player with a source file and loop the media when it reaches the end -->

<d2l-labs-media-player loop src="./local-video.mp4"></d2l-labs-media-player>

Properties:

PropertyTypeGet/SetDescription
currentTimeNumberGet & SetCurrent time playback time of the media in seconds.
activeCueObjectGetVTTCue instance for the currently-displayed captions cue. If no cue is currently displayed, the value is null.
durationNumberGetTotal duration of the media in seconds.
endedBooleanGetWhether or not the video has ended.
pausedBooleanGetWhether or not the video is currently paused.
sourceType["audio", "video", "unknown"]GetThe source type of the media.
textTracks[TextTrack]GetThe TextTracks, for handling WebVTT. (See MDN link)
// Programatically determine the current playback time of the media player

console.log(`Current playback time of the media player = ${this.document.querySelector('d2l-labs-media-player').currentTime} sec`);

Methods:

MethodTypeDescription
exitFullscreen()voidRequests to exit fullscreen mode from the browser. Ignored if it is not playing video content, or if the video is not in fullscreen mode.
play()voidBegins playing the media. Ignored if the media is already playing.
pause()voidPauses the media. Ignored if the media is already paused.
requestFullscreen()voidRequests fullscreen mode from the browser. Ignored if it is not playing video content, or the video is already in fullscreen mode.
// Programatically pause the media player

this.document.querySelector('d2l-labs-media-player').pause();

Events:

EventDescription
cuechangeDispatched when the currently-displayed captions cue changes.
durationchangeDispatched when the video or media displayed has changed its duration
endedDispatched when the media has reached the end of its duration.
errorDispatched when the media failed to load.
loadeddataDispatched when the media at the current playback position has finished loading. Often the first frame.
loadedmetadataDispatched when the metadata for the media has finished loading.
playDispatched when the media begins playing.
pauseDispatched when the media is paused.
seekedDispatched when the user finishes navigating through the media's timeline using the seek bar.
seekingDispatched when the user starts navigating through the media's timeline using the seek bar.
timeupdateDispatched when the currentTime of the media player has been updated.
trackloadedDispatched when a track element has loaded.
trackloadfailedDispatched when a track element could not be loaded from the provided src attribute.
tracksmenuitemchangedDispatched when the tracks menu item has changed.
// Listen for the loadeddata event

this.document.querySelector('d2l-labs-media-player').addEventListener('loadeddata', () => {
	console.log('loadeddata event has been dispatched');
});

Multiple qualities using <source>

The media player supports switching to different qualities. If multiple <source> tags are present, a quality selector will be available in the menu. In this case, do not set src on d2l-labs-media-player.

<d2l-labs-media-player>
  <source src="sample-video-144p.mp4" label="SD">
  <source src="sample-video.mp4" label="HD" default>
</d2l-labs-media-player

Attributes

AttributeTypeDefaultDescription
labelString, requiredThe label for the track, displayed to the user for selection.
srcString, requiredThe URL of the source file.
defaultBooleanfalseThe source to be selected by default. If no source has the default attribute, then the first <source> tag is selected by default. Only one default should be set.

Showing thumbnails preview with thumbnails attribute

Provide a url to the thumbnails sprite image. This sprite is a grid of images taken from the video, at a set interval.

e.g. sample video thumbnails sprite Example thumbnails sprite

The thumbnail file name must use the following format: th<height>w<width>i<interval>-<hash>.[png|jpg]

  • width and height are the width/height px of each individual thumbnail
  • interval indicates how many seconds apart each thumbnail is

For example, a sprite image named th90w160i5-<hash>png has the thumbnails 5 seconds apart, with width 160px and height 90px.

AttributeRequiredDefaultDescription
hashoptional
heightoptional90pxHeight px of each individual thumbnail in the sprite.
intervalrequiredInterval in seconds between each thumbnail.
widthoptional160pxWidth px of each individual thumbnail in the sprite.

Chapters with metadata attribute

Provide metadata JSON e.g. getMetadata endpoint

Example format:

{
    "cuts": [
      "in": 20,
      "out": 30
    ],
    "chapters": [
      {
        "time": 0,
        "title": {
          "en": "Chapter One",
          "fr": "Chapitre Un"
        }
      },
      {
        "time": 30,
        "title": {
          "en": "Chapter Two",
          "fr": "Chapitre Deux"
        }
      },
      {
        "time": 70,
        "title": {
          "en": "Chapter Three",
          "fr": "Chapitre Trois"
        }
      }
    ]
}

Captions and Subtitles Using <track>

The media player supports captions and subtitles, provided as .srt or .vtt files. If any valid tracks are present, a captions menu will be presented in the settings menu with an item for each track.

<script type="module">
    import '@brightspace-ui-labs/media-player/media-player.js';
</script>
<d2l-labs-media-player src="/video.webm">
	<track src="/english-captions.srt" srclang="en" label="English" kind="captions">
	<track src="/french-captions.vtt" srclang="fr" label="French" kind="captions">
</d2l-labs-media-player>

Attributes

AttributeTypeDefaultDescription
kind["captions", "subtitles"], requiredThe kind of track.
labelString, requiredThe label for the track, displayed to the user for selection.
srcString, requiredThe URL of the source file.
srclangString, requiredThe language's code.
defaultBooleanfalseThe track to be selected by default. If D2L.MediaPlayer.Preferences.Track is defined in local storage, then it will take precedence over this attribute.
default-ignore-preferencesBooleanfalseSame as default, but if D2L.MediaPlayer.Preferences.Track is defined, it will be ignored and this track will be selected instead.

Local Storage

The media player uses local storage to persist the user's playback speed, track selections, and volume.

Items

KeyDescription
D2L.MediaPlayer.Preferences.SpeedPlayback speed that was last selected.
D2L.MediaPlayer.Preferences.TrackIdentifier for the kind and language of the track that was last selected.
D2L.MediaPlayer.Preferences.VolumeVolume that was last selected.

Accessibility

The following features are implemented to improve accessibility:

  • all controls can be accessed using the mouse or keyboard
  • captions can be provided to the media player
  • important events, such as a media source failing to load, are displayed visually and announced by screen readers

Developing, Testing and Contributing

After cloning the repo, run npm install to install dependencies.

Running the demos

To start a @web/dev-server that hosts the demo page and tests:

npm start

Troubleshooting Common Issues

  • Captions fail to load due to a "Protocols, domains, and ports must match" error
    • Solution: Set the Media Player's crossorigin property to the appropriate value (either "anonymous" or "use-credentials").
    • Explanation: If your captions sources are on a different origin, CORS needs to be enabled on the <video>/<audio> element. Otherwise, the browser will block requests to that origin due to the security measures outlined in the same-origin policy. The Media Player passes its crossorigin property directly to the <video>/<audio> element's crossorigin attribute, which sets the CORS policy. (If the crossorigin attribute isn't defined, CORS will not be used at all.)

Linting

# eslint and lit-analyzer
npm run lint

# eslint only
npm run lint:eslint

# lit-analyzer only
npm run lint:lit

Testing

# lint & run headless unit tests
npm test

# unit tests only
npm run test:headless

# debug or run a subset of local unit tests
npm run test:headless:watch

Visual Diff Testing

This repo uses the @brightspace-ui/visual-diff utility to compare current snapshots against a set of golden snapshots stored in source control.

The golden snapshots in source control must be updated by the visual-diff GitHub Action. If a pull request results in visual differences, a draft pull request with the new goldens will automatically be opened against its branch.

To run the tests locally to help troubleshoot or develop new tests, first install these dependencies:

npm install @brightspace-ui/visual-diff@X mocha@Y puppeteer@Z  --no-save

Replace X, Y and Z with the current versions the action is using.

Then run the tests:

# run visual-diff tests
npx mocha './test/**/*.visual-diff.js' -t 10000
# subset of visual-diff tests:
npx mocha './test/**/*.visual-diff.js' -t 10000 -g some-pattern
# update visual-diff goldens
npx mocha './test/**/*.visual-diff.js' -t 10000 --golden

Versioning and Releasing

This repo is configured to use semantic-release. Commits prefixed with fix: and feat: will trigger patch and minor releases when merged to main.

To learn how to create major releases and release from maintenance branches, refer to the semantic-release GitHub Action documentation.

FAQs

Last updated on 21 May 2024

Did you know?

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc