开始使用

借助 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 通过与其加载所在页面相同的协议来加载依赖项,因此您需要使用网络服务器来测试您的应用。启动本地开发服务器的最简单方法是使用 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 中的脚本标记在 ads.js 的标记之前添加 IMA 框架。

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 使用专门的广告容器元素来显示广告以及与广告相关的界面元素。此容器的大小必须从左上角叠加视频元素。此容器中投放的广告的高度和宽度由 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 Video Suite Inspector 对此网址或任何广告代码网址进行测试。

最佳实践是,仅在网页的整个生命周期中维护一个 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. 启动 VPAID

若要开始播放广告,您需要启动 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. 使 VPAID 具备自适应能力

为了确保广告能够动态调整尺寸以匹配视频播放器的尺寸,如果屏幕大小或方向发生变化,窗口大小调整事件必须调用 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. 监听 VPAID 事件

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 上的示例