开始使用

借助 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. 启动 Ad Manager

若要开始播放广告,您需要启动 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. 将 Adapter 设置为自适应

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

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