Cómo configurar la clase de jugador

En video_player.js, define una clase de wrapper de reproductor de video para iniciar y controlar el reproductor dash.js.

Configura el reproductor de banda ancha

Para definir dónde colocar el reproductor de banda ancha en tu app, crea etiquetas de video y wrapper:

<div id="broadband-wrapper">
    <video id="broadband-video"></video>
</div>

Crea el reproductor de video

Inicializa la clase de reproductor de video con variables para elementos HTML, el reproductor dash.js y devoluciones de llamada que pueden usar otros métodos de clase.

/**
 * Video player wrapper class to control ad creative playback with dash.js in
 * broadband.
 */
var VideoPlayer = function() {
  this.videoElement = document.querySelector('video');
  this.broadbandWrapper = document.getElementById('broadband-wrapper');
  this.player = dashjs.MediaPlayer().create();
  this.onAdPodEndedCallback = null;

  // Function passed in VideoPlayer.prototype.setEmsgEventHandler.
  this.onCustomEventHandler = null;
  //  Scope (this) passed in VideoPlayer.prototype.setEmsgEventHandler.
  this.customEventHandlerScope = null;

  // Function to remove all of player event listeners.
  this.cleanUpPlayerListener = null;
  debugView.log('Player: Creating dash.js player');
};

Define las funciones de control de reproducción

Para mostrar el reproductor de anuncios y adjuntar la vista de video, crea el método VideoPlayer.play(). Luego, crea el método VideoPlayer.stop() para controlar la limpieza después de que finalicen los grupos de anuncios.

/** Starts playback of ad stream. */
VideoPlayer.prototype.play = function() {
  debugView.log('Player: Start playback');
  this.show();
  this.player.attachView(this.videoElement);
};

/** Stops ad stream playback and deconstructs player. */
VideoPlayer.prototype.stop = function() {
  debugView.log('Player: Request to stop player');
  if (this.cleanUpPlayerListener) {
    this.cleanUpPlayerListener();
  }
  this.player.reset();
  this.player.attachView(null);
  this.player.attachSource(null);
  this.player = null;
  this.hide();
};

Precarga el manifiesto de la transmisión de anuncios

Para verificar que los anuncios se carguen lo suficiente durante la transmisión de contenido y antes de que comience la pausa publicitaria, usa VideoPlayer.preload() y VideoPlayer.isPreloaded().

1. Precarga la transmisión de anuncios

Crea el método VideoPlayer.preload() para precargar el manifiesto de la transmisión de anuncios y crear un búfer de anuncios antes de una pausa publicitaria. Debes actualizar la configuración de transmisión del reproductor 'cacheInitSegments' a true. Si actualizas la configuración, habilitas el almacenamiento en caché de los segmentos de inicialización, lo que evita demoras cuando cambias a los anuncios.

/**
 * Starts ad stream prefetching into Media Source Extensions (MSE) buffer.
 * @param {string} url manifest url for ad stream playback.
 */
VideoPlayer.prototype.preload = function(url) {
  if (!this.player) {
    this.player = dashjs.MediaPlayer().create();
  }
  debugView.log('Player: init with ' + url);
  this.player.initialize(/* HTMLVideoElement */ null, url, /* autoplay */ true);

  this.player.updateSettings({
    'debug': {
      'logLevel': dashjs.Debug.LOG_LEVEL_WARNING,
      'dispatchEvent': true,  // flip to false to hide all debug events.
    },
    'streaming': {
      'cacheInitSegments': true,
    }
  });
  this.player.preload();
  this.attachPlayerListener();
  debugView.log('Player: Pre-loading into MSE buffer');
};

2. Verifica el búfer de anuncios precargado

Crea el método VideoPlayer.isPreloaded() para verificar si se precargó suficiente búfer de anuncios en comparación con un umbral de búfer establecido en la app:

// Ads will only play with 10 or more seconds of ad loaded.
var MIN_BUFFER_THRESHOLD = 10;
/**
 * Checks if the ad is preloaded and ready to play.
 * @return {boolean} whether the ad buffer level is sufficient.
 */
VideoPlayer.prototype.isPreloaded = function() {
  var currentBufferLevel = this.player.getDashMetrics()
      .getCurrentBufferLevel('video', true);
  return currentBufferLevel >= MIN_BUFFER_THRESHOLD;
};

Adjunta objetos de escucha del reproductor

Para agregar objetos de escucha de eventos para el evento del reproductor dash.js, crea el método VideoPlayer.attachPlayerListener(): PLAYBACK_PLAYING, PLAYBACK_ENDED, LOG y ERROR. Este método también controla eventos para el URI de ID de esquema, además de establecer la función de limpieza para quitar estos objetos de escucha.

var SCHEME_ID_URI = 'https://developer.apple.com/streaming/emsg-id3';
/** Attaches event listener for various dash.js events.*/
VideoPlayer.prototype.attachPlayerListener = function() {
  var playingHandler = function() {
    this.onAdPodPlaying();
  }.bind(this);
  this.player.on(dashjs.MediaPlayer.events['PLAYBACK_PLAYING'], playingHandler);
  var endedHandler = function() {
    this.onAdPodEnded();
  }.bind(this);
  this.player.on(dashjs.MediaPlayer.events['PLAYBACK_ENDED'], endedHandler);
  var logHandler = function(e) {
    this.onLog(e);
  }.bind(this);
  this.player.on(dashjs.MediaPlayer.events['LOG'], logHandler);
  var errorHandler = function(e) {
    this.onAdPodError(e);
  }.bind(this);
  this.player.on(dashjs.MediaPlayer.events['ERROR'], errorHandler);

  var customEventHandler = null;
  if (this.onCustomEventHandler) {
    customEventHandler =
        this.onCustomEventHandler.bind(this.customEventHandlerScope);
    this.player.on(SCHEME_ID_URI, customEventHandler);
  }

  this.cleanUpPlayerListener = function() {
    this.player.off(
        dashjs.MediaPlayer.events['PLAYBACK_PLAYING'], playingHandler);
    this.player.off(dashjs.MediaPlayer.events['PLAYBACK_ENDED'], endedHandler);
    this.player.off(dashjs.MediaPlayer.events['LOG'], logHandler);
    this.player.off(dashjs.MediaPlayer.events['ERROR'], errorHandler);
    if (customEventHandler) {
      this.player.off(SCHEME_ID_URI, customEventHandler);
    }
  };
};

Establece devoluciones de llamada de eventos del reproductor

Para administrar la reproducción de grupos de anuncios en función de los eventos del reproductor, crea los métodos VideoPlayer.onAdPodPlaying(), VideoPlayer.onAdPodEnded() y VideoPlayer.onAdPodError():

/**
 * Called when ad stream playback buffered and is playing.
 */
VideoPlayer.prototype.onAdPodPlaying = function() {
  debugView.log('Player: Ad Playback started');
};

/**
 * Called when ad stream playback has been completed.
 * Will call the restart of broadcast stream.
 */
VideoPlayer.prototype.onAdPodEnded = function() {
  debugView.log('Player: Ad Playback ended');
  this.stop();
  if (this.onAdPodEndedCallback) {
    this.onAdPodEndedCallback();
  }
};

/**
 * @param {!Event} event The error event to handle.
 */
VideoPlayer.prototype.onAdPodError = function(event) {
  debugView.log('Player: Ad Playback error from dash.js player.');
  this.stop();
  if (this.onAdPodEndedCallback) {
    this.onAdPodEndedCallback();
  }
};

Crea el setter para el evento onAdPodEnded

Para establecer una función de devolución de llamada que se ejecute cuando finalice un grupo de anuncios, crea el método VideoPlayer.setOnAdPodEnded(). La clase de app usa este método para reanudar la transmisión de contenido después de las pausas publicitarias.

/**
 * Sets a callback function for when an ad pod has ended.
 * @param {!Function} callback Callback function.
 */
VideoPlayer.prototype.setOnAdPodEnded = function(callback) {
  this.onAdPodEndedCallback = callback;
};

Controla eventos de metadatos de transmisión

Para establecer una función de devolución de llamada que se ejecute en función de los eventos emsg, crea el método VideoPlayer.setEmsgEventHandler(). Para esta guía, incluye el parámetro scope, ya que invocas setEmsgEventHandler() fuera de video_player.js.

/**
 * Sets emsg event handler.
 * @param {!Function} customEventHandler Event handler.
 * @param {!Object} scope JS scope in which event handler function is called.
 */
VideoPlayer.prototype.setEmsgEventHandler = function(
    customEventHandler, scope) {
  this.onCustomEventHandler = customEventHandler;
  this.customEventHandlerScope = scope;
};

Muestra y oculta el reproductor de video para las pausas publicitarias

Para mostrar el reproductor de video durante las pausas publicitarias y ocultarlo después de que finalice la pausa publicitaria, crea los métodos VideoPlayer.show() y VideoPlayer.hide():

/** Shows the video player. */
VideoPlayer.prototype.show = function() {
  debugView.log('Player: show');
  this.broadbandWrapper.style.display = 'block';
};

/** Hides the video player. */
VideoPlayer.prototype.hide = function() {
  debugView.log('Player: hide');
  this.broadbandWrapper.style.display = 'none';
};

A continuación, crea una clase de administrador de anuncios para usar el SDK de IMA para realizar una solicitud de transmisión, obtener un manifiesto de grupo de anuncios, escuchar eventos de transmisión de IMA y pasar eventos emsg al SDK de IMA.