借助 IMA SDK,您可以轻松将多媒体广告集成到您的网站和应用中。IMA SDK 可以从任何 与 VAST 兼容的广告服务器请求广告,并管理应用中的广告播放。借助 IMA 客户端 SDK,您可以控制内容视频播放,而 SDK 则负责处理广告播放。广告在应用内容视频播放器上方的一个单独视频播放器中播放。
本指南介绍了如何将 IMA SDK 集成到简单的视频播放器应用中。如果您想查看或跟随完成的示例集成,请从 GitHub 下载简单示例。如果您有兴趣使用预集成了 SDK 的 HTML5 播放器,请查看 适用于 Video.js 的 IMA SDK 插件。
IMA 客户端概览
实现 IMA 客户端涉及四个主要 SDK 组件,本指南将对此进行演示:
AdDisplayContainer
:一个容器对象,用于指定 IMA 在何处呈现广告界面元素并衡量可见度,包括 Active View 和 Open Measurement。AdsLoader
:用于请求广告并处理广告请求响应中的事件的对象。您应仅实例化一个广告加载器,该加载器可在应用的整个生命周期内重复使用。AdsRequest
:用于定义广告请求的对象。广告请求会指定 VAST 广告代码的网址,以及其他参数(例如广告尺寸)。AdsManager
:一个对象,包含对广告请求的响应,控制广告播放,并监听 SDK 触发的广告事件。
前提条件
在开始之前,您需要做好以下准备:
- 三个空文件:
- index.html
- style.css
- ads.js
- 在用于测试的计算机或网络服务器上安装 Python
1. 启动开发服务器
由于 IMA SDK 加载依赖项所用的协议与其加载时所在网页使用的协议相同,因此您需要使用网络服务器来测试应用。要启动本地开发服务器,最简单的方法是使用 Python 的内置服务器。
- 在您的 index.html 文件所在的目录下使用命令行运行以下命令:
python -m http.server 8000
- 在网络浏览器中,前往
http://localhost:8000/
您也可以使用任何其他网络服务器,例如 Apache HTTP Server。
2. 创建一个简单的视频播放器
首先,修改 index.html,以创建一个简单的 HTML5 视频元素(包含在封装元素中),以及一个用于触发播放的按钮。此外,还要添加必要的标记来加载 style.css 和 ads.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>
#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%; }
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 时,应该可以看到视频元素,并且当您点击“Play”(播放)按钮时,视频应该会开始播放。
3. 导入 IMA SDK
接下来,在 index.html 中使用脚本标记添加 IMA 框架,将其放在 ads.js
对应的标记之前。
... </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
尺寸,以便网页在移动设备上具有自适应功能
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()
函数中为容器定义一个变量。
... <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> ...
... #ad-container { position: absolute; top: 0; left: 0; width: 100%; }
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 常见问题解答。
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.jsvar 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
。为了全面支持移动浏览器,此操作应由用户互动触发。
... 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()
。
... 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
的错误处理程序。
... function onAdsManagerLoaded(adsManagerLoadedEvent) { adsManager = adsManagerLoadedEvent.getAdsManager( videoElement); adsManager.addEventListener( google.ima.AdErrorEvent.Type.AD_ERROR, onAdError); } ...
触发播放和暂停事件
当 AdsManager
准备好插入要展示的广告时,它会触发 CONTENT_PAUSE_REQUESTED
事件。通过在底层视频播放器上触发暂停来处理此事件。同样,当广告播放完毕时,AdsManager
会触发 CONTENT_RESUME_REQUESTED
事件。通过在底层内容视频上重启播放来处理此事件。
... 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
添加点击处理脚本,并在底层视频上触发播放或暂停事件。
... 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
事件。然后,检查广告是否为线性广告,如果不是,则恢复视频元素的播放。
... 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 上的示例。