设置 IMA SDK

请选择平台HTML5 Android iOS tvOS

借助 IMA SDK,您可以轻松地将多媒体广告集成到网站和应用中。IMA SDK 可以 从任何 符合 VAST 标准的广告服务器请求广告,并管理应用中的广告播放。借助 IMA 客户端 SDK, 您可以控制内容视频的播放,而 SDK 则负责处理广告播放。广告会在应用的内容视频播放器上方的 单独视频播放器中播放。

本指南演示了如何将 IMA SDK 集成到简单的视频播放器应用中。如果您想查看或按照完整的示例集成进行操作,请从 GitHub 下载 简单示例。如果您对预先集成 SDK 的 HTML5 播放器感兴趣,请查看 IMA SDK 插件(适用于 Video.js)

IMA 客户端概览

实现 IMA 客户端涉及四个主要的 SDK 组件,本指南将对此进行演示:

  • AdDisplayContainer:一个容器对象,用于指定 IMA 在何处呈现广告界面元素并衡量可见度,包括 Active View开放衡量
  • 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 视频元素(包含在封装 元素中),以及一个用于触发播放的按钮。以下示例导入了 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() 的调用,该调用在 初始化 AdsLoader 并发出广告请求 部分中定义。

3. 导入 IMA SDK

接下来,在 index.html 中使用脚本标记添加 IMA 框架,将其放在 ads.js 对应的标记之前。

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

4. 创建广告容器

在大多数浏览器中,IMA SDK 使用专用广告容器元素来显示广告和 与广告相关的界面元素。此容器的大小必须能够从 左上角叠加视频元素。放置在此容器中的广告的高度和宽度由 adsManager 对象设置,因此您无需手动设置这些值。

如需实现此广告容器元素,请先在 video-container 元素中创建一个新的 div。然后,更新 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 Video Suite Inspector 测试此广告代码网址或任何其他广告代码网址。

最佳实践是,在页面的整个 生命周期内仅维护一个 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 成功加载广告时,它会发出 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 上的示例