瞭解詳情

IMA SDK 可讓您輕鬆將多媒體廣告整合至您的網站和應用程式。IMA SDK 可以 向任何 與 VAST 相容的廣告伺服器,並管理您應用程式中的廣告播放方式。使用 IMA 用戶端 SDK 您能掌控內容影片播放,而 SDK 會處理廣告播放。廣告在 獨立影片播放器位於應用程式內容影片播放器上方。

本指南說明如何將 IMA SDK 整合到簡易的影片播放器應用程式中。 想查看或按照已完成的整合範例操作 GitHub 的簡易範例。如果您是 想瞭解預先整合 SDK 的 HTML5 播放器,請參閱 Video.js 專用的 IMA SDK 外掛程式

IMA 用戶端總覽

導入 IMA 用戶端需要四個主要的 SDK 元件,如本例所示 指南:

  • AdDisplayContainer: 廣告顯示位置的容器物件。
  • AdsLoader: 這個物件會請求廣告,以及處理廣告請求回應中的事件。除了 將一個廣告載入器執行個體化,以便在應用程式生命週期中重複使用。
  • AdsRequest: 定義廣告請求的物件。廣告請求會指定 VAST 廣告代碼的網址,以及 額外參數,例如廣告尺寸。
  • AdsManager: 包含回應廣告請求、控制廣告播放以及監聽廣告的物件 SDK 觸發的事件。

必要條件

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

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

1. 啟動開發伺服器

由於 IMA SDK 透過與載入該 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
>h<tml lang="en"<>/span>
  h<ead<>/span>
    t<itleI>MA HTML5 Simple Demo/<title
>    m<eta charset="utf-8"<>/span>
    m<eta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"<>/span>
    l<ink rel="stylesheet" href="style.css"<>/span>
  /<head
>  b<ody<>/span>
    d<iv id="page-content"<>/span>
      d<iv id="video-container"<>/span>
        v<ideo id="video-element"<>/span>
          s<ource src="https://storage.googleapis.com/interactive-media-ads/media/android.mp4"<>/span>
          s<ource src="https://storage.googleapis.com/interactive-media-ads/media/android.webm"<>/span>
        /<video
>      /<div
>      b<utton id="play-button"P>lay/<button
>    /<div
>    s<cript 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 中的指令碼代碼 (在 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 元素這個容器的大小必須設為超出 所有 GCP 服務此容器中廣告的高度和寬度是由 adsManager 物件,因此您無需手動設定這些值。

如要導入這個廣告容器元素,請先在div video-container 元素。然後更新 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 請求及顯示廣告。進一步瞭解 請參閱其他指南 GitHub 上的範例