預先擷取預先擷取

IMA SDK 可用於在直播和隨選影片營利。 如果是直播影片,您需要為每個廣告插播建立新的廣告請求。 請分散這些要求,確保所有觀眾不會同時請求廣告,且廣告伺服器過於龐大。

為協助完成這項作業,IMA SDK 含有 AdsRequest.liveStreamPrefetchSeconds 屬性。這項屬性會指定您呼叫 AdsLoader.requestAds() 後, SDK 應等待的秒數上限,系統將隨機挑選實際要求時間。舉例來說,如果您將 AdsRequest.liveStreamPrefetchSeconds 設為 30,則在您呼叫 AdsLoader.requestAds() 後,SDK 會等待 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 via 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);
}