设置 Player 类

video_player.js 中,定义一个视频播放器封装容器类,用于启动和控制 dash.js 播放器。

设置宽带播放器

通过创建视频和封装容器代码来定义宽带播放器在应用中的放置位置:

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

创建视频播放器

使用 HTML 元素、dash.js 播放器的变量以及其他类方法可用的回调初始化视频播放器类。

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

定义播放控制函数

如需展示广告播放器并附加视频视图,请创建 VideoPlayer.play() 方法。随后,创建 VideoPlayer.stop() 方法以在广告连播完成后进行清理。

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

预加载广告流清单

如需确保在内容流式传输期间和广告插播开始前充分加载广告,请使用 VideoPlayer.preload()VideoPlayer.isPreloaded()

1. 预加载广告串流

创建 VideoPlayer.preload() 方法以预加载广告流清单,并在广告插播时间点之前积累广告缓冲区。您必须将播放器流式传输设置 'cacheInitSegments' 更新为 true。通过更新设置,您可以启用缓存 init 分段,从而避免在切换到广告时出现延迟。

/**
 * 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. 检查预加载的广告缓冲区

创建 VideoPlayer.isPreloaded() 方法,以检查相比应用中设置的缓冲区阈值,是否预加载了足够的广告缓冲区:

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

附加播放器监听器

若要为 dash.js 播放器事件添加事件监听器,请创建 VideoPlayer.attachPlayerListener() 方法:PLAYBACK_PLAYINGPLAYBACK_ENDEDLOGERROR。除了设置清理函数以移除这些监听器之外,此方法还会处理架构 ID URI 的事件。

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

设置播放器事件回调

如需根据播放器事件管理广告连播播放,请创建 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();
  }
};

onAdPodEnded 事件创建 setter

通过创建 VideoPlayer.setOnAdPodEnded() 方法,设置在广告连播结束时运行的回调函数。应用类会使用此方法在广告插播后继续播放内容。

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

处理数据流元数据事件

通过创建 VideoPlayer.setEmsgEventHandler() 方法,设置一个根据 emsg 事件运行的回调函数。对于本指南,请添加 scope 参数,因为您是在 video_player.js 之外调用 setEmsgEventHandler()

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

为广告插播时间点显示和隐藏视频播放器

如需在广告插播期间显示视频播放器,并在广告插播结束后隐藏播放器,请创建 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';
};

接下来,创建一个广告管理器类,以使用 IMA SDK 发出视频流请求、获取广告连播清单、监听 IMA 视频流事件,以及将 emsg 事件传递给 IMA SDK。