開始使用

您可以使用 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 Server

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

首先,請修改 index.html,建立簡單的 HTML5 影片元素,並在包裝元素中加入觸發播放的按鈕。並新增必要的標記,以便載入 style.cssads.js 檔案。接著,修改 styles.css,讓影片播放器在行動裝置上呈現回應式設計。最後,在 ads.js 中,觸發點選播放按鈕時的影片播放。

index.html
<!doctype html>
<html lang="en">
  <head>
    <title>IMA HTML5 Simple Demo</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div id="page-content">
      <div id="video-container">
        <video id="video-element">
          <source src="https://storage.googleapis.com/interactive-media-ads/media/android.mp4">
          <source src="https://storage.googleapis.com/interactive-media-ads/media/android.webm">
        </video>
      </div>
      <button id="play-button">Play</button>
    </div>
    <script src="ads.js"></script>
  </body>
</html>
style.css
#page-content {
  position: relative;
  /* this element's width controls the effective height */
  /* of the video container's padding-bottom */
  max-width: 640px;
  margin: 10px auto;
}

#video-container {
  position: relative;
  /* forces the container to match a 16x9 aspect ratio */
  /* replace with 75% for a 4:3 aspect ratio, if needed */
  padding-bottom: 56.25%;
}

#video-element {
  /* forces the contents to fill the container */
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
ads.js
var videoElement;

// On window load, attach an event to the play button click
// that triggers playback on the video element
window.addEventListener('load', function(event) {
  videoElement = document.getElementById('video-element');
  var playButton = document.getElementById('play-button');
  playButton.addEventListener('click', function(event) {
    videoElement.play();
  });
});

完成這個步驟後,您在瀏覽器中 (透過開發伺服器) 開啟 index.html 時,應該會看到影片元素,點選播放按鈕後,影片就會開始播放。

3. 匯入 IMA SDK

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

index.html
...

        </video>
      </div>
      <button id="play-button">Play</button>
    </div>
    <script src="//imasdk.googleapis.com/js/sdkloader/ima3.js"></script>
    <script src="ads.js"></script>
  </body>
</html>

4. 附加頁面和影片播放器處理常式

如要使用 JavaScript 修改影片播放器的行為,請新增會觸發下列動作的事件處理常式:

  • 網頁載入完成後,請初始化 IMA SDK。
  • 使用者點選影片播放按鈕時,載入廣告 (除非已載入廣告)。
  • 當瀏覽器視窗大小調整時,請更新影片元素和 adsManager 尺寸,讓網頁能回應行動裝置
ads.js
var videoElement;
// Define a variable to track whether there are ads loaded and initially set it to false
var adsLoaded = false;

window.addEventListener('load', function(event) {
  videoElement = document.getElementById('video-element');
  initializeIMA();
  videoElement.addEventListener('play', function(event) {
    loadAds(event);
  });
  var playButton = document.getElementById('play-button');
  playButton.addEventListener('click', function(event) {
    videoElement.play();
  });
});

window.addEventListener('resize', function(event) {
  console.log("window resized");
});

function initializeIMA() {
  console.log("initializing IMA");
}

function loadAds(event) {
  // Prevent this function from running on if there are already ads loaded
  if(adsLoaded) {
    return;
  }
  adsLoaded = true;

  // Prevent triggering immediate playback when ads are loading
  event.preventDefault();

  console.log("loading ads");
}

5. 建立廣告容器

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

如要實作這個廣告容器元素,請先在 video-container 元素中建立新的 div。接著,更新 CSS 以將元素置於 video-element 的左上角。最後,請在 initializeIMA() 函式中定義容器的變數,該函式會在網頁載入時執行。

index.html
...

  <div id="video-container">
    <video id="video-element" controls>
      <source src="https://storage.googleapis.com/interactive-media-ads/media/android.mp4">
      <source src="https://storage.googleapis.com/interactive-media-ads/media/android.webm">
    </video>
    <div id="ad-container"></div>
  </div>

...
style.css
...

#ad-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}
ads.js
var videoElement;
var adsLoaded = false;
var adContainer;

...

function initializeIMA() {
  console.log("initializing IMA");
  adContainer = document.getElementById('ad-container');
}

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

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

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

ads.js
var videoElement;
var adsLoaded = false;
var adContainer;
var adDisplayContainer;
var adsLoader;

...

function initializeIMA() {
  console.log("initializing IMA");
  adContainer = document.getElementById('ad-container');
  adDisplayContainer = new google.ima.AdDisplayContainer(adContainer, videoElement);
  adsLoader = new google.ima.AdsLoader(adDisplayContainer);

  // Let the AdsLoader know when the video has ended
  videoElement.addEventListener('ended', function() {
    adsLoader.contentComplete();
  });

  var 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&impl=s&correlator=';

  // Specify the linear and nonlinear slot sizes. This helps the SDK to
  // select the correct creative if multiple are returned.
  adsRequest.linearAdSlotWidth = videoElement.clientWidth;
  adsRequest.linearAdSlotHeight = videoElement.clientHeight;
  adsRequest.nonLinearAdSlotWidth = videoElement.clientWidth;
  adsRequest.nonLinearAdSlotHeight = videoElement.clientHeight / 3;

  // Pass the request to the adsLoader to request ads
  adsLoader.requestAds(adsRequest);
}

7. 監聽 AdsLoader 事件

廣告載入成功後,ima.AdsLoader 會發出 ADS_MANAGER_LOADED 事件。剖析傳遞至回呼的事件,以便初始化 AdsManager 物件。AdsManager 會根據廣告代碼網址的回應,載入個別廣告。

此外,請務必處理載入程序中可能發生的任何錯誤。如果廣告無法載入,請務必讓媒體繼續播放,且不插播廣告,以免影響使用者體驗。

ads.js
var videoElement;
var adsLoaded = false;
var adContainer;
var adDisplayContainer;
var adsLoader;
var adsManager;

...

function initializeIMA() {
  console.log("initializing IMA");
  adContainer = document.getElementById('ad-container');
  adDisplayContainer = new google.ima.AdDisplayContainer(adContainer, videoElement);
  adsLoader = new google.ima.AdsLoader(adDisplayContainer);
  adsLoader.addEventListener(
      google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
      onAdsManagerLoaded,
      false);
  adsLoader.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR,
      onAdError,
      false);

...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  // Instantiate the AdsManager from the adsLoader response and pass it the video element
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);
}

function onAdError(adErrorEvent) {
  // Handle the error logging.
  console.log(adErrorEvent.getError());
  if(adsManager) {
    adsManager.destroy();
  }
}

8. 啟動 AdsManager

如要開始播放廣告,您必須啟動 AdsManager。為了全面支援行動瀏覽器,此功能應由使用者互動觸發。

ads.js
...

function loadAds(event) {
  // prevent this function from running on every play event
  if(adsLoaded) {
    return;
  }
  adsLoaded = true;

  // prevent triggering immediate playback when ads are loading
  event.preventDefault();

  console.log("loading ads");

  // Initialize the container. Must be done via a user action on mobile devices.
  videoElement.load();
  adDisplayContainer.initialize();

  var width = videoElement.clientWidth;
  var height = videoElement.clientHeight;
  try {
    adsManager.init(width, height, google.ima.ViewMode.NORMAL);
    adsManager.start();
  } catch (adError) {
    // Play the video without ads, if an error occurs
    console.log("AdsManager could not be started");
    videoElement.play();
  }
}

...

9. 讓 AdsManager 回應式

為確保廣告能動態調整大小,以符合影片播放器的大小,如果螢幕變更大小或方向,視窗大小調整事件必須呼叫 adsManager.resize()

ads.js
...

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

...

10. 監聽 AdsManager 事件

AdsManager 也會觸發必須處理的幾個事件。這些事件可用於追蹤狀態變更、觸發內容影片的播放和暫停,以及註冊錯誤。

處理錯誤

AdsLoader 建立的錯誤處理常式,可透過新增具有相同回呼函式的新事件處理常式,充當 AdsManager 的錯誤處理常式。

ads.js
...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);

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

...

觸發播放和暫停事件

AdsManager 準備插入廣告以供顯示時,會觸發 CONTENT_PAUSE_REQUESTED 事件。處理這個事件時,請觸發對基礎影片播放器的暫停動作。同樣地,當廣告播放完畢時,AdsManager 會觸發 CONTENT_RESUME_REQUESTED 事件。如要處理這項事件,請重新啟動基礎內容影片的播放作業。

ads.js
...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);

  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);
}

...

function onContentPauseRequested() {
  videoElement.pause();
}

function onContentResumeRequested() {
  videoElement.play();
}

在行動裝置上觸發點擊暫停功能

由於 AdContainer 會疊加影片元素,使用者無法直接與底層播放器互動。這可能會讓行動裝置使用者感到困惑,因為他們預期輕觸影片播放器即可暫停播放。為解決這個問題,IMA SDK 會將 IMA 未處理的任何點擊從廣告疊加層傳遞至 AdContainer 元素,以便處理這些點擊。這項規定不適用於非行動瀏覽器上的線性廣告,因為點按廣告會開啟點閱連結。

如要實作點擊暫停功能,請在 AdContainer 中加入點擊處理常式,並在基礎影片上觸發播放或暫停事件。

ads.js
...

function initializeIMA() {
  console.log("initializing IMA");
  adContainer = document.getElementById('ad-container');
  adContainer.addEventListener('click', adContainerClick);
  adDisplayContainer = new google.ima.AdDisplayContainer(adContainer, videoElement);
  adsLoader = new google.ima.AdsLoader(adDisplayContainer);

...

function adContainerClick(event) {
  console.log("ad container clicked");
  if(videoElement.paused) {
    videoElement.play();
  } else {
    videoElement.pause();
  }
}

...

觸發非線性廣告播放

AdsManager 會在廣告準備播放時暫停內容影片,但這項行為不適用於非線性廣告,因為在這種情況下,內容應在廣告顯示時繼續播放。如要支援非線性廣告,請監聽 AdsManager 以發出 LOADED 事件。接著,請檢查廣告是否為線性廣告,如果不是,請在影片元素上繼續播放。

ads.js
...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);

  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);
}

...

function onAdLoaded(adEvent) {
  var ad = adEvent.getAd();
  if (!ad.isLinear()) {
    videoElement.play();
  }
}

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