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 tạo và kiểm soát trình phát dash.js.

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

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

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

Tạo trình phát video

Khởi tạo 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à các 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 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 các nhóm quảng cáo hoàn tất.

/** 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 được 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 bộ đệm quảng cáo trước một khoảng chèn quảng cáo. Bạn phải cập nhật chế độ cài đặt phát trực tuyến 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 cho các phân đoạn khởi tạo, 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 vùng đệm quảng cáo được tải trước

Tạo phương thức VideoPlayer.isPreloaded() để kiểm tra xem đã tải trước đủ bộ đệm quảng cáo 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 của 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. Ngoài việc đặt hàm dọn dẹp để xoá các trình nghe này, phương thức này cũng xử lý các sự kiện cho URI mã nhận dạng lược đồ.

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 của 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 của 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 thiết lập cho sự kiện onAdPodEnded

Đặt một hàm gọi lại 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 dùng phương thức này để tiếp tục phát nội dung sau khi kết thúc đ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 của luồng phát

Đặt một hàm gọi lại 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 thêm tham số scope khi 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 các điểm chèn quảng cáo

Để hiển thị trình phát video trong thời gian chèn quảng cáo và ẩn trình phát sau khi thời gian 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 tạo yêu cầu về luồng phát, nhận tệp kê khai nhóm quảng cáo, theo dõi các sự kiện luồng phát IMA và truyền các sự kiện emsg đến SDK IMA.