开始使用

IMA SDK 可让您轻松地将多媒体广告集成到您的网站和应用中。IMA SDK 可以 向任意 <ph type="x-smartling-placeholder"></ph> 符合 VAST 标准的广告服务器,并管理应用中的广告播放。借助 IMA 客户端 SDK 您控制内容视频播放,而 SDK 处理广告播放。广告播放 独立的视频播放器,位于应用的内容视频播放器之上。

本指南将演示如何将 IMA SDK 集成到简单的视频播放器应用中。如果您想 想要查看或了解已完成的示例集成,请下载 简单示例。如果您 对预先集成了 SDK 的 HTML5 播放器感兴趣,请查看 适用于 Video.js 的 IMA SDK 插件

IMA 客户端概览

实施 IMA 客户端涉及四个主要的 SDK 组件,本示例演示了这些组件 指南:

  • AdDisplayContainer: 用于呈现广告的容器对象。
  • AdsLoader: 用于请求广告并处理广告请求响应中事件的对象。您只能 实例化一个广告加载器,该加载器可在应用的整个生命周期内重复使用。
  • AdsRequest: 用于定义广告请求的对象。广告请求会指定 VAST 广告代码的网址,以及 其他参数(例如广告尺寸)
  • AdsManager: 一个对象,包含对广告请求的响应、控制广告播放以及监听广告 所有事件。

前提条件

在开始之前,您需要做好以下准备:

  • 三个空文件: <ph type="x-smartling-placeholder">
      </ph>
    • 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
>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 文件中添加 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 尺寸,以使网页可在移动设备上自适应
。 <ph type="x-smartling-placeholder">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 对象,因此您无需手动设置这些值。

<ph type="x-smartling-placeholder">

若要实现此广告容器元素,请先在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. 监听 IDFA 事件

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