Configurare la classe Player

In video_player.js, definisci una classe wrapper del video player per avviare e controllare il player dash.js.

Configurare il lettore a banda larga

Definisci in quale punto dell'app posizionare il player a banda larga creando tag video e wrapper:

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

Crea il video player

Inizializza la classe del video player con variabili per gli elementi HTML, il player dash.js e i callback che altri metodi della classe possono utilizzare.

/**
 * 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');
};

Definisci le funzioni di controllo della riproduzione

Per mostrare il player dell'annuncio e allegare la visualizzazione del video, crea il metodo VideoPlayer.play(). Successivamente, crea il metodo VideoPlayer.stop() per gestire la pulizia al termine dei pod annuncio.

/** 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();
};

Precaricare il manifest del flusso di annunci

Per verificare che gli annunci siano caricati a sufficienza durante lo stream di contenuti e prima dell'inizio dell'interruzione pubblicitaria, utilizza VideoPlayer.preload() e VideoPlayer.isPreloaded().

1. Precaricare il flusso di annunci

Crea il metodo VideoPlayer.preload() per precaricare il manifest del flusso di annunci e creare un buffer di annunci prima di un'interruzione pubblicitaria. Devi aggiornare le impostazioni di streaming del player 'cacheInitSegments' a true. Se aggiorni le impostazioni, attivi la memorizzazione nella cache dei segmenti iniziali, il che evita ritardi quando passi agli annunci.

/**
 * 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. Controllare il buffer degli annunci precaricati

Crea il metodo VideoPlayer.isPreloaded() per verificare se è stato precaricato un buffer pubblicitario sufficiente rispetto a una soglia del buffer impostata nell'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;
};

Allegare listener del giocatore

Per aggiungere listener di eventi per l'evento del player dash.js, crea il metodo VideoPlayer.attachPlayerListener(): PLAYBACK_PLAYING, PLAYBACK_ENDED, LOG e ERROR. Questo metodo gestisce anche gli eventi per l'URI ID schema, oltre a impostare la funzione di pulizia per rimuovere questi listener.

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);
    }
  };
};

Impostare i callback degli eventi del player

Per gestire la riproduzione del pod di annunci in base agli eventi del player, crea i metodi VideoPlayer.onAdPodPlaying(), VideoPlayer.onAdPodEnded() e 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 il setter per l'evento onAdPodEnded

Imposta una funzione di callback che viene eseguita al termine di un pod di annunci creando il metodo VideoPlayer.setOnAdPodEnded(). La classe dell'app utilizza questo metodo per riprendere la trasmissione dei contenuti dopo le interruzioni pubblicitarie.

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

Gestire gli eventi di metadati dello stream

Imposta una funzione di callback che viene eseguita in base agli eventi emsg creando il metodo VideoPlayer.setEmsgEventHandler(). Per questa guida, includi il parametro scope, poiché richiami setEmsgEventHandler() al di fuori di 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;
};

Mostrare e nascondere il video player per le interruzioni pubblicitarie

Per visualizzare il video player durante le interruzioni pubblicitarie e nasconderlo al termine dell'interruzione, crea i metodi VideoPlayer.show() e 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';
};

Successivamente, crea una classe Ads Manager per utilizzare l'SDK IMA per effettuare una richiesta di stream, ottenere un manifest del pod di annunci, ascoltare gli eventi di streaming IMA e passare gli eventi emsg all'SDK IMA.