Javascript 自动播放ads IMA SDK HTML5

Javascript 自动播放ads IMA SDK HTML5,javascript,html5-video,autoplay,imasdk,vpaid,Javascript,Html5 Video,Autoplay,Imasdk,Vpaid,我正在尝试为HTML5播放器创建自动播放广告,我使用VPAID和IMA SDK。 我确实阅读了有关如何使用autoplay等的文档,但无法创建此代码 请解释我的错误以及如何修复,我的代码示例附在下面。 现在我只能通过点击开始广告 Index.html <!doctype html> <html lang="en"> <head> <title>IMA HTML5 Simple Demo</title>

我正在尝试为HTML5播放器创建自动播放广告,我使用VPAID和IMA SDK。 我确实阅读了有关如何使用autoplay等的文档,但无法创建此代码

请解释我的错误以及如何修复,我的代码示例附在下面。 现在我只能通过点击开始广告

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>
ads.js

#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%;
}
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, 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();
        }
    }

    function onContentPauseRequested() {
      videoElement.pause();
    }

    function onContentResumeRequested() {
      videoElement.play();
    }

    function onAdLoaded(adEvent) {
      var ad = adEvent.getAd();
      if (!ad.isLinear()) {
        videoElement.play();
      }
    }

你的编码技巧很好,但我注意到你的视频无法播放的问题似乎是由于疏忽造成的。您没有在视频标签中添加“自动播放”。

我正在重写代码,现在ads有自动播放和全屏功能,在所有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, 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>

IMAHTML5简单演示
#视频容器{
位置:绝对位置;
排名:0;
左:0;
宽度:100%;
身高:100%;
}
#广告容器{
位置:绝对位置;
排名:0;
左:0;
宽度:100%;
}
#内容元素{
位置:绝对位置;
排名:0;
左:0;
宽度:100%;
身高:100%;
}
#播放按钮{
边缘顶部:10px;
垂直对齐:顶部;
宽度:1px;
高度:1px;
填充:0;
字体大小:22px;
颜色:白色;
文本对齐:居中;
文本阴影:0 1px2pRGBA(0,0,0,0.25);
背景#2c3e50;
边界:0;
边框底部:2个实心#22303f;
光标:指针;
-网络工具包盒阴影:插图0-2px#22303f;
盒影:插图0-2px#22303f;
}
玩
风险资产管理人;
无功负载;
var附加显示容器;
无功间隔定时器;
var播放按钮;
视频内容;
var暂停;
变量计数器=0
函数init(){
console.log('init')
videoContent=document.getElementById('contentElement');
playButton=document.getElementById('playButton');
playButton.addEventListener('click',testButton');
setUpIMA();
}
函数testButton(){
window.setTimeout(
函数(){
document.body.style.backgroundColor=`red`;
adsManager.pause();
}, 1000);
}
函数testButtonPlay(){
window.setTimeout(
函数(){
document.body.style.backgroundColor=`green`;
adsManager.play();
}, 2000);
}
函数adsfish(){
window.webkit.messageHandlers.iosclicklister.postMessage('ads_finish');
}
函数setUpIMA(){
//创建广告显示容器。
createAdDisplayContainer();
//创建广告加载器。
adsLoader=新的google.ima.adsLoader(adDisplayContainer);
adsLoader.getSettings().setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);
//收听并响应加载的广告和错误事件。
adsLoader.addEventListener(
google.ima.AdsManagerLoadedEvent.Type.ADS\u MANAGER\u已加载,
OnadManager已加载,
假);
adsLoader.addEventListener(
google.ima.AdErrorEvent.Type.AD_错误,
奥纳德罗,
假);
//一个事件侦听器,告诉SDK我们的内容视频
//已完成,因此SDK可以播放任何后期滚动广告。
var contentEndedListener=function(){adsLoader.contentComplete();};
videoContent.onended=contentEndedListener;
//请求视频广告。
var adsRequest=new google.ima.adsRequest();
adsRequest.adTagUrl='VPAID LINK';
//指定线性和非线性插槽大小。这有助于SDK
//如果返回多个,请选择正确的创意。
adsRequest.lineardslotwidth=640;
adsRequest.LineardSlotheight=400;
adsRequest.nonlineardslotwidth=640;
adsRequest.nonlineardslotheight=150;
adsLoader.requestAds(adsRequest);
}
函数createAdDisplayContainer(){
google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);
//我们假设adContainer是要容纳的元素的DOM id
//广告。
adDisplayContainer=新的google.ima.adDisplayContainer(
document.getElementById('adContainer'),videoContent);
}
函数playAds(){
//初始化容器。必须通过移动设备上的用户操作完成。
videoContent.load();
adDisplayContainer.initialize();
试一试{
var elmnt=document.getElementById('contentElement');
//初始化广告管理器。此时将启动广告规则播放列表。
init(window.screen.width、window.screen.height、google.ima.ViewMode.NORMAL);
//呼叫play开始显示广告。单个视频和叠加广告将
//此时开始;对于ad规则,该调用将被忽略。
adsManager.start();
window.webkit.messageHandlers.iosclicklister.postMessage('ads_start');
返回;
}捕获(错误){
//如果大量响应出现问题,可能会抛出错误。
videoContent.play();
计数器+=1;
如果(计数器==2)