為直播載入片頭廣告

選取平台: 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 秒,確保在預先擷取時間範圍結束時傳送的要求有足夠時間解決):

這些程式碼片段說明如何在進階範例中新增預先擷取的直播內容,但這種做法也適用於其他 IMA 實作方式。

VideoPlayerController.java

/** Ads logic for handling the IMA SDK integration code and events. */
public class VideoPlayerController {

  // 5 minutes == 300 seconds. Include a 10 second buffer
  private float AD_INTERVAL = 290;
  private double AD_TIMEOUT = 300;

...

  adsManager.addAdEventListener(
    new AdEvent.AdEventListener() {
      /** Responds to AdEvents. */
      @Override
      public void onAdEvent(AdEvent adEvent) {

      ...

      case ALL_ADS_COMPLETED:
        if (adsManager != null) {
          adsManager.destroy();
          adsManager = null;
        }

        // When pre-fetching for live streams, be sure to destroy the current AdsManager,
        // in case the tag you requested previously contains post-rolls
        // (you don't want to play those now).

        // Pre-fetch the next ad break.
        // Play those ads in ~5 minutes. In a real-world implementation,
        // this will likely be done as the result of a message from your
        // streaming server, not a through the playAdsAfterThisTime parameter
        // of requestAndPlayAds().
        requestAndPlayAds(AD_TIMEOUT);
        break;
      default:
        break;
      }
  }

...

public void requestAndPlayAds(double playAdsAfterThisTime) {
  if (currentAdTagUrl == null || currentAdTagUrl == "") {
    log("No VAST ad tag URL specified");
    resumeContent();
    return;
  }

  // Since you're switching to a new video, tell the SDK the previous video is finished.
  if (adsManager != null) {
    adsManager.destroy();
  }

  playButton.setVisibility(View.GONE);

  // Create the ads request.
  AdsRequest request = sdkFactory.createAdsRequest();
  request.setAdTagUrl(currentAdTagUrl);
  request.setContentProgressProvider(videoPlayerWithAdPlayback.getContentProgressProvider());
  request.setLiveStreamPrefetchSeconds(AD_INTERVAL);

  playAdsAfterTime = playAdsAfterThisTime;

  // Request the ad. After the ad is loaded, onAdsManagerLoaded() will be called.
  adsLoader.requestAds(request);
}