Tìm nạp trước luồng trực tiếp

Bạn có thể sử dụng SDK IMA để kiếm tiền từ các sự kiện phát trực tiếp cũng như video theo yêu cầu. Đối với sự kiện phát trực tiếp, bạn cần tạo một yêu cầu quảng cáo mới cho mỗi điểm chèn quảng cáo. Phân chia các yêu cầu này để đảm bảo rằng tất cả người xem của bạn không yêu cầu quảng cáo cùng một lúc và làm hỏng(các) máy chủ quảng cáo.

Để giúp giải quyết việc này, SDK IMA có thuộc tính AdsRequest.liveStreamPrefetchSeconds. Thuộc tính này chỉ định số giây tối đa mà SDK cần chờ trước khi liên hệ với máy chủ quảng cáo sau khi bạn gọi AdsLoader.requestAds(). Thời gian yêu cầu thực tế sẽ được chọn ngẫu nhiên. Ví dụ: nếu bạn đặt AdsRequest.liveStreamPrefetchSeconds thành 30, SDK sẽ đợi từ 0 đến 30 giây sau khi bạn gọi AdsLoader.requestAds() để thực sự gửi yêu cầu đến máy chủ.

Tính năng tìm nạp trước sự kiện phát trực tiếp trong thực tế

Bạn nên tìm nạp trước điểm chèn quảng cáo tiếp theo ngay khi điểm chèn quảng cáo hoàn tất. Điều này đảm bảo khoảng thời gian tối đa có sẵn cho cửa sổ tìm nạp trước của bạn. Giả sử bạn có 5 phút giữa các điểm chèn quảng cáo. Khi một điểm chèn quảng cáo hoàn tất, bạn có thể yêu cầu điểm chèn quảng cáo tiếp theo với thời lượng tìm nạp trước là 290 giây (5 phút trừ 10 giây, để đảm bảo các yêu cầu được gửi ở cuối cửa sổ tìm nạp trước có đủ thời gian để giải quyết):

// 5 minutes == 300 seconds. Include a 10 second buffer
var AD_INTERVAL = 290;

function onAdEvent(adEvent) {
  var ad = adEvent.getAd();
  switch(adEvent.type) {
    case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:
      // Pre-fetch our next ad break.
      requestAds();
      // Play those ads in 5 minutes. In a real-world implementation,
      // this is likely done as the result of a message from your
      // streaming server, not a timeout.
      setTimeout(playAds, AD_INTERVAL * 1000);// Convert to ms.
  }
}

function requestAds() {
  // Destroy the current AdsManager, in case the tag you requested previously
  // contains post-rolls (don't play those now).
  if (adsManager) {
    adsManager.destroy();
  }
  // Your AdsLoader will be set up on page-load. You should re-use the same
  // AdsLoader for every request. For more info on setting up the AdsLoader,
  // see the "Get Started" guide in the prerequisites above.
  if (adsLoader) {
    // Reset the IMA SDK.
    adsLoader.contentComplete();
  }
  var adsRequest = new google.ima.AdsRequest();
  adsRequest.adTagUrl = '...';
  adsRequest.linearAdSlotWidth = <linear_width>;
  adsRequest.linearAdSlotHeight = <linear_height>;
  adsRequest.nonLinearAdSlotWidth = <nonlinear_width>;
  adsRequest.nonLinearAdSlotHeight = <nonlinear_height>;
  adsRequest.liveStreamPrefechSeconds = AD_INTERVAL;
  adsLoader.requestAds(adsRequest);
}

function playAds() {
  adsManager.init(
      <linear_width>,  <linear_height>, google.ima.ViewMode.NORMAL);
  adsManager.start();
}