创建广告倒计时器

本指南将向您逐步介绍如何使用 IMA DAI SDK 实现广告倒计时器。 倒计时器是一个 HTML 元素,因此您可以根据需要调整其样式和位置。

前提条件

本指南以 使用入门指南。

创建计时器

要创建计时器,请在 HTML 中添加占位符元素,并在 CSS。然后,添加一些 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;
    }
  }