設定 IMA SDK

使用 IMA SDK,即可輕鬆將多媒體廣告整合至網站和應用程式。IMA SDK 可向任何 符合 VAST 規定的廣告伺服器請求廣告,並在應用程式中管理廣告播放。使用 IMA 用戶端 SDK 時,您可以控管內容影片的播放,SDK 則會處理廣告播放。廣告會在應用程式內容影片播放器上方的獨立影片播放器中播放。

本指南說明如何將 IMA SDK 整合至簡易影片播放器應用程式。如要查看或跟著操作完整的整合範例,請從 GitHub 下載簡易範例。如果您對預先整合 SDK 的 HTML5 播放器感興趣,請參閱 Video.js 適用的 IMA SDK 外掛程式

IMA 用戶端總覽

導入 IMA 用戶端需要四個主要 SDK 元件,本指南將說明這些元件:

  • AdDisplayContainer: 容器物件,用於指定 IMA 要在何處算繪廣告 UI 元素及評估可視度,包括 Active ViewOpen Measurement
  • AdsLoader: 這個物件會請求廣告,並處理廣告請求回應中的事件。您應該只例項化一個廣告載入器,這個載入器可在應用程式的整個生命週期中重複使用。
  • AdsRequest: 定義廣告請求的物件。廣告請求會指定 VAST 廣告代碼的網址,以及廣告尺寸等其他參數。
  • AdsManager: 這個物件包含廣告請求的回應、控制廣告播放,以及監聽 SDK 觸發的廣告事件。

必要條件

在您開始之前,您需要擁有下列項目:

  • 三個空白檔案:
    • index.html
    • style.css
    • ads.js
  • 電腦上安裝的 Python,或用於測試的網路伺服器

1. 啟動開發伺服器

由於 IMA SDK 會使用與載入網頁相同的通訊協定載入依附元件,因此您需要使用網路伺服器測試應用程式。如要啟動本機開發伺服器,最簡單的方法是使用 Python 的內建伺服器。

  1. 透過指令列,從含有 index.html 檔案的目錄執行下列指令:
      python -m http.server 8000
  2. 使用網路瀏覽器前往 http://localhost:8000/

您也可以使用任何其他網頁伺服器,例如 Apache HTTP 伺服器

2. 建立簡單的影片播放器

首先,請修改 index.html,建立簡單的 HTML5 影片元素 (包含在包裝元素中),以及觸發播放的按鈕。下列範例會匯入 IMA SDK,並設定 AdDisplayContainer 容器元素。詳情請參閱 匯入 IMA SDK 建立廣告容器 步驟。

<html>
  <head>
    <title>IMA HTML5 Simple Demo</title>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <div id="mainContainer">
      <div id="content">
        <video id="contentElement">
          <source src="https://storage.googleapis.com/gvabox/media/samples/stock.mp4"></source>
        </video>
      </div>
      <div id="adContainer"></div>
    </div>
    <button id="playButton">Play</button>
    <script src="//imasdk.googleapis.com/js/sdkloader/ima3.js"></script>
    <script src="ads.js"></script>
  </body>
</html>
#mainContainer {
  position: relative;
  width: 640px;
  height: 360px;
}

#content {
  position: absolute;
  top: 0;
  left: 0;
  width: 640px;
  height: 360px;
}

#contentElement {
  width: 640px;
  height: 360px;
  overflow: hidden;
}

#playButton {
  margin-top:10px;
  vertical-align: top;
  width: 350px;
  height: 60px;
  padding: 0;
  font-size: 22px;
  color: white;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
  background: #2c3e50;
  border: 0;
  border-bottom: 2px solid #22303f;
  cursor: pointer;
  -webkit-box-shadow: inset 0 -2px #22303f;
  box-shadow: inset 0 -2px #22303f;
}
let adsManager;
let adsLoader;
let adDisplayContainer;
let isAdPlaying;
let isContentFinished;
let playButton;
let videoContent;
let adContainer;

// On window load, attach an event to the play button click
// that triggers playback of the video element.
window.addEventListener('load', function(event) {
  videoContent = document.getElementById('contentElement');
  adContainer = document.getElementById('adContainer');
  adContainer.addEventListener('click', adContainerClick);
  playButton = document.getElementById('playButton');
  playButton.addEventListener('click', playAds);
  setUpIMA();
});

新增必要標記,載入 style.cssads.js 檔案。接著,修改 styles.css,讓影片播放器可回應行動裝置。最後,在 ads.js 中宣告變數,並在點選播放按鈕時觸發影片播放。

請注意,ads.js 程式碼片段包含對 setUpIMA() 的呼叫,該呼叫定義於 Initialize the AdsLoader and make an ads request 部分。

3. 匯入 IMA SDK

接著,請在 index.html 中,於 ads.js 的標記前,使用指令碼標記新增 IMA 架構。

<script src="//imasdk.googleapis.com/js/sdkloader/ima3.js"></script>

4. 建立廣告容器

在大多數瀏覽器中,IMA SDK 會使用專屬的廣告容器元素,顯示廣告和廣告相關的 UI 元素。這個容器的大小必須能從左上角疊加在影片元素上。這個容器中廣告的高度和寬度是由 adsManager 物件設定,因此您不需要手動設定這些值。

如要導入這個廣告容器元素,請先在 div 元素中建立新的 video-container。接著,更新 CSS,將元素放置在 video-element 的左上角。最後,新增 createAdDisplayContainer() 函式,使用新的廣告容器 div 建立 AdDisplayContainer 物件。

<div id="adContainer"></div>
#adContainer {
  position: absolute;
  top: 0;
  left: 0;
  width: 640px;
  height: 360px;
}
/**
 * Sets the 'adContainer' div as the IMA ad display container.
 */
function createAdDisplayContainer() {
  adDisplayContainer = new google.ima.AdDisplayContainer(
      document.getElementById('adContainer'), videoContent);
}

5. 初始化 AdsLoader 並提出廣告請求

如要要求廣告,請建立 AdsLoader 執行個體。AdsLoader 建構函式會將 AdDisplayContainer 物件做為輸入內容,並可用於處理與指定廣告代碼網址相關聯的 AdsRequest 物件。本範例使用的廣告代碼包含 10 秒的片頭廣告。您可以使用 IMA 影片套件檢查器,測試這個或任何廣告代碼網址。

最佳做法是在整個網頁生命週期中,只維護一個 AdsLoader 例項。如要提出其他廣告請求,請建立新的 AdsRequest 物件,但重複使用相同的 AdsLoader。詳情請參閱 IMA SDK 常見問題

使用 AdsLoader.addEventListener 監聽並回應廣告載入和錯誤事件。 監聽下列事件:

  • ADS_MANAGER_LOADED
  • AD_ERROR

如要建立 onAdsManagerLoaded()onAdError() 監聽器,請參閱下列範例:

/**
 * Sets up IMA ad display container, ads loader, and makes an ad request.
 */
function setUpIMA() {
  // Create the ad display container.
  createAdDisplayContainer();
  // Create ads loader.
  adsLoader = new google.ima.AdsLoader(adDisplayContainer);
  // Listen and respond to ads loaded and error events.
  adsLoader.addEventListener(
      google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
      onAdsManagerLoaded, false);
  adsLoader.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR, onAdError, false);

  // An event listener to tell the SDK that our content video
  // is completed so the SDK can play any post-roll ads.
  const contentEndedListener = function() {
    // An ad might have been playing in the content element, in which case the
    // content has not actually ended.
    if (isAdPlaying) return;
    isContentFinished = true;
    adsLoader.contentComplete();
  };
  videoContent.onended = contentEndedListener;

  // Request video ads.
  const adsRequest = new google.ima.AdsRequest();
  adsRequest.adTagUrl = 'https://pubads.g.doubleclick.net/gampad/ads?' +
      'iu=/21775744923/external/single_ad_samples&sz=640x480&' +
      'cust_params=sample_ct%3Dlinear&ciu_szs=300x250%2C728x90&gdfp_req=1&' +
      'output=vast&unviewed_position_start=1&env=vp&correlator=';

  // Specify the linear and nonlinear slot sizes. This helps the SDK to
  // select the correct creative if multiple are returned.
  adsRequest.linearAdSlotWidth = 640;
  adsRequest.linearAdSlotHeight = 400;

  adsRequest.nonLinearAdSlotWidth = 640;
  adsRequest.nonLinearAdSlotHeight = 150;

  adsLoader.requestAds(adsRequest);
}

6. 回應 AdsLoader 事件

AdsLoader成功載入廣告時,AdsLoader會發出 ADS_MANAGER_LOADED 事件。剖析傳遞至回呼的事件,初始化 AdsManager 物件。AdsManager 會載入個別廣告,這些廣告是由廣告代碼網址的回應所定義。

請務必處理載入程序期間發生的任何錯誤。如果廣告無法載入,請確保媒體播放作業會繼續進行,不會顯示廣告,以免干擾使用者觀看內容。

/**
 * Handles the ad manager loading and sets ad event listeners.
 * @param {!google.ima.AdsManagerLoadedEvent} adsManagerLoadedEvent
 */
function onAdsManagerLoaded(adsManagerLoadedEvent) {
  // Get the ads manager.
  const adsRenderingSettings = new google.ima.AdsRenderingSettings();
  adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true;
  // videoContent should be set to the content video element.
  adsManager =
      adsManagerLoadedEvent.getAdsManager(videoContent, adsRenderingSettings);

  // Add listeners to the required events.
  adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, onContentPauseRequested);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
      onContentResumeRequested);
  adsManager.addEventListener(google.ima.AdEvent.Type.LOADED, onAdLoaded);
}

/**
 * Handles ad errors.
 * @param {!google.ima.AdErrorEvent} adErrorEvent
 */
function onAdError(adErrorEvent) {
  // Handle the error logging.
  console.log(adErrorEvent.getError());
  adsManager.destroy();
}

如要進一步瞭解 onAdsManagerLoaded() 函式中設定的接聽程式,請參閱下列小節:

處理 AdsManager 錯誤

AdsLoader 建立的錯誤處理常式,也可以做為 AdsManager 的錯誤處理常式。請參閱重複使用 onAdError() 函式的事件處理常式。

adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError);

處理播放和暫停事件

AdsManager準備好插入廣告時,會觸發 CONTENT_PAUSE_REQUESTED 事件。觸發基礎影片播放器的暫停動作,即可處理這項事件。同樣地,廣告播放完畢時,AdsManager 會觸發 CONTENT_RESUME_REQUESTED 事件。處理這項事件的方法是重新啟動基礎內容影片的播放作業。

adsManager.addEventListener(
    google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, onContentPauseRequested);
adsManager.addEventListener(
    google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
    onContentResumeRequested);

如要瞭解 onContentPauseRequested()onContentResumeRequested() 函式的定義,請參閱下列範例:

/**
 * Pauses video content and sets up ad UI.
 */
function onContentPauseRequested() {
  isAdPlaying = true;
  videoContent.pause();
  // This function is where you should setup UI for showing ads (for example,
  // display ad timer countdown, disable seeking and more.)
  // setupUIForAds();
}

/**
 * Resumes video content and removes ad UI.
 */
function onContentResumeRequested() {
  isAdPlaying = false;
  if (!isContentFinished) {
    videoContent.play();
  }
  // This function is where you should ensure that your UI is ready
  // to play content. It is the responsibility of the Publisher to
  // implement this function when necessary.
  // setupUIForContent();
}

在非線性廣告期間處理內容播放

當廣告準備播放時,AdsManager 會暫停內容影片,但這項行為不適用於非線性廣告,因為這類廣告顯示時,內容會繼續播放。

adsManager.addEventListener(google.ima.AdEvent.Type.LOADED, onAdLoaded);

如要支援非線性廣告,請監聽 AdsManager,發出 LOADED 事件。檢查廣告是否為線性,如果不是,請在影片元素上繼續播放。

如需 onAdLoaded() 函式的定義,請參閱以下範例。

/**
 * Handles ad loaded event to support non-linear ads. Continues content playback
 * if the ad is not linear.
 * @param {!google.ima.AdEvent} adEvent
 */
function onAdLoaded(adEvent) {
  let ad = adEvent.getAd();
  if (!ad.isLinear()) {
    videoContent.play();
  }
}

7. 在行動裝置上觸發「按一下即可暫停」功能

由於 AdContainer 會疊加在影片元素上,使用者無法直接與底層播放器互動。這可能會造成行動裝置使用者混淆,因為他們預期輕觸影片播放器即可暫停播放。為解決這個問題,IMA SDK 會將廣告重疊畫面中未經 IMA 處理的任何點擊,傳遞至 AdContainer 元素,以便處理。這不適用於非行動瀏覽器上的線性廣告,因為點擊廣告會開啟點閱後連結。

如要實作點按暫停功能,請在視窗載入監聽器中,加入名為 adContainerClick() 的點按處理常式函式。

/**
 * Handles clicks on the ad container to support expected play and pause
 * behavior on mobile devices.
 * @param {!Event} event
 */
function adContainerClick(event) {
  console.log("ad container clicked");
  if(videoContent.paused) {
    videoContent.play();
  } else {
    videoContent.pause();
  }
}

8. 啟動 AdsManager

如要開始播放廣告,請啟動並開始 AdsManager。為全面支援行動瀏覽器 (無法自動播放廣告),請透過使用者與網頁的互動 (例如點選播放按鈕) 觸發廣告播放。

/**
 * Loads the video content and initializes IMA ad playback.
 */
function playAds() {
  // Initialize the container. Must be done through a user action on mobile
  // devices.
  videoContent.load();
  adDisplayContainer.initialize();

  try {
    // Initialize the ads manager. This call starts ad playback for VMAP ads.
    adsManager.init(640, 360);
    // Call play to start showing the ad. Single video and overlay ads will
    // start at this time; the call will be ignored for VMAP ads.
    adsManager.start();
  } catch (adError) {
    // An error may be thrown if there was a problem with the VAST response.
    videoContent.play();
  }
}

9. 支援調整播放器大小

如要讓廣告動態調整大小,以配合影片播放器的大小,或配合螢幕方向的變化,請在回應視窗大小調整事件時呼叫 adsManager.resize()

window.addEventListener('resize', function(event) {
  console.log("window resized");
  if(adsManager) {
    let width = videoContent.clientWidth;
    let height = videoContent.clientHeight;
    adsManager.resize(width, height, google.ima.ViewMode.NORMAL);
  }
});

大功告成!您現在可以使用 IMA SDK 請求及顯示廣告。如要瞭解更多進階 SDK 功能,請參閱其他指南或 GitHub 上的範例