Video.js 使用

載入 Video.js 相關的 js 、css 工具。下面由 CDN 載入相關工具

<link href="https://vjs.zencdn.net/8.16.1/video-js.css" rel="stylesheet" />
<!-- "core" version of Video.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/8.17.3/video.min.js"></script>
<!--Video.js 支援串流 plugin-->
<script src="https://cdn.jsdelivr.net/npm/@videojs/http-streaming@3.10.0/dist/videojs-http-streaming.min.js"></script>

在需要使用 video 的位置放入 <video-js> 的客製化的 html Tag

<video-js
  id="vid1"
  width="640"
  height="264"
  class="video-js vjs-default-skin"
>
</video-js>

id 使用唯一值,後面是以它為識別做 player 的初始化

videojs("vid1", options);

以下是 videojs 的基本使用方法,包括初始化播放器、事件監聽和控制播放等功能。

// 基本初始化
const player = videojs('vid1', {
  autoplay: true,
  // 使用控制項
  controls: true,
  // 由 options 內控制影片來源、type
  sources: [{ src: 'path/to/video.mp4', type: 'video/mp4' }]
});

// 事件監聽
player.on('play', function() {
  console.log('影片開始播放');
});

影片格式

裡面不同的 src 有對應的 type,設定正確的格式才能夠正常使用,以下是幾個比較常見的:

Src Type
mp4 video/mp4
m3u8 application/x-mpegURL
webm video/webm
ogg video/ogg
mpd application/dash+xml

操作語法

以下是幾個常使用的控制項操作語法:

// 播放
player.play();
// 暫停
player.pause();
// 跳到 30 秒處
player.currentTime(30);

樣式

Videojs 的外觀調整設定如下:

<!-- In the head of your document with your other CSS includes... -->
<!-- Video.js base CSS -->
<link
  href="https://unpkg.com/video.js@7/dist/video-js.min.css"
  rel="stylesheet"
/>

<!-- 載入要使用的 theme css -->
<!-- City -->
<link
  href="https://unpkg.com/@videojs/themes@1/dist/city/index.css"
  rel="stylesheet"
/><!-- Then, in the player -->

<!--元件的 class 加入對應 theme 的 css class-->
<video class="video-js vjs-theme-city" ...></video>

完整範例:

<!DOCTYPE html>
<html>
  <head>
    <link href="//vjs.zencdn.net/8.18.0/video-js.min.css" rel="stylesheet" />
    <script src="//vjs.zencdn.net/8.18.0/video.min.js"></script>
  </head>
  <body>
    <video
      id="my-video"
      class="video-js"
      controls
      preload="auto"
      width="640"
      height="264"
      poster="MY_VIDEO_POSTER.jpg"
      data-setup="{}"
    >
      <source src="MY_VIDEO.mp4" type="video/mp4" />
      <source src="MY_VIDEO.webm" type="video/webm" />
      <p class="vjs-no-js">
        To view this video please enable JavaScript, and consider upgrading to a
        web browser that
        <a href="https://videojs.com/html5-video-support/" target="_blank"
          >supports HTML5 video</a
        >
      </p>
    </video>
    <script>
      const player = videojs('my-video');
    </script>
  </body>
</html>