Konfigurowanie klasy gracza

video_player.js zdefiniuj klasę kontenera odtwarzacza wideo, aby zainicjować odtwarzacz dash.js i nim sterować.

Konfigurowanie odtwarzacza szerokopasmowego

Określ, w którym miejscu aplikacji ma się znajdować odtwarzacz szerokopasmowy, tworząc tagi wideo i tagi opakowujące:

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

Tworzenie odtwarzacza wideo

Zainicjuj klasę odtwarzacza wideo za pomocą zmiennych dla elementów HTML, odtwarzacza dash.js i wywołań zwrotnych, z których mogą korzystać inne metody klasy.

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

Określanie funkcji elementów sterujących odtwarzaniem

Aby wyświetlić odtwarzacz reklam i dołączyć wyświetlenie filmu, utwórz metodę VideoPlayer.play(). Następnie utwórz metodę VideoPlayer.stop(), która będzie obsługiwać czyszczenie po zakończeniu wyświetlania bloków reklamowych.

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

Wstępne wczytywanie pliku manifestu strumienia reklam

Aby sprawdzić, czy reklamy są wystarczająco wczytane podczas strumienia treści i przed rozpoczęciem przerwy na reklamę, użyj funkcji VideoPlayer.preload()VideoPlayer.isPreloaded().

1. Wstępne wczytywanie strumienia reklam

Utwórz metodę VideoPlayer.preload(), która będzie wstępnie wczytywać manifest strumienia reklam i tworzyć bufor reklam przed przerwą na reklamę. Musisz zaktualizować ustawienia przesyłania strumieniowego odtwarzacza 'cacheInitSegments' na true. Aktualizacja ustawień umożliwia buforowanie segmentów inicjujących, co pozwala uniknąć opóźnień podczas przełączania się na reklamy.

/**
 * 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. Sprawdzanie bufora wstępnie wczytanej reklamy

Utwórz metodę VideoPlayer.isPreloaded(), aby sprawdzić, czy wstępnie wczytano wystarczającą ilość bufora reklam w porównaniu z progiem bufora ustawionym w aplikacji:

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

Dołączanie odbiorców odtwarzacza

Aby dodać detektory zdarzeń dla zdarzenia odtwarzacza dash.js, utwórz metodę VideoPlayer.attachPlayerListener(): PLAYBACK_PLAYING, PLAYBACK_ENDED, LOGERROR. Ta metoda obsługuje też zdarzenia dla identyfikatora URI schematu, a także ustawia funkcję czyszczenia, która usuwa te odbiorniki.

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

Ustawianie wywołań zwrotnych zdarzeń odtwarzacza

Aby zarządzać odtwarzaniem boksu reklam na podstawie zdarzeń odtwarzacza, utwórz metody:VideoPlayer.onAdPodPlaying(), VideoPlayer.onAdPodEnded()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();
  }
};

Utwórz funkcję ustawiającą dla zdarzenia onAdPodEnded.

Ustaw funkcję wywołania zwrotnego, która będzie uruchamiana po zakończeniu bloku reklamowego, tworząc metodę VideoPlayer.setOnAdPodEnded(). Klasa aplikacji używa tej metody do wznawiania transmisji treści po przerwach na reklamy.

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

Obsługa zdarzeń metadanych strumienia

Ustaw funkcję wywołania zwrotnego, która będzie uruchamiana na podstawie zdarzeń emsg, tworząc metodę VideoPlayer.setEmsgEventHandler(). W tym przewodniku uwzględnij parametr scope, ponieważ wywołujesz setEmsgEventHandler() poza 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;
};

Wyświetlanie i ukrywanie odtwarzacza wideo podczas przerw na reklamy

Aby wyświetlać odtwarzacz wideo podczas przerw na reklamy i ukrywać go po zakończeniu przerwy, utwórz metody VideoPlayer.show()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';
};

Następnie utwórz klasę menedżera reklam, aby używać pakietu IMA SDK do wysyłania żądań strumienia, pobierania manifestu bloku reklamowego, nasłuchiwania zdarzeń strumienia IMA i przekazywania zdarzeń emsg do pakietu IMA SDK.