建立廣告倒數計時器

本指南將逐步引導您如何使用 IMA DAI SDK 導入廣告倒數計時計時器。 倒數計時器是 HTML 元素,因此您可以視需要調整其樣式和位置。

必要條件

本指南以 入門指南

建立計時器

如要建立計時器,請在 HTML 中加入預留位置元素,並在 例如 CSS、CSS、CSS 和 JS。然後,新增一些 JavaScript 來監聽 AdProgress 事件並計算 距離事件 adProgressData 的剩餘時間。

dai.html

  <body onLoad="initPlayer()">
    <h2>IMA DAI SDK for HTML5 Demo (HLS.JS)</h2>
      <video id="video"></video>
      <div id="adUi"></div>
      <div id="ad-timer">Ad not currently playing.</div>
  </body>

dai.css


#ad-timer {
  display: inline-block;
  margin-top: 375px;
  padding: 15px;
  border: 1px solid #000;
}

...

dai.js

  ...

  var streamManager;   // used to request ad-enabled streams.
  var hls = new Hls(); // hls.js video player
  var videoElement;
  var adUiElement;
  var timerElement

  ...

  function initPlayer() {
    videoElement = document.getElementById('video');
    adUiElement = document.getElementById('adUi');
    timerElement = document.getElementById('ad-timer');

  ...

  streamManager.addEventListener(
    [google.ima.dai.api.StreamEvent.Type.LOADED,
     google.ima.dai.api.StreamEvent.Type.ERROR,
     google.ima.dai.api.StreamEvent.Type.AD_BREAK_STARTED,
     google.ima.dai.api.StreamEvent.Type.AD_BREAK_ENDED,
     google.ima.dai.api.StreamEvent.Type.PAUSED,
     google.ima.dai.api.StreamEvent.Type.RESUMED,
     google.ima.dai.api.StreamEvent.Type.AD_PROGRESS],
    onStreamEvent,
    false);

  ...

  function onStreamEvent(e) {
    switch (e.type) {
      case google.ima.dai.api.StreamEvent.Type.LOADED:
        console.log('Stream loaded');
        loadUrl(e.getStreamData().url);
        break;
      case google.ima.dai.api.StreamEvent.Type.ERROR:
        console.log('Error loading stream, playing backup stream.' + e);
        loadUrl(BACKUP_STREAM);
        break;
      case google.ima.dai.api.StreamEvent.Type.AD_BREAK_STARTED:
        console.log('Ad Break Started');
        videoElement.controls = false;
        adUiElement.style.display = 'block';
        break;
      case google.ima.dai.api.StreamEvent.Type.AD_PROGRESS:
        var progressData = e.getStreamData().adProgressData;
        var timeRemaining = Math.ceil(progressData.duration - progressData.currentTime);
        timerElement.innerHTML = 'Ad finished in: ' + timeRemaining;
        break;
      case google.ima.dai.api.StreamEvent.Type.AD_BREAK_ENDED:
        timerElement.innerHTML = 'Ad not currently playing.';
        console.log('Ad Break Ended');
        videoElement.controls = true;
        adUiElement.style.display = 'none';
        break;
      default:
        break;
    }
  }