預先載入直播的廣告插播

選取平台: 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);
}