Plyr: JavaScript open sources media playerの使用法


<img width="162" alt="Screen Shot 2018-05-23 at 18.29.50.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/644c62b8-5a0a-00a2-d172-f401158b12c1.png">

<img width="595" alt="Screen Shot 2018-05-23 at 14.49.57.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/1b0bde93-17e9-bb94-5a11-44d4db0578a7.png">


##はじめに

こんにちは streampack チームのメディです。
https://cloudpack.jp/service/option/streampack.html

In my opinion ***Plyr*** is a really interesting player  and  I would like to show you common use cases. Plyr is simple and easy to use.
***Plyr*** は興味深いプレイヤーなので、一般的な使用法を説明します。Plyrはシンプルで使いやすいです。

##Copyrights of videos
**Big Buck Bunny**
© copyright 2008, Blender Foundation | www.bigbuckbunny.org
**Sintel**
© copyright Blender Foundation | www.sintel.org
**Elephants Dream**
© copyright Blender Foundation | https://orange.blender.org
**Caminandes: Gran Dillama**
© copyright Blender Foundation | http://caminandes.org

##What is Plyr ・ Plyrとは
**Plyr** is an open sources JavasScript media player for the web. 
**Plyr** はウェブ用のオープンソースJavascriptメディアプレーヤーです。

##Objective・目的
Learning how to use Plyr through simple examples.
Plyrの簡単な例を学ぶこと。

#Simple example・ 簡単な実装
<img width="595" alt="Screen Shot 2018-05-23 at 15.11.25.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/893e7a55-d434-dc4c-2a73-573445b32e60.png">

###Implementation・実装
```html
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Plyr</title>
  <!-- Plyr Style sheet -->
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.css" />
</head>

<body>
  <!-- Plyr -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.min.js"></script>

  <video id="player" controls>
  </video>
</body>

<script type="text/javascript">
  const player = new Plyr('#player');
  player.source = {
    type: 'video',
    title: 'Elephant Dream',
    sources: [{
      src: 'ed_1024.mp4',
      type: 'video/mp4',
    }]
  };
</script>

</html>
```
*Alternative way ・別の方法*

```html
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Plyr</title>
  <!-- Plyr style -->
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.css" />

</head>

<body>
  <!-- Plyr -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.min.js"></script>

  <video id="player" controls>
      <source src="ed_1024.mp4" type="video/mp4">
  </video>
</body>

<script type="text/javascript">
  const player = new Plyr('#player');
</script>

</html>

```
#Subtitles・字幕

<img width="1055" alt="Screen Shot 2018-05-23 at 15.32.35.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/766f4042-534a-1d62-47a9-690966306eaa.png">

You will need to add the *crossorigin* attribute in your *video* element if you load your subtitles from another domain.

```html
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Plyr</title>
  <!-- Plyr style -->
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.css" />

</head>

<body>
  <!-- Plyr -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.min.js"></script>

  <video id="player" controls crossorigin>
  </video>
</body>

<script type="text/javascript">
  const player = new Plyr('#player');
  player.source = {
    type: 'video',
    title: 'Sintel',
    sources: [{
        src: '//iandevlin.github.io/mdn/video-player-with-captions/video/sintel-short.webm',
        type: 'video/mp4',
      }

    ],
    tracks: [{
        kind: 'captions',
        label: 'English',
        srclang: 'en',
        src: '//iandevlin.github.io/mdn/video-player-with-captions/subtitles/vtt/sintel-en.vtt',
        default: false,
      },
      {
        kind: 'captions',
        label: 'German',
        srclang: 'de',
        src: '//iandevlin.github.io/mdn/video-player-with-captions/subtitles/vtt/sintel-de.vtt',
      },
    ],
  };
</script>

</html>
```

#Logging・ロギング

<img width="1041" alt="Screen Shot 2018-05-23 at 16.47.49.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/3a02194c-21d5-fba2-6d63-4424a431031e.png">


```html
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Plyr</title>
  <!-- Plyr style sheet -->
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.css" />

</head>

<body>
  <!-- Plyr -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.min.js"></script>

  <video id="player" controls>
  </video>
</body>

<script type="text/javascript">
  const player = new Plyr('#player', {
    "debug": true
  });
  player.source = {
    type: 'video',
    title: 'Elephant Dream',
    sources: [{
      src: 'ed_1024.mp4',
      type: 'video/mp4',
    }]
  };
  player.on('loadstart', event => {
    console.log("Do something ...");
  })
  /*
    Full list of events:
    https://github.com/sampotts/plyr#events
  */
</script>

</html>

```

#HLS

<img width="1035" alt="Screen Shot 2018-05-23 at 16.21.48.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/130416d9-607c-da15-d436-2d6c94ec3a81.png">


```html
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Plyr HLS</title>
  <!-- Plyr style sheet -->
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/plyr/3.3.5/plyr.css" />
</head>

<body>
  <!-- HLS support -->
  <script src="//cdn.jsdelivr.net/hls.js/latest/hls.js"></script>
  <!-- Plyr -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/plyr/3.3.5/plyr.min.js"></script>

  <video preload="none" id="player" controls crossorigin></video>

</body>
<script type="text/javascript">
  var video = document.querySelector('video');
  if (Hls.isSupported()) {
    var hls = new Hls();
    hls.loadSource('//bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8');
    hls.attachMedia(video);
  }

  var player = new Plyr(video, {
    resetOnEnd: true
  });
</script>

</html>

```

#MPEG Dash
<img width="180" alt="Screen Shot 2018-05-24 at 10.45.16.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/560958d9-dbd3-6b63-eea7-f65f1ea58221.png">

**N.B:** iOS does not support MPEG-DASH yet.
**注意：** iOSはまだMPEG-DASHをサポートしていません。

![download.jpeg](https://qiita-image-store.s3.amazonaws.com/0/229807/96ed309c-d753-92ed-5a7d-4c5d20880d79.jpeg)


##Case 1 : dash.js ・ ケース 1 : 使用dash.js

```html
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Plyr Dash</title>
  <!-- Plyr style sheet -->
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/plyr/3.3.5/plyr.css" />
</head>

<body>
  <!-- MPEG Dash support -->
  <script src="//dashif.org/reference/players/javascript/nightly/dash.js/dist/dash.all.debug.js"></script>
  <!-- Plyr -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/plyr/3.3.5/plyr.min.js"></script>

  <video preload="none" id="player" controls crossorigin></video>

</body>
<script type="text/javascript">
  var mpd = "//rdmedia.bbc.co.uk/dash/ondemand/bbb/2/client_manifest-common_init.mpd";
  var dash = dashjs.MediaPlayer().create();
  var video = document.querySelector('#player');

  dash.initialize(video, mpd, false);

  var player = new Plyr(video, {
    resetOnEnd: true
  });
</script>

</html>

```

##Case 2 : Shaka  ・ ケース 2 : 使用Shaka

Shaka is very useful for **DRM** handling.
Shakaは**DRM**に非常に便利です。

```html
<!DOCTYPE html>
<html>

<head>
  <!-- Plyr style sheet -->
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/plyr/3.3.5/plyr.css" />
</head>

<body>
  <!-- Plyr -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/plyr/3.3.5/plyr.min.js"></script>
  <!-- Shaka Player compiled library: -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/shaka-player/2.4.0/shaka-player.compiled.debug.js"></script>

  <video id="video" width="640" controls></video>

  <script>
    var manifestUri = '//rdmedia.bbc.co.uk/dash/ondemand/bbb/2/client_manifest-common_init.mpd';

    function initApp() {
      // Install built-in polyfills to patch browser incompatibilities.
      shaka.polyfill.installAll();

      // Check to see if the browser supports the basic APIs Shaka needs.
      if (shaka.Player.isBrowserSupported()) {
        // Everything looks good!
        initPlayer();
      } else {
        // This browser does not have the minimum set of APIs we need.
        console.error('Browser not supported!');
      }
    }

    function initPlayer() {
      // Create a Player instance.
      var video = document.getElementById('video');
      var player = new shaka.Player(video);

      //DRM handling
      player.configure({
        /*
        //Example : MPDEG-DASH CENC DRM configuration
        drm: {
          clearKeys: {
            '0123456789abcdef0123456789abcdef': '0123456789abcdef0123456789abcdef'
          }
        }
        */

      });

      // Attach player to the window to make it easy to access in the JS console.
      window.player = player;

      // Listen for error events.
      player.addEventListener('error', onErrorEvent);


      // Try to load a manifest.
      // This is an asynchronous process.
      player.load(manifestUri).then(function() {
        // This runs if the asynchronous load is successful.
        console.log('The video has now been loaded!');
        //Init PLyr
        var player = new Plyr(video, {
          resetOnEnd: true
        });

      }).catch(onError); // onError is executed if the asynchronous load fails.
    }

    function onErrorEvent(event) {
      // Extract the shaka.util.Error object from the event.
      onError(event.detail);
    }

    function onError(error) {
      // Log the error.
      console.error('Error code', error.code, 'object', error);
    }

    document.addEventListener('DOMContentLoaded', initApp);
  </script>
</body>

</html>

```

#WebTorrent (Peer to peer with Bittorent)
<img width="234" alt="Screen Shot 2018-05-24 at 10.06.09.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/385b4e29-2c34-1de7-fc2b-2ca4c8e77d36.png">


<img width="1066" alt="68747470733a2f2f71696974612d696d6167652d73746f72652e73332e616d617a6f6e6177732e636f6d2f302f3232393830372f31373365613164332d363830322d616535392d336334342d3533623630323935303934392e706e67.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/42da69e6-8d2e-9ecc-4f12-68a229ccffc7.png">

>BitTorrent (BT) is a communication protocol for peer-to-peer file sharing ("P2P") which is used to distribute data and electronic files over the Internet. 
© Wikipedia

>BitTorrent（ビットトレント）は、Peer to Peerを用いたファイル転送用プロトコル及びその通信を行うソフトウェアです。
© Wikipedia

If you are interested in WebTorrent, I wrote [a more detailed article](https://qiita.com/mehdi/items/22ba55ae30bdcedd0746).
WebTorrent に興味がある場合は、[より詳細な記事にあります](https://qiita.com/mehdi/items/22ba55ae30bdcedd0746)。

**N.B**  WebTorrent is based on the WebRTC protocol. Safari does not support WebTorrent yet.
**注意** ：WebTorrentはWebRTCプロトコルに基づいています。 Safari はまだWebTorrentをサポートしていません。

![download (1).jpeg](https://qiita-image-store.s3.amazonaws.com/0/229807/a06a40fc-9692-d7ed-2fdc-6d9dd557d127.jpeg)


**N.B** It takes a few seconds to initialize WebTorrent.
**注意** WebTorrentを初期化するには数秒かかります。



```html
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>WebTorrent & Plyr demo</title>
  <!-- Plyr style sheet -->
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.css" />
</head>

<body>
  <!-- WebTorrent -->
  <script src="//cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js"></script>
  <!-- Plyr  -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.min.js"></script>

  <video id="player" controls></video>
</body>

<script type="text/javascript">
  var client = new WebTorrent();
  var torrentId =
    'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent';

  const player = new Plyr('#player', {
    debug: true
  });

  client.add(torrentId, function(torrent) {
    var file = torrent.files.find(function(file) {
      return file.name.endsWith('.mp4')
    });
    file.renderTo('video', {
      autoplay: false,
      muted: true
    }, function callback() {
      console.log("ready to play!");
    });
  });
</script>

</html>
```

#Youtube playback in Plyr
<img width="148" alt="Screen Shot 2018-05-24 at 10.12.34.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/5d0b8f47-28b3-fa7f-8e2d-1f375e5a349d.png">

<img width="790" alt="Screen Shot 2018-05-23 at 15.42.29.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/1da59589-f9f8-0220-c28e-3025afaad106.png">

```html
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Plyr</title>
  <!-- Plyr style sheet -->
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.css" />

</head>

<body>
  <!-- Plyr -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.min.js"></script>

  <video id="player" controls>
  </video>
</body>

<script type="text/javascript">
  const player = new Plyr('#player');
  player.source = {
    type: 'video',
    sources: [{
      src: 'aqz-KE-bpKQ', // From the YouTube video link
      provider: 'youtube',
    }, ],
  };

  /*
    YouTube video link
    https://www.youtube.com/watch?v=aqz-KE-bpKQ
  */
</script>

</html>

```

#Vimeo playback in Plyr
<img width="265" alt="Screen Shot 2018-05-24 at 10.12.07.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/c1600139-e423-eb1b-3369-2f0f5e5ff08f.png">


<img width="1042" alt="Screen Shot 2018-05-23 at 15.53.12.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/c65f3d1e-f343-e341-71b1-4d19ca7b25e0.png">


```html
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Plyr</title>
  <!-- Plyr style sheet -->
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.css" />

</head>

<body>
  <!-- Plyr  -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.min.js"></script>

  <video id="player" controls>
  </video>
</body>

<script type="text/javascript">
  const player = new Plyr('#player');
  player.source = {
    type: 'video',
    sources: [{
      src: '87662113', // From the Vimeo video link
      provider: 'vimeo',
    }, ],
  };

  /*
    Vimeo video link
    https://vimeo.com/87662113
  */
</script>

</html>

```

#NicoNico danmaku style・ニコニコ弾幕コメント波

<img width="974" alt="Screen Shot 2018-05-23 at 18.17.26.png" src="https://qiita-image-store.s3.amazonaws.com/0/229807/f74951bb-222c-4f04-3fda-b37289d1f94d.png">


**N.B:** It's a demo with random comments.
For live comments, please refer to the [plugin homepage](https://github.com/weizhenye/Danmaku).
**注意** これはランダムなコメントのデモです。
ライブコメントについては、[プラグインのホームページ](https://github.com/weizhenye/Danmaku)を参照してください。

```html
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Plyr</title>
  <!-- Plyr style sheet -->
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.css" />
</head>

<body>
  <!-- Plyr -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/plyr/3.1.0/plyr.min.js"></script>
  <!-- Danmaku comments wave plugin -->
  <script type="text/javascript" src="//cdn.jsdelivr.net/npm/danmaku@1.3.5/dist/danmaku.min.js"></script>

  <video id="player" controls>
     <source src="ed_1024.mp4" type="video/mp4">
 </video>
</body>


<script type="text/javascript">
  const player = new Plyr('#player');

  //Setting up random comments
  var danmaku = new Danmaku();
  danmaku.init({
    video: document.getElementById('player'),
  });

  function sendDanmaku(data) {
    var colors = ['#ffffff', '#ff0000', '#ffff00', '#ff00ff', '#3399ff', '#996633'];
    var textColor = colors[Math.floor(Math.random() * 6)];
    var comment = {
      text: data,
      style: {
        fontSize: '20px',
        color: textColor,
      },
    };
    danmaku.emit(comment);
  }
  setInterval(function() {
    sendDanmaku('time / タイムスタンプ：' + new Date().getTime());
  }, 1000);
</script>

</html>

```

#Information sources ・ 情報源
**Player homepage**
https://plyr.io/
https://github.com/sampotts/plyr

**Other libraries**
https://github.com/weizhenye/Danmaku
https://github.com/video-dev/hls.js/
https://github.com/Dash-Industry-Forum/dash.js/wiki
https://github.com/google/shaka-player

**Media files**
http://www.bbc.co.uk/rd/blog/2013-09-mpeg-dash-test-streams
http://docs.evostream.com/sample_content/table_of_contents
https://bitmovin.com/mpeg-dash-hls-examples-sample-streams/
http://iandevlin.github.io/mdn/video-player-with-captions/
https://vimeo.com/87662113
https://www.youtube.com/watch?v=aqz-KE-bpKQ
https://www.blender.org/about/projects/