Creating an ad countdown timer

This guide walks you through adding a countdown timer that displays the seconds remaining in the current ad to an HTML5 IMA SDK DAI implementation. The countdown timer is an HTML element, so you can adjust its styling and positioning as needed.

Prerequisites

This guide builds on the HTML5 DAI example described in the Get started guide.

Creating the timer

To create the timer, add a placeholder element to the HTML and implement styling in the CSS. Then, add some JavaScript to listen to the AdProgress event and calculate the remaining time from the event's adProgressData.

dai.html

  <body onLoad="initPlayer()">
    <h2>IMA SDK DAI Demo (HLS.JS)</h2>
      <video id="video"></video>
      <div id="click"></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 clickElement;
  var timerElement

  ...

  function initPlayer() {
    videoElement = document.getElementById('video');
    clickElement = document.getElementById('click');
    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.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;
        clickElement.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;
        clickElement.style.display = 'none';
        break;
      default:
        break;
    }
  }