如何解决自动播放广告 IMA SDK HTML5
我正在尝试为 HTML5 播放器创建自动播放广告,我使用 VPAID 和 IMA SDK。 我确实阅读了有关如何使用自动播放等的文档,但无法创建此代码。
请解释我做错了什么以及如何解决这个问题,下面附上我的代码示例。 现在我只能通过点击开始广告。
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" playsinline muted>
<source src=""></source>
<source src=""></source>
</video>
<div id="ad-container"></div>
</div>
<!-- <button id="play-button">Play</button>-->
</div>
<script type="text/javascript" async defer src="https://imasdk.googleapis.com/js/sdkloader/ima3.js"></script>
<script type="text/javascript" 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%;
}
#ad-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
ads.js
var videoElement;
// Define a variable to track whether there are ads loaded and initially set it to false
var adsLoaded = false;
var adContainer;
var addisplayContainer;
var adsLoader;
var adsManager;
window.addEventListener('load',function(event) {
videoElement = document.getElementById('video-element');
initializeIMA();
videoElement.addEventListener('canplay',function(event) {
loadAds(event);
});
});
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);
}
});
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);
// Let the AdsLoader kNow when the video has ended
videoElement.addEventListener('ended',function() {
adsLoader.contentComplete();
});
var adsRequest = new google.ima.AdsRequest();
adsRequest.adTagUrl = 'https://4736.in/vpaid/?id=6';
// 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);
adsLoader.addEventListener(
google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,onAdsManagerLoaded,false);
adsLoader.addEventListener(
google.ima.AdErrorEvent.Type.AD_ERROR,onAdError,false);
}
function adContainerClick(event) {
console.log("ad container clicked");
if(videoElement.paused) {
videoElement.play();
} else {
videoElement.pause();
}
}
function onAdsManagerLoaded(adsManagerLoadedEvent) {
// Instantiate the AdsManager from the adsLoader response and pass it the video element
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 onAdError(adErrorEvent) {
// Handle the error logging.
console.log(adErrorEvent.getError());
if(adsManager) {
adsManager.destroy();
}
}
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");
videoElement.load();
addisplayContainer.initialize();
var width = videoElement.clientWidth;
var height = videoElement.clientHeight;
try {
adsManager.init(width,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();
}
}
function onContentPauseRequested() {
videoElement.pause();
}
function onContentResumeRequested() {
videoElement.play();
}
function onAdLoaded(adEvent) {
var ad = adEvent.getAd();
if (!ad.isLinear()) {
videoElement.play();
}
}
解决方法
我稍微重写了代码,现在广告有自动播放和全屏功能,在所有 80% 的 ios 模拟器上都经过测试。
<html>
<head>
<title>IMA HTML5 Simple Demo</title>
<style type="text/css">
#video-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#adContainer {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
#contentElement {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#playButton {
margin-top:10px;
vertical-align: top;
width: 1px;
height: 1px;
padding: 0;
font-size: 22px;
color: white;
text-align: center;
text-shadow: 0 1px 2px rgba(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;
}
</style>
</head>
<body>
<div id="video-container">
<video id="contentElement" webkit-playsinline playsinline>
<source src=""></source>
</video>
<div id="adContainer"></div>
</div>
<button id="playButton">Play</button>
<script type="text/javascript" src="https://imasdk.googleapis.com/js/sdkloader/ima3.js"></script>
<script type="text/javascript">
var adsManager;
var adsLoader;
var adDisplayContainer;
var intervalTimer;
var playButton;
var videoContent;
var paused;
var counter = 0
function init() {
console.log('init')
videoContent = document.getElementById('contentElement');
playButton = document.getElementById('playButton');
playButton.addEventListener('click',testButton);
setUpIMA();
}
function testButton() {
window.setTimeout(
function() {
document.body.style.backgroundColor = `red`;
adsManager.pause();
},1000);
}
function testButtonPlay() {
window.setTimeout(
function() {
document.body.style.backgroundColor = `green`;
adsManager.play();
},2000);
}
function adsFinish() {
window.webkit.messageHandlers.iosClickListener.postMessage('ads_finish');
}
function setUpIMA() {
// Create the ad display container.
createAdDisplayContainer();
// Create ads loader.
adsLoader = new google.ima.AdsLoader(adDisplayContainer);
adsLoader.getSettings().setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);
// 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.
var contentEndedListener = function() {adsLoader.contentComplete();};
videoContent.onended = contentEndedListener;
// Request video ads.
var adsRequest = new google.ima.AdsRequest();
adsRequest.adTagUrl = 'VPAID LINK';
// 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);
}
function createAdDisplayContainer() {
google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);
// We assume the adContainer is the DOM id of the element that will house
// the ads.
adDisplayContainer = new google.ima.AdDisplayContainer(
document.getElementById('adContainer'),videoContent);
}
function playAds() {
// Initialize the container. Must be done via a user action on mobile devices.
videoContent.load();
adDisplayContainer.initialize();
try {
var elmnt = document.getElementById('contentElement');
// Initialize the ads manager. Ad rules playlist will start at this time.
adsManager.init(window.screen.width,window.screen.height,google.ima.ViewMode.NORMAL);
// Call play to start showing the ad. Single video and overlay ads will
// start at this time; the call will be ignored for ad rules.
adsManager.start();
window.webkit.messageHandlers.iosClickListener.postMessage('ads_started');
return;
} catch (adError) {
// An error may be thrown if there was a problem with the VAST response.
videoContent.play();
counter += 1;
if (counter == 2) {
window.setTimeout(
function() {
adsFinish();
counter = 0;
},5000);
} else {
setUpIMA();
}
}
}
function onAdsManagerLoaded(adsManagerLoadedEvent) {
// Get the ads manager.
var adsRenderingSettings = new google.ima.AdsRenderingSettings();
adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true;
// videoContent should be set to the content video element.
adsManager = adsManagerLoadedEvent.getAdsManager(
videoContent,adsRenderingSettings);
adsManager.addEventListener( google.ima.AdEvent.Type.ADS_MANAGER_LOADED,playAds);
adsManager.addEventListener( google.ima.AdEvent.Type.ALL_ADS_COMPLETED,adsFinish);
adsManager.addEventListener( google.ima.AdEvent.Type.SKIPPED,adsFinish);
// 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);
// Listen to any additional events,if necessary.
adsManager.addEventListener(
google.ima.AdEvent.Type.LOADED,onAdEvent);
adsManager.addEventListener(
google.ima.AdEvent.Type.STARTED,onAdEvent);
adsManager.addEventListener(
google.ima.AdEvent.Type.COMPLETE,onAdEvent);
adsManager.addEventListener(google.ima.AdEvent.Type.IMPRESSION,() => paused = false);
adsManager.addEventListener(google.ima.AdEvent.Type.RESUMED,() => paused = false);
adsManager.addEventListener(google.ima.AdEvent.Type.PAUSED,() => paused = true);
adsManager.addEventListener(google.ima.AdEvent.Type.ALL_ADS_COMPLETED,() => paused = undefined);
playAds();
}
function onAdEvent(adEvent) {
// Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)
// don't have ad object associated.
var ad = adEvent.getAd();
switch (adEvent.type) {
case google.ima.AdEvent.Type.LOADED:
// This is the first event sent for an ad - it is possible to
// determine whether the ad is a video ad or an overlay.
if (!ad.isLinear()) {
// Position AdDisplayContainer correctly for overlay.
// Use ad.width and ad.height.
videoContent.play();
}
break;
case google.ima.AdEvent.Type.STARTED:
adsManager.setVolume(1);
// This event indicates the ad has started - the video player
// can adjust the UI,for example display a pause button and
// remaining time.
if (ad.isLinear()) {
// For a linear ad,a timer can be started to poll for
// the remaining time.
intervalTimer = setInterval(
function() {
var remainingTime = adsManager.getRemainingTime();
},300); // every 300ms
}
break;
case google.ima.AdEvent.Type.COMPLETE:
// This event indicates the ad has finished - the video player
// can perform appropriate UI actions,such as removing the timer for
// remaining time detection.
if (ad.isLinear()) {
clearInterval(intervalTimer);
}
break;
}
}
function onAdError(adErrorEvent) {
// Handle the error logging.
console.log(adErrorEvent.getError());
adsManager.destroy();
counter += 1;
if (counter == 2) {
window.setTimeout(
function() {
adsFinish();
counter = 0;
},5000);
} else {
setUpIMA();
}
}
function onContentPauseRequested() {
adsManager.pause();
// This function is where you should setup UI for showing ads (e.g.
// display ad timer countdown,disable seeking etc.)
// setupUIForAds();
}
function onContentResumeRequested() {
adsManager.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();
}
// Wire UI element references and UI event listeners.
init();
const pauseButton = document.getElementById('pauseButton');
pauseButton.addEventListener('click',() => {
if (paused === undefined || !adsManager) return;
paused ? adsManager.resume() : adsManager.pause();
});
</script>
</body>
</html>
,
您的编码技巧非常好,但我注意到您的视频无法播放的问题似乎是由疏忽造成的。您错过了在视频标签中包含“自动播放”的内容。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。