为直播加载前贴片广告

选择平台HTML5 Android iOS tvOS

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

为了帮助您实现此目的,IMA SDK 提供了 AdsRequest.liveStreamPrefetchSeconds 属性。此属性用于指定在您调用AdsLoader.requestAds()后,SDK 应等待的最长时间(以秒为单位),然后才与广告服务器联系。实际请求时间将随机化。例如,如果您将 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);
}