Home > Youtube, Youtube Wrapper > Youtube AS3 Wrapper – How to use

Youtube AS3 Wrapper – How to use

March 30th, 2009

This is a How to guideline on the Youtube AS3 Wrapper.

Before starting, this tutorial assumes you are at least familiar with AS3.

  • Firstly, you should download the latest Youtube AS3 Wrapper from here (the lastest at the time of this writing is v0.7). Unzip the contents into your project folder (generally the 2 swf file should be placed in the same directory as the swf file that will use the wrapper, or a subdirectory of it; in this tutorial I will assume they are in the same directory). Next, depending on whether you’re using the .as source files, found under pinosh/youtube/ in the zip archive, or the .swc component, located in the swc folder, you should place the 2 .as source files in the Classpath of your project, or include the .swc in the components directory.
    My Directory structure looks like this:
    • rootproject
      • classes
        • pinosh
          • youtube
            • IYoutube.as
            • YoutubeEvent.as
      • ytPlayer.swf
      • ytODLCWrapper.swf
      • TestPlayer.as
      • TestPlayer.swf
      • TestPlayer.fla

    With a directory like this, I should set the classPath to “./classes”.

  • Now TestPlayer.as will be set as the Document class in Flash. Since it’s going to be the Document class, we should make the TestPlayer class extend MovieClip.
    This is how our bare bones class should look at first:
    package {
    import flash.display.MovieClip;
        public class TestPlayer extends MovieClip {
            public function TestPlayer() {
                 super();
            }
        }
    }
  • Next, we will need IYoutube interface and YoutubeEvent class, so let’s import those:
        import pinosh.youtube.IYoutube;
        import pinosh.youtube.YoutubeEvent;

    Also, because we must load the ytPlayer.swf in our swf at runtime, we will need the Loader class and URLRequest class. Also we’ll need IOErrorEvent class and Event class to handle properly the events dispatched by our loader.

        import flash.events.Event;
        import flash.events.IOErrorEvent;
        import flash.display.Loader;
        import flash.net.URLRequest;
  • Now we have set up everything we need. So let’s load our youtube player. We’ll save our player, after it has been loaded, in a private variable named player.
    The code to load the player, will be placed inside the constructor of our TestPlayer class:
    var loader : Loader = new Loader();
    // listen for the right events
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.playerLoaded);
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.playerCannotBeLoaded);

    loader.load(new URLRequest("ytPlayer.swf")); // to pass the youtube api key use "ytPlayer.swf?apiKey="+apiKey

    Now we must declare and define the 2 event handler methods:

         private function playerLoaded(event : Event) : void {
                // grab the loader object
                var loader : Loader = event.target["loader"] as Loader;
                // add it to the display list of TestPlayer
                this.addChild(loader);
               
                // grab the IYoutube object; it's the content property of the loader object
                this.player = loader.content as IYoutube;
                // start listening for the events dispatched by player
                this.player.addEventListener(YoutubeEvent.PLAYER_READY, this.onYTPlayerReady);
                this.player.addEventListener(YoutubeEvent.PLAYER_STATE_CHANGE, this.onYTPlayerStateChange);
                this.player.addEventListener(YoutubeEvent.PLAYER_ERROR, this.onYTPlayerError);
         }

         private function playerCannotBeLoaded(event : IOErrorEvent) : void {
               // trace the for this test, bu should be handled more carrefully
               trace("Player Cannot be found: "+event);
         }
  • Now we’re only left with the youtube handler methods, and we should declare those.
         private function onYTPlayerReady(event : YoutubeEvent) : void {
                // now our player is ready to rumble; let's play a clip
                this.player.loadVideo("Lrmf283dSXw");
         }

         private function onYTPlayerStateChange(event : YoutubeEvent) : void {
                trace("TestPlayer::onYTPlayerStateChange ==> "+this.player.getPlayerState());
         }

         private function onYTPlayerError(event : YoutubeEvent) : void {
                trace("TestPlayer::onYTPlayerError ==> "+this.player.getPlayerError());
         }

So this is about everything to load the wrapper and play a first clip.

Here is how the entire class file should look like:

package {
import flash.display.MovieClip;
    import pinosh.youtube.IYoutube;
    import pinosh.youtube.YoutubeEvent;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.display.Loader;
    import flash.net.URLRequest;

    public class TestPlayer extends MovieClip {
        private var player : IYoutube;
        public function TestPlayer() {
             super();
             var loader : Loader = new Loader();
             // listen for the right events
             loader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.playerLoaded);
             loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.playerCannotBeLoaded);

             loader.load(new URLRequest("ytPlayer.swf")); // to pass the youtube api key use "ytPlayer.swf?apiKey="+apiKey
        }

        private function playerLoaded(event : Event) : void {
            // grab the loader object
            var loader : Loader = event.target["loader"] as Loader;
            // add it to the display list of TestPlayer
            this.addChild(loader);
           
            // grab the IYoutube object; it's the content property of the loader object
            this.player = loader.content as IYoutube;
            // start listening for the events dispatched by player
            this.player.addEventListener(YoutubeEvent.PLAYER_READY, this.onYTPlayerReady);
            this.player.addEventListener(YoutubeEvent.PLAYER_STATE_CHANGE, this.onYTPlayerStateChange);
            this.player.addEventListener(YoutubeEvent.PLAYER_ERROR, this.onYTPlayerError);
     }

     private function playerCannotBeLoaded(event : IOErrorEvent) : void {
           // trace the for this test, bu should be handled more carrefully
           trace("Player Cannot be found: "+event);
     }

     private function onYTPlayerReady(event : YoutubeEvent) : void {
            // now our player is ready to rumble; let's play a clip
            this.player.loadVideo("Lrmf283dSXw");
     }

     private function onYTPlayerStateChange(event : YoutubeEvent) : void {
            trace("TestPlayer::onYTPlayerStateChange ==> "+this.player.getPlayerState());
     }

     private function onYTPlayerError(event : YoutubeEvent) : void {
            trace("TestPlayer::onYTPlayerError ==> "+this.player.getPlayerError());
     }

   }
}

For the entire documentation and a list of all the methods you can use to manage youtube clips,
please check out the documentation: Youtube AS3 Wrapper – Documentation

When you test your app, make sure you don’t test in the Flash IDE as it will not work. Test it in browser or in standalone flash player!

This wrapper can be used with flex too, not only with flash. The Test Harness Player is a flex app. You can view the Test Harness Player here, and download the entire source for it here.

  • Delicious
  • Facebook
  • MySpace
  • StumbleUpon
  • Digg
  • Furl
  • LinkedIn
  • Reddit
  • Share/Save/Bookmark

admin Youtube, Youtube Wrapper , , , ,

  1. milife
    April 18th, 2009 at 20:42 | #1

    hi thanks works in flex but not with AIR?

  2. April 20th, 2009 at 13:15 | #2

    Hi, it does not yet work with AIR due to the way AIR modifies connection names in LocalConnection.
    This should be fixed in a next release.
    Ovidiu

  3. April 21st, 2009 at 23:36 | #3

    Can we use this wrapper in an opensource project? we will be very gratefull if we may!

    thank you for this wrapper , i am going to test it right now!

  4. April 21st, 2009 at 23:36 | #4

    I would like to announce that a new version, v0.7.1, of Youtube AS3 Wrapper is available for download.
    This new version adds Adobe AIR support.
    Best Regards,
    Ovidiu

  5. April 22nd, 2009 at 09:26 | #5

    Yes sure you can use it, but only as it is, the source code will not be made public.

  6. Paul
    April 22nd, 2009 at 10:58 | #6

    This looks great! However, I tried to used your wrapper in my Flash project without success so far. It could be a few things but I was wondering since you posted up the AS3 example code could you also post a small fla demo?

  7. April 22nd, 2009 at 11:05 | #7

    I will post a fla demo, in a future post, however make sure you test your movie in browser or standalone player, as it will not work if you test directly in FLASH IDE. So if you followed on this post correctly, compiled your swf and test in browser or standalone, it will work for certain.

  8. Paul
    April 22nd, 2009 at 14:11 | #8

    I did indeed follow your original instructions and when I load the compiled swf I get a Flash Player Security warning dialog box. I guess the problem is something to do with creating a local-trusted sandbox?

  9. April 22nd, 2009 at 14:24 | #9

    That’s the Flash Player Security Dialog. You must allow the swf to communicate with the internet. To do that, just follow the instructions in the dialog. And allow the swf to communicate with the internet, or allow the entire folder where the swf is in.

  10. Bejil
    April 26th, 2009 at 21:32 | #10

    Hi ! First, thanks for this source you share with us.
    I’m searching for it since a long time.

    Just a question : the youtube window added to the scene, what am I supposed to do in order to play the video ?

    I tried this.player.playVideo(); but it doesn’t do anything…

    Thanks a lot (excuse my english, i’m french :S)

  11. April 26th, 2009 at 23:14 | #11

    Hi, You’re very welcome. I hope you find it usefull.

    To play a youtube video you have the loadVideo(videoId:String):void and cueVideo(videoId:String):void methods. The videoId parameter is the vide id string as seen on Youtube site or an entire link as seen on Youtube site.
    The playVideo():void method is for resuming a video from a paused state.
    For more info please look at the entire documentation found here.

  12. Bejil
    April 27th, 2009 at 00:53 | #12

    Thanks.

    I have already looked the doc. My question was stupid because I read that loadVideo() play the video. But i can’t understand what’s happening.

    None of the 3 YoutubeEvents are fired.
    I put some trace after their adding and it don’t trace me anything.
    Then I trace “this.player” after the line “this.player = loader.content as IYoutube;” and it returns me “null”.

    It would at least say to me that it’s an IYoutube object no ?

  13. April 27th, 2009 at 09:26 | #13

    If you did everything exactly like in this tutorial, make sure you test in browser or in standalone player. If you test in the Flash IDE, it will not work.
    Also make sure the you don’t receive the IO_ERROR event.
    Please let me know if you need further help.

  14. Bejil
    April 27th, 2009 at 11:21 | #14

    Thanks a lot for your answer.

    I restart from the beginning by following your files organisation and the video is now playing, wahou !

    I am now trying to adapt it to mine.

    So, I put TestPlayer.as into a folder namde “com/zen” and change his package path to “com.zen” : it’s working again.

    Then I put your “pinosh” folder into “com/” and :

    - in IYouTube.as change “package com.pinosh.youtube” and
    [Event(name="playerReady", type="com.pinosh.youtube.YoutubeEvent")]
    [Event(name="playerError", type="com.pinosh.youtube.YoutubeEvent")]
    [Event(name="playerStateChange", type="com.pinosh.youtube.YoutubeEvent")]

    - in YouTubeEvent.as change “package com.pinosh.youtube ”

    But it’s not working. It’s the problem I had yesterday, I try directly to adapt it to my arborescence. I shall not, it would have made me spare time.

  15. April 27th, 2009 at 11:28 | #15

    You cannot change the package of IYoutube nor YoutubeEvent. If you do so, flash compiler will complain about it. That’s because the ytPlayer.swf file is compiled using the files as they are, in their packages, and you can’t change them unless recompile the swf files.
    So you’ll have to leave them as they are.

  16. Bejil
    April 27th, 2009 at 12:20 | #16

    That’s what I supposed, ok !
    I will try to change the ytPlayer.swf (if you allow me to), otherwise i will let it like that. I will inform you of my progress.

    In any case, thank you very much for your precious help and this magnificent source.

  17. Bejil
    April 27th, 2009 at 17:20 | #17

    I tried to decompile it and I seen “new pinosh.ytAS2LCWrapper.YtAS2LCWrapper(this);” in ytODLCWrapper.swf.
    I changed it to “com.pinosh…” but it doesn’t work.

    I’ll leave it as it is, no importance.

  18. April 27th, 2009 at 18:43 | #18

    Ok.
    You can use it however is easier for you :-)

  19. Bejil
    April 27th, 2009 at 18:48 | #19

    Arf, once again, i’m back…
    If I create two instances of TestPlayer.as and add them to the stage, the second doesn’t load the youtube movie.

    I thought your code allowed the cohabitation of multiple instances ?

  20. April 27th, 2009 at 19:15 | #20

    This wrapper allows multiple instances of players on the same html page, but not inside the same swf file.
    This is a limitation for now.

  21. Bejil
    April 27th, 2009 at 19:34 | #21

    ha, I was afraid of that…
    I’m searching the way of adding several video on the same scene.

    I was confronted with the same problem by using “tubeloc” describes on the youtube api, do you know a way where I could search ?

  22. April 27th, 2009 at 20:24 | #22

    No I don’t know any wrappers able to do this, yet.
    Sorry.

  23. Bejil
    April 27th, 2009 at 21:04 | #23

    I think I find something :
    http://prlwytzkofsky.com/2009/03/streaming-multiple-youtube-videos/

    The example :
    http://www.robinvanemden.dds.nl/

    My competences in as3 are limited but I will try to do something with it…

  24. April 27th, 2009 at 21:41 | #24

    You should watch out with that way, because it takes the link to the flv file directly instead of using the API provided by Youtube, which is rather fraudulent. Also, Youtube’s CDN changes ips very frequently, which could break that mechanism.
    Anyway, I wish you success in using that API.

  25. Bejil
    April 28th, 2009 at 11:16 | #25

    Take advice of your pillow!

    This morning, I said myself: but why not use a proxy?

    In fact, I just want to add one or more video on the stage (selected by the user). As a result I just pass the URL of the video to my php (ex: http://www.youtube.com/swf/l.swf?swf=http%3A//s.ytimg.com/yt/swf/cps-vfl92380.swf&video_id=XkOYGrZQqmU&rel=1&eurl=&iurl=http%3A//i4.ytimg.com/vi/XkOYGrZQqmU/hqdefault.jpg&sk=l0QjRmBZQRE_1FByyA0WrgfATubky5fHC&cr=US&avg_rating=4.77391304348&video_id=XkOYGrZQqmU).

    The php reads and returns the content.

    It is perfect and so much simple that I can’t believe it’s working !

  26. April 28th, 2009 at 16:14 | #26

    Yes,
    but as I said “Youtube’s CDN changes ips very frequently, which could break that mechanism”.

  27. June 8th, 2009 at 06:13 | #27

    Error #2044: Unhandled IOErrorEvent:. text=Error #2124: Loaded file is an unknown type.

    seems to load really nice !….but get this error ….

  28. June 8th, 2009 at 09:38 | #28

    You should try redownloading the latest wrapper, maybe you got your’s corrupt, and see if that works.

  29. Jerry Brook
    August 27th, 2009 at 16:51 | #29

    Hi,
    can anybody tell me, why the video doesnt load. Im not very good in scripting. I put in my main.fla in the frist frame this script:

    var myTestPlayer:TestPlayer = new TestPlayer();

    i get no error message. thx 4 the help and sorry 4 the english.

    cp

  30. August 27th, 2009 at 17:03 | #30

    You need to add your created object to the display list of an object on the stage.
    You can add after the line where you initialize myTestPlayer:

    this.addChild(myTestPlayer);
  31. Jerry Brook
    August 28th, 2009 at 10:53 | #31

    …sorry. thx a lot! its working.

  32. Wenhu
    September 20th, 2009 at 14:51 | #32

    Hi, I tried your example locally(non air version) with 0.8 version. the ytLoaded method is triggered, but the ytReady was never triggered, because i got the following error:
    SecurityError: Error #2000: No active security context

    I have tried the following statement in init method:
    _loaderContext.checkPolicyFile = true;
    var loader : Loader = new Loader();
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.ytLoaded);
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.ytIOError);

    loader.load(new URLRequest(”ytPlayer.swf?apiKey=”+API_KEY),_loaderContext); // load ytPlayer.swf : will give us the ytPlayer; to pass in the youtube api key ==> “ytPlayer.swf?apiKey=XXXXXX”

    but no luck. Can anyone help me or anyone with similiar experience?

    Thanks

  33. September 21st, 2009 at 11:19 | #33

    Firstly, you should make sure that the swf file you’re testing has access to the internet (which you can provide by using the Global Security Settings Manager on the adobe’s site).
    Then, since you use a LoaderContext object, what is the ApplicationDomain that you pass to the LoaderContext?
    Also, what is the SecurityContext you pass to the LoaderContext object, although it shouldn’t have any effect since you load from the same domain.

    Also, what is your reason to use a LoaderContext object, because you load the swf’s from the same domain as your main swf file is in, thus the policy file is not needed…?

  1. April 1st, 2009 at 21:06 | #1