Advertisement
Guest User

Untitled

a guest
Nov 24th, 2015
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Copyright 2012 Google Inc. All Rights Reserved.
  2. // You may study, modify, and use this example for any purpose.
  3. // Note that this example is provided "as is", WITHOUT WARRANTY
  4. // of any kind either expressed or implied.
  5.  
  6. package {
  7.     import flash.display.MovieClip;
  8.     import com.google.ads.ima.api.*;
  9.     import spark.components.Group;
  10.     import spark.components.VideoPlayer;
  11.     import spark.core.SpriteVisualElement;
  12.  
  13.     import com.google.ads.ima.api.AdErrorEvent;
  14.     import com.google.ads.ima.api.AdEvent;
  15.     import com.google.ads.ima.api.AdsLoader;
  16.     import com.google.ads.ima.api.AdsManager;
  17.     import com.google.ads.ima.api.AdsManagerLoadedEvent;
  18.     import com.google.ads.ima.api.AdsRenderingSettings;
  19.     import com.google.ads.ima.api.AdsRequest;
  20.     import com.google.ads.ima.api.ViewModes;
  21.  
  22.     import org.osmf.events.TimeEvent;
  23.  
  24.     import mx.events.FlexEvent;
  25.  
  26.     import flash.events.Event;
  27.     import flash.events.FullScreenEvent;
  28.     import flash.events.MouseEvent;
  29.  
  30.  
  31.     /**
  32.        * Simple Google IMA SDK video player integration.
  33.        */
  34.     public class Main extends MovieClip {
  35.         // The video player object.
  36.     private var videoPlayer:VideoPlayer = new VideoPlayer();
  37.  
  38.     private var fullScreenExited:Boolean;
  39.     private var contentPlayheadTime:Number;
  40.  
  41.     // SDK Objects
  42.     private var adsLoader:AdsLoader;
  43.     private var adsManager:AdsManager;
  44.  
  45.         public function Main() {
  46.             trace(videoPlayer)
  47.             SdkIntegrationExample(videoPlayer);
  48.         }
  49.  
  50.         private static const CONTENT_URL:String =
  51.         "http://rmcdn.2mdn.net/Demo/vast_inspector/android.flv";
  52.  
  53.     private static const LINEAR_AD_TAG:String =
  54.         "http://pubads.g.doubleclick.net/gampad/ads?sz=400x300&" +
  55.         "iu=%2F6062%2Fiab_vast_samples&ciu_szs=300x250%2C728x90&impl=s&" +
  56.         "gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&" +
  57.         "url=[referrer_url]&correlator=[timestamp]&" +
  58.         "cust_params=iab_vast_samples%3Dlinear";
  59.  
  60.     private static const NONLINEAR_AD_TAG:String =
  61.         "http://pubads.g.doubleclick.net/gampad/ads?sz=400x300&" +
  62.         "iu=%2F6062%2Fiab_vast_samples&ciu_szs=300x250%2C728x90&" +
  63.         "impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&" +
  64.         "url=[referrer_url]&correlator=[timestamp]&" +
  65.         "cust_params=iab_vast_samples%3Dimageoverlay";
  66.  
  67.     /**
  68.      * Sets up the click-to-play player for ads and content playback.
  69.      *
  70.      * @param videoPlayerValue The content video player.
  71.      */
  72.     public function SdkIntegrationExample(videoPlayerValue:VideoPlayer):void {
  73.       videoPlayer = videoPlayerValue;
  74.       videoPlayer.source = CONTENT_URL;
  75.       // Add some custom event handlers.
  76.       //videoPlayer.stage.addEventListener(FullScreenEvent.FULL_SCREEN,
  77.         //                                 fullscreenChangeHandler);
  78.       videoPlayer.addEventListener(TimeEvent.COMPLETE, contentCompleteHandler);
  79.       videoPlayer.addEventListener(TimeEvent.CURRENT_TIME_CHANGE,
  80.                                    contentPlayheadTimeChangeHandler);
  81.       // Workaround flex problem with fullscreen: when fullscreen is exited,
  82.       // flex video player component still has the old dimension values. We wait
  83.       // for update complete event, after which correct values are available.
  84.       videoPlayer.addEventListener(FlexEvent.UPDATE_COMPLETE,
  85.                                    videoPlayerUpdateCompleteHandler);
  86.       initAdsLoader();
  87.     }
  88.  
  89.     /**
  90.      * Handler for when a user clicks on the "Linear Ad" radio button.
  91.      */
  92.     public function linearAdSelectionHandler(event:Event):void {
  93.       destroyAdsManager();
  94.       requestAds(LINEAR_AD_TAG);
  95.     }
  96.  
  97.     /**
  98.      * Handler for when a user clicks on the "Non-linear Ad" radio button.
  99.      */
  100.     public function nonlinearAdSelectionHandler(event:Event):void {
  101.       destroyAdsManager();
  102.       requestAds(NONLINEAR_AD_TAG);
  103.     }
  104.  
  105.  
  106.     /**
  107.      * Initialize the AdsLoader and load the SDK
  108.      */
  109.     private function initAdsLoader():void {
  110.       if (adsLoader == null) {
  111.         // On the first request, create the AdsLoader.
  112.         adsLoader = new AdsLoader();
  113.         // The SDK uses a 2 stage loading process. Without this call, the second
  114.         // loading stage will take place when ads are requested. Including this
  115.         // call will decrease latency in starting ad playback.
  116.         adsLoader.loadSdk();
  117.       }
  118.     }
  119.  
  120.     /**
  121.      * Request ads using the specified ad tag.
  122.      *
  123.      * @param adTag A URL that will return a valid VAST response.
  124.      */
  125.     private function requestAds(adTag:String):void {
  126.       // The AdsRequest encapsulates all the properties required to request ads.
  127.       var adsRequest:AdsRequest = new AdsRequest();
  128.       adsRequest.adTagUrl = adTag;
  129.       adsRequest.linearAdSlotWidth = videoPlayer.width;
  130.       adsRequest.linearAdSlotHeight = videoPlayer.height;
  131.       adsRequest.nonLinearAdSlotWidth = videoPlayer.width;
  132.       adsRequest.nonLinearAdSlotHeight = videoPlayer.height;
  133.  
  134.       // Instruct the AdsLoader to request ads using the AdsRequest object.
  135.       adsLoader.requestAds(adsRequest);
  136.     }
  137.  
  138.     /**
  139.      * Invoked when the AdsLoader successfully fetched ads.
  140.      */
  141.     private function adsManagerLoadedHandler(event:AdsManagerLoadedEvent):void {
  142.       // Publishers can modify the default preferences through this object.
  143.       var adsRenderingSettings:AdsRenderingSettings =
  144.           new AdsRenderingSettings();
  145.  
  146.       // In order to support ad rules ads, ads manager requires an object that
  147.       // provides current playhead position for the content.
  148.       var contentPlayhead:Object = {};
  149.       contentPlayhead.time = function():Number {
  150.         return contentPlayheadTime * 1000; // convert to milliseconds.
  151.       };
  152.  
  153.       // Get a reference to the AdsManager object through the event object.
  154.       adsManager = event.getAdsManager(contentPlayhead, adsRenderingSettings);
  155.       if (adsManager) {
  156.         // Add required ads manager listeners.
  157.         // ALL_ADS_COMPLETED event will fire once all the ads have played. There
  158.         // might be more than one ad played in the case of ad pods and ad rules.
  159.         adsManager.addEventListener(AdEvent.ALL_ADS_COMPLETED,
  160.                                     allAdsCompletedHandler);
  161.         // If ad is linear, it will fire content pause request event.
  162.         adsManager.addEventListener(AdEvent.CONTENT_PAUSE_REQUESTED,
  163.                                     contentPauseRequestedHandler);
  164.         // When ad finishes or if ad is non-linear, content resume event will be
  165.         // fired. For example, if ad rules response only has post-roll, content
  166.         // resume will be fired for pre-roll ad (which is not present) to signal
  167.         // that content should be started or resumed.
  168.         adsManager.addEventListener(AdEvent.CONTENT_RESUME_REQUESTED,
  169.                                     contentResumeRequestedHandler);
  170.         // We want to know when an ad starts.
  171.         adsManager.addEventListener(AdEvent.STARTED, startedHandler);
  172.         adsManager.addEventListener(AdErrorEvent.AD_ERROR,
  173.                                     adsManagerPlayErrorHandler);
  174.  
  175.         // If your video player supports a specific version of VPAID ads, pass
  176.         // in the version. If your video player does not support VPAID ads yet,
  177.         // just pass in 1.0.
  178.         adsManager.handshakeVersion("1.0");
  179.         // Init should be called before playing the content in order for ad rules
  180.         // ads to function correctly.
  181.         adsManager.init(videoPlayer.videoDisplay.width,
  182.                         videoPlayer.videoDisplay.height,
  183.                         ViewModes.NORMAL);
  184.  
  185.         // Add the adsContainer to the display list. Below is an example of how
  186.         // to do it in Flex.
  187.         var flexAdContainer:SpriteVisualElement = new SpriteVisualElement();
  188.         flexAdContainer.addChild(adsManager.adsContainer);
  189.         (videoPlayer.videoDisplay.parent as Group).addElement(flexAdContainer);
  190.  
  191.         // Start the ad playback.
  192.         adsManager.start();
  193.       }
  194.     }
  195.  
  196.     /**
  197.      * If an error occurs during the ads load, the content can be resumed or
  198.      * another ads request can be made. In this example, the content is resumed
  199.      * if there's an error loading ads.
  200.      */
  201.     private function adsLoadErrorHandler(event:AdErrorEvent):void {
  202.       trace("warning", "Ads load error: " + event.error.errorMessage);
  203.       videoPlayer.play();
  204.     }
  205.  
  206.     /**
  207.      * Errors that occur during ads manager play should be treated as
  208.      * informational signals. The SDK will send all ads completed event if there
  209.      * are no more ads to display.
  210.      */
  211.     private function adsManagerPlayErrorHandler(event:AdErrorEvent):void {
  212.       trace("warning", "Ad playback error: " + event.error.errorMessage);
  213.     }
  214.  
  215.     /**
  216.      * Clean up AdsManager references when no longer needed. Explicit cleanup
  217.      * is necessary to prevent memory leaks.
  218.      */
  219.     private function destroyAdsManager():void {
  220.       enableContentControls();
  221.       if (adsManager) {
  222.         if (adsManager.adsContainer.parent &&
  223.             adsManager.adsContainer.parent.contains(adsManager.adsContainer)) {
  224.           adsManager.adsContainer.parent.removeChild(adsManager.adsContainer);
  225.         }
  226.         adsManager.destroy();
  227.       }
  228.     }
  229.  
  230.     /**
  231.      * The AdsManager raises this event when it requests the publisher to pause
  232.      * the content.
  233.      */
  234.     private function contentPauseRequestedHandler(event:AdEvent):void {
  235.       // The ad will cover a large portion of the content, therefore content
  236.       // must be paused.
  237.       if (videoPlayer.playing) {
  238.         videoPlayer.pause();
  239.       }
  240.       // Manually flip play button state.
  241.       videoPlayer.playPauseButton.selected =
  242.             !videoPlayer.playPauseButton.selected;
  243.       // Rewire controls to affect ads manager instead of the content video.
  244.       enableLinearAdControls();
  245.       // Ads usually do not allow scrubbing.
  246.       canScrub = false;
  247.     }
  248.  
  249.     /**
  250.      * The AdsManager raises this event when it requests the publisher to resume
  251.      * the content.
  252.      */
  253.     private function contentResumeRequestedHandler(event:AdEvent):void {
  254.       // Rewire controls to affect content instead of the ads manager.
  255.       enableContentControls();
  256.       videoPlayer.play();
  257.     }
  258.  
  259.     /**
  260.      * The AdsManager raises this event when the ad has started.
  261.      */
  262.     private function startedHandler(event:AdEvent):void {
  263.       // If the ad exists and is a non-linear, start the content with the ad.
  264.       if (event.ad != null && !event.ad.linear) {
  265.         videoPlayer.play();
  266.       }
  267.     }
  268.  
  269.     /**
  270.      * The AdsManager raises this event when all ads for the request have been
  271.      * played.
  272.      */
  273.     private function allAdsCompletedHandler(event:AdEvent):void {
  274.       // Ads manager can be destroyed after all of its ads have played.
  275.       destroyAdsManager();
  276.     }
  277.  
  278.     /**
  279.      * The video player raises this event when the user clicks the play/pause
  280.      * button.
  281.      */
  282.     private function playPauseButtonHandler(event:MouseEvent):void {
  283.       // Prevent video player from receiving the event, because it would affect
  284.       // content.
  285.       event.stopImmediatePropagation();
  286.       var paused:Boolean = !videoPlayer.playPauseButton.selected;
  287.       if (paused) {
  288.         adsManager.pause();
  289.       } else {
  290.         adsManager.resume();
  291.       }
  292.     }
  293.  
  294.     /**
  295.      * Switches the video player controls to control the video ad.
  296.      */
  297.     private function enableLinearAdControls():void {
  298.       // Subscribe to the player control click events with maximum
  299.       // priority, so that we can handle the click before it is handled by the
  300.       // VideoPlayer instance.
  301.       videoPlayer.playPauseButton.addEventListener(MouseEvent.CLICK,
  302.                                                    playPauseButtonHandler,
  303.                                                    false, // use capture.
  304.                                                    int.MAX_VALUE);
  305.       videoPlayer.volumeBar.addEventListener(Event.CHANGE,
  306.                                              volumeChangeHandler,
  307.                                              false, // use capture.
  308.                                              int.MAX_VALUE);
  309.       videoPlayer.volumeBar.addEventListener(FlexEvent.MUTED_CHANGE,
  310.                                              volumeMutedHandler,
  311.                                              false, // use capture.
  312.                                              int.MAX_VALUE);
  313.     }
  314.  
  315.     /**
  316.      * Switches the video player controls to control the content.
  317.      */
  318.     private function enableContentControls():void {
  319.       videoPlayer.playPauseButton.removeEventListener(MouseEvent.CLICK,
  320.                                                       playPauseButtonHandler);
  321.       videoPlayer.volumeBar.removeEventListener(Event.CHANGE,
  322.                                                 volumeChangeHandler);
  323.       videoPlayer.volumeBar.removeEventListener(FlexEvent.MUTED_CHANGE,
  324.                                                 volumeMutedHandler);
  325.       canScrub = true;
  326.     }
  327.  
  328.     private function volumeMutedHandler(event:FlexEvent):void {
  329.       // Prevent video player from receiving the event, because it would affect
  330.       // content.
  331.       event.stopImmediatePropagation();
  332.       adsManager.volume = 0;
  333.     }
  334.  
  335.     private function volumeChangeHandler(event:Event):void {
  336.       // Prevent video player from receiving the event, because it would affect
  337.       // content.
  338.       event.stopImmediatePropagation();
  339.       adsManager.volume = videoPlayer.volumeBar.value;
  340.     }
  341.  
  342.     private function set canScrub(value:Boolean):void {
  343.       videoPlayer.scrubBar.enabled = value;
  344.       videoPlayer.scrubBar.mouseEnabled = value;
  345.     }
  346.  
  347.     /**
  348.      * Update the playhead time for the AdsManager.
  349.      */
  350.     private function contentPlayheadTimeChangeHandler(event:TimeEvent):void {
  351.       contentPlayheadTime = event.time;
  352.     }
  353.  
  354.     private function fullscreenChangeHandler(event:FullScreenEvent):void {
  355.       if (event.fullScreen) {
  356.         adsManager.resize(videoPlayer.videoDisplay.width,
  357.                           videoPlayer.videoDisplay.height,
  358.                           ViewModes.FULLSCREEN);
  359.       } else {
  360.         fullScreenExited = true;
  361.         // Ads manager resize will occur after update complete.
  362.       }
  363.     }
  364.  
  365.     /**
  366.      * Workaround for a bug in the video player's full screen functionality.
  367.      */
  368.     private function videoPlayerUpdateCompleteHandler(event:FlexEvent):void {
  369.       if (fullScreenExited) {
  370.         fullScreenExited = false;
  371.         adsManager.resize(videoPlayer.videoDisplay.width,
  372.                           videoPlayer.videoDisplay.height,
  373.                           ViewModes.NORMAL);
  374.       }
  375.     }
  376.  
  377.     /**
  378.      * The video player raises this event when the content has finished playing.
  379.      */
  380.     private function contentCompleteHandler(event:TimeEvent):void {
  381.       videoPlayer.stage.removeEventListener(FullScreenEvent.FULL_SCREEN,
  382.                                             fullscreenChangeHandler);
  383.       videoPlayer.removeEventListener(FlexEvent.UPDATE_COMPLETE,
  384.                                       videoPlayerUpdateCompleteHandler);
  385.       videoPlayer.removeEventListener(TimeEvent.COMPLETE,
  386.                                       contentCompleteHandler);
  387.       // Tell the SDK when any content completes, even content without ads. The
  388.       // SDK uses this method for better ad selection (especially ad rules).
  389.       adsLoader.contentComplete();
  390.     }
  391.  
  392.  
  393.     }
  394. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement