Thiết lập lớp người chơi

Trong video_player.js, hãy xác định một lớp trình bao bọc trình phát video để khởi chạy và kiểm soát trình phát dash.js.

Thiết lập trình phát băng thông rộng

Xác định vị trí đặt trình phát băng thông rộng trong ứng dụng bằng cách tạo thẻ video và thẻ trình bao bọc:

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

Tạo trình phát video

Khởi chạy lớp trình phát video bằng các biến cho phần tử HTML, trình phát dash.js và lệnh gọi lại mà các phương thức lớp khác có thể sử dụng.

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

Xác định các hàm điều khiển chế độ phát

Để hiển thị trình phát quảng cáo và đính kèm khung hiển thị video, hãy tạo phương thức VideoPlayer.play(). Sau đó, hãy tạo phương thức VideoPlayer.stop() để xử lý việc dọn dẹp sau khi nhóm quảng cáo kết thúc.

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

Tải trước tệp kê khai luồng quảng cáo

Để xác minh rằng quảng cáo đã tải đủ trong luồng nội dung và trước khi điểm chèn quảng cáo bắt đầu, hãy sử dụng VideoPlayer.preload()VideoPlayer.isPreloaded().

1. Tải trước luồng quảng cáo

Tạo phương thức VideoPlayer.preload() để tải trước tệp kê khai luồng quảng cáo và tạo vùng đệm quảng cáo trước điểm chèn quảng cáo. Bạn phải cập nhật chế độ cài đặt truyền phát của trình phát 'cacheInitSegments' thành true. Bằng cách cập nhật chế độ cài đặt, bạn có thể bật tính năng lưu vào bộ nhớ đệm các phân đoạn khởi chạy, giúp tránh tình trạng chậm trễ khi chuyển sang quảng cáo.

/**
 * 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. Kiểm tra bộ đệm quảng cáo đã tải trước

Tạo phương thức VideoPlayer.isPreloaded() để kiểm tra xem bộ đệm quảng cáo đã tải trước đủ so với ngưỡng bộ đệm được đặt trong ứng dụng hay chưa:

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

Đính kèm trình nghe trình phát

Để thêm trình nghe sự kiện cho sự kiện trình phát dash.js, hãy tạo phương thức VideoPlayer.attachPlayerListener(): PLAYBACK_PLAYING, PLAYBACK_ENDED, LOGERROR. Phương thức này cũng xử lý các sự kiện cho URI mã lược đồ, ngoài việc đặt hàm dọn dẹp để xoá các trình nghe này.

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

Đặt lệnh gọi lại sự kiện trình phát

Để quản lý việc phát nhóm quảng cáo dựa trên các sự kiện trình phát, hãy tạo các phương thức 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();
  }
};

Tạo phương thức setter cho sự kiện onAdPodEnded

Đặt một hàm callback chạy khi một nhóm quảng cáo kết thúc bằng cách tạo phương thức VideoPlayer.setOnAdPodEnded(). Lớp ứng dụng sử dụng phương thức này để tiếp tục phát nội dung sau điểm chèn quảng cáo.

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

Xử lý các sự kiện siêu dữ liệu luồng

Đặt một hàm callback chạy dựa trên các sự kiện emsg bằng cách tạo phương thức VideoPlayer.setEmsgEventHandler(). Đối với hướng dẫn này, hãy đưa tham số scope vào vì bạn gọi setEmsgEventHandler() bên ngoài 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;
};

Hiện và ẩn trình phát video cho điểm chèn quảng cáo

Để hiển thị trình phát video trong điểm chèn quảng cáo và ẩn trình phát sau khi điểm chèn quảng cáo kết thúc, hãy tạo các phương thức 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';
};

Tiếp theo, hãy tạo một lớp trình quản lý quảng cáo để sử dụng SDK IMA nhằm đưa ra yêu cầu luồng, nhận tệp kê khai nhóm quảng cáo, theo dõi các sự kiện luồng IMA và chuyển các sự kiện emsg đến SDK IMA.