直播预提取

IMA SDK 可用于通过直播和视频点播创收。 对于直播,您需要为每个广告插播时间点发出新的广告请求。 错开这些请求,确保不会让所有观看者同时请求广告,导致广告服务器无法运行。

为帮助完成此任务,IMA SDK 具有 AdsRequest.liveStreamPrefetchSeconds 属性。此属性用于指定在您调用 AdsLoader.requestAds() 后,SDK 在与广告服务器通信之前应等待的最大秒数。实际请求时间是随机的。例如,如果您将 AdsRequest.liveStreamPrefetchSeconds 设置为 30,在您调用 AdsLoader.requestAds() 以实际向服务器发出请求后,SDK 会等待 0 到 30 秒。

直播预提取的实际运用

我们建议在广告插播结束后立即预提取下一个广告插播时间点。 这样可以确保预取窗口具有最长的时间长度。假设您的广告插播时间点之间有 5 分钟的间隔时间。广告插播结束后,您可以请求将预提取时长设置为 290 秒(5 分钟减去 10 秒,以确保在预提取窗口结束时发送的请求有足够的时间进行解析)的下一个广告插播时间点:

// 5 minutes == 300 seconds. Include a 10 second buffer
var AD_INTERVAL = 290;

function onAdEvent(adEvent) {
  var ad = adEvent.getAd();
  switch(adEvent.type) {
    case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:
      // Pre-fetch our next ad break.
      requestAds();
      // Play those ads in 5 minutes. In a real-world implementation,
      // this is likely done as the result of a message from your
      // streaming server, not a timeout.
      setTimeout(playAds, AD_INTERVAL * 1000);// Convert to ms.
  }
}

function requestAds() {
  // Destroy the current AdsManager, in case the tag you requested previously
  // contains post-rolls (don't play those now).
  if (adsManager) {
    adsManager.destroy();
  }
  // Your AdsLoader will be set up on page-load. You should re-use the same
  // AdsLoader for every request. For more info on setting up the AdsLoader,
  // see the "Get Started" guide in the prerequisites above.
  if (adsLoader) {
    // Reset the IMA SDK.
    adsLoader.contentComplete();
  }
  var adsRequest = new google.ima.AdsRequest();
  adsRequest.adTagUrl = '...';
  adsRequest.linearAdSlotWidth = <linear_width>;
  adsRequest.linearAdSlotHeight = <linear_height>;
  adsRequest.nonLinearAdSlotWidth = <nonlinear_width>;
  adsRequest.nonLinearAdSlotHeight = <nonlinear_height>;
  adsRequest.liveStreamPrefechSeconds = AD_INTERVAL;
  adsLoader.requestAds(adsRequest);
}

function playAds() {
  adsManager.init(
      <linear_width>,  <linear_height>, google.ima.ViewMode.NORMAL);
  adsManager.start();
}