為直播載入片頭廣告

適用於 iOS 的 Google 互動式媒體廣告 (IMA) SDK。

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

為此,IMA SDK 提供 AdsRequest.liveStreamPrefetchSeconds 屬性。這個屬性會指定 SDK 在您呼叫 AdsLoader.requestAds() 後,與廣告伺服器連線前應等待的秒數上限。實際要求時間會隨機產生。舉例來說,如果將 AdsRequest.liveStreamPrefetchSeconds 設為 30,SDK 會在您呼叫 AdsLoader.requestAds() 後等待 0 到 30 秒,再實際向伺服器發出要求。

實際運用直播預先擷取功能

建議您在廣告插播結束後,立即預先擷取下一個廣告插播。 確保預先擷取視窗有最長的時間。 假設廣告插播間隔為 5 分鐘,廣告插播結束後,您可以在 290 秒的預先擷取時間範圍內要求下一個廣告插播 (5 分鐘減去 10 秒,確保在預先擷取時間範圍結束時傳送的要求有足夠時間解決):

Objective-C


- (void)adsManager:(IMAAdsManager *)adsManager didReceiveAdEvent:(IMAAdEvent *)event {

  ...

  switch (event.type) {

    ...

    case kIMAAdEvent_ALL_ADS_COMPLETED:

      IMAAdsRequest *request = [[IMAAdsRequest alloc]
             initWithAdTagUrl: self.adTagUrl
           adDisplayContainer: self.adDisplayContainer
         avPlayerVideoDisplay: self.avPlayerVideoDisplay
        pictureInPictureProxy: self.pictureInPictureProxy
                  userContext: nil];

      // set a delay between the end of the last ad
      // in the last request, and the first ad from
      // the new request
      Float64 adGap = 30;
      // make sure the request occurs at least five
      // seconds before starting the new set of ads
      request.liveStreamPrefetchSeconds = adGap - 5;
      [self.adsLoader requestAdsWithRequest:request];
      // start new ads after adGap seconds have elapsed
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, adGap * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [adsManager start];
      });

      break;

    ...

  }

  ...

}

Swift

func adsManager(_ adsManager: IMAAdsManager!, didReceive event: IMAAdEvent!) {
  switch event.type {

    ...

    case IMAAdEventType.ALL_ADS_COMPLETED:

      let request = IMAAdsRequest(
        adTagUrl: AdTagUrl,
        adDisplayContainer: adDisplayContainer,
        contentPlayhead: contentPlayhead,
        userContext: nil)

      // set a delay between the end of the last ad
      // in the last request, and the first ad from
      // the new request
      let adGap = 30
      // make sure the request occurs at least five
      // seconds before starting the new set of ads
      request.liveStreamPrefetchSeconds = adGap - 5
      adsLoader.requestAds(with: request)
      // start new ads after adGap seconds have elapsed
      DispatchQueue.main.asyncAfter(deadline: .now() + adGap) {
        adsManager.start()
      }

      break

    ...
  }
}