為直播載入片頭廣告

選取平台: HTML5 Android iOS tvOS

IMA SDK 可用於透過直播串流和隨選影片營利。 如果是直播,則必須在每個廣告插播中發出新的廣告請求。 請錯開這些要求,確保所有觀眾不會同時要求廣告,導致廣告伺服器負載過重。

為此,IMA SDK 提供 AdsRequest.liveStreamPrefetchSeconds 屬性。這個屬性會指定 SDK 在您呼叫 AdsLoader.requestAds() 後,與廣告伺服器連線前應等待的秒數上限。實際要求時間會隨機產生。舉例來說,如果將 AdsRequest.liveStreamPrefetchSeconds 設為 30,SDK 會在您呼叫 AdsLoader.requestAds() 後等待 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 IMA HTML5 client-side "Set up the IMA SDK" guide:
  // https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/get-started
  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>);
  adsManager.start();
}