Home > Actionscript 3.0, FLEX, Youtube, Youtube Wrapper > Youtube AS3 Wrapper

Youtube AS3 Wrapper

March 26th, 2009

I started building this AS3 to AS2 youtube wrapper some time back, from the need to add youtube support to actionscript 3 projects, and now i decided to share it.
I tried some of the wrappers available out there, some are good, soom are pretty bad but all of them had all sorts of issues. Some had problems with volume, some were not capable of supporting more than 1 instance of a player on the same page, some were using javascript which i found inacceptable, so i started writing my own wrapper.

SEE A TEST PLAYER HERE

DOWNLOAD WRAPPER HERE

SEE A HOW TO START TUTORIAL HERE

SEE FULL DOCUMENTATION HERE

SEE A MULTIPLE INSTANCES SAMPLE HERE

What came out, i might say that’s probably the best wrapper available yet: it uses LocalConnection to communicate to the As2 youtube player, but it’s still very responsive and fast.

Very easy to use, follows the youtube as2 chromeless style: load a swf, listen for a ready event and then you’re good to go!

It uses interfaces to support code completion on editors that support it: FDT, Flex Builder, Flash Develop, etc.

Small in size: 2 swf files – ytPlayer.swf only 4,230 Bytes <=> 4.13 KB
– ytODLCWrapper.swf only 4,305 Bytes <=> 4.20 KB

Optimized for responsivness – reduced to the minimum the number of LocalConnection calls

Uses the same method calls as youtube api with some minor changes and some additions.
So, for someone familiar with the youtube api will find this very easy to use.

And it’s also easy for the one that starts his way into youtube just now, with just a few lines of code youtube will be set up and running.

So how does this work?
As i mentioned above, there a are these 2 swf file: ytPlayer.swf and ytODLCWrapper.swf.

ytPlayer.swf is the as3 version, and the one that’s most important to you.
ytODLCWrapper.swf is the as2 version, and it’s handled in the background, you don’t need to worry about this one.

There is 1 interface

pinosh.youtube.IYoutube

and 1 class

pinosh.youtube.YoutubeEvent
IYoutube

is the player, has all the methods of the player and

YoutubeEvent

is the type of event that will be thrown by IYoutube.
There are only 3 types of events:

YoutubeEvent.PLAYER_READY

dispatched when the player is ready to play video clips: only after this event is fired, the methods can be called

YoutubeEvent.PLAYER_ERROR

dispatched when an error occurs: when this event is fired, a next clip should be played (in example)

YoutubeEvent.PLAYER_STATE_CHANGE

dispatched when the player changes state

The error codes and player states are the same as for youtube as2.

IYoutube.getPlayerError()

returns the current error code, if any error occured for the current clip, or 0 if no error: error codes -> 100 – video not found, 101 and 150 – playback not allowed in users region or in chromeless player

IYoutube.getPlayerState()

returns the current state:
player states -> -1=Unstarted,0=Ended,1=Playing,2=Paused,3=Buffering,5=Video cued.

The first thing to do is to load ytPlayer.swf in a

object.
Youtube requires a developer key, in order to correctly pass the key load ytPlayer.swf with the apiKey=XXXXXX.. parameter
Example:

var apiKey : String = "XXXXXXXXXX";
var loader : Loader = new Loader();
...
..
loader.load(new URLRequest("ytPlayer.swf?apiKey="+apiKey));

When the loading completes, Event.COMPLETE event fired, add the loader to the stage’s display list (can be through a child of the stage).
You should have

var ytPlayer : IYoutube;

declared.
Set this variable to be the content property of the Loader object.
Example:

var ytPlayer : IYoutube;
....
ytPlayer = loader.content as IYoutube;

Now we can start listening for the events mentioned:

ytPlayer.addEventListener(YoutubeEvent.PLAYER_READY, onYTPlayerReady);
ytPlayer.addEventListener(YoutubeEvent.PLAYER_ERROR, onYTPlayerError);
ytPlayer.addEventListener(YoutubeEvent.PLAYER_STATE_CHANGE, onYTPlayerStateChange);

Now we must declare the listener functions.
Inside onYTPlayerReady we can write some initializing code, or you can go ahead and play some video right frome there.

function onYTPlayerReady(event : YoutubeEvent) : void {
      // maybe set the size
      ytPlayer.setSize(500, 400);
      // maybe set volume
      ytPlayer.setVolume(80);

      // maybe play a clip
      ytPlayer.loadClip("0_fPV13lKm4");
}

function onYTPlayerError(event : YoutubeEvent) : void {
       // maybe check the error code and do something based on it
      switch(ytPlayer.getPlayerError()) {
               case 100:
               case 101:
               case 150:
               default: // maybe play a next clip
      }
}

function onYTPlayerStateChange(event : YoutubeEvent) : void {
       // maybe get the player state and do something based on it
      switch(ytPlayer.getPlayerState()) {
            case -1: break; // Unstarted
            case 0: break; // Ended
            case 1: break; // Playing
            case 2: break; // Paused
            case 3: break; // Buffering
            case 5: break; // Video cued - when using cueVideo() method on ytPlayer
            default: // Unknown
     }
}

Of course you can handle play, pause.. and any other methods of the ytPlayer object,
just make sure you test that the player is loaded and ready
Example:

if(ytPlayer != null && ytPlayer.isPlayerReady())
{
        // call methods here
       ytPlayer.playVideo();
}

Below is a implementation of this wrapper in a “test harness” player.
The test player is written in flex, but absolutelly the same principles work in flash too. (except the mxml code)

The entire source code for the player can be downloaded here.
The code is commented out (only what’s related to the wrapper and youtube).

The wrapper files can be downloaded here.

To start playing a video, click one title on the right or copy and paste a youtube video id (or entire link) in the Custom youtube input text field and click Load.

You need javascript enabled!
DeliciousFacebookMySpaceStumbleUponDiggLinkedInRedditShare

admin Actionscript 3.0, FLEX, Youtube, Youtube Wrapper , , , , , ,

  1. May 25th, 2009 at 09:35 | #1

    Hi, You have a really cool component here!

    I was doing a test application with your component, and I ran through Error Code 150.
    Could you point me to some more info about that error?
    Thanks in advance.
    Regards

  2. May 25th, 2009 at 09:46 | #2

    Hi,
    You can find more about the error code here.
    The 150 error is the same as 101 error: the video is not allowed to be played in the user’s region (country) or is not allowed in chromeless player.

    Ovidiu

  3. May 28th, 2009 at 09:46 | #3

    Hi again! I’ve been working wonderfully with your component. It’s the best youtube wrapper around, and I tried most of them.
    I’m confronting with a little problem though.. I hope you can help me.
    I’m embedding the player in a Panel, and this panel is added to stage by PopUpManager.addPopUp() function.
    When the popup is added to stage for the first time, it works beautifully, and my Console shows:
    [SWF] C:\..\bin-debug\ytPlayer.swf – 8.004 bytes after decompression
    [SWF] C:\..\bin-debug\ytODLCWrapper.swf – 15.251 bytes after decompression
    (//waits some time here)
    [SWF] /swf/cl.swf – 7.720 bytes after decompression
    [SWF] /swf/apiplayer.swf – 164.192 bytes after decompression
    (//now [onYTReady] function is called)

    When I remove the popup, and add it to stage again, trying to play any other video, all functions are called accordingly, but it doesn’t finish loading the swfs, i think.
    It doesn’t call the [onYTReady] function. Console shows:
    [SWF] C:\..\bin-debug\ytPlayer.swf – 8.004 bytes after decompression
    [SWF] C:\..\bin-debug\ytODLCWrapper.swf – 15.251 bytes after decompression

    and stops… Player doesn’t show up. Do you have any idea about what I’m doing wrong? (I’m not calling any destroy() or so functions)
    Thanks a lot!
    Best regards

  4. May 28th, 2009 at 23:18 | #4

    Hi,

    Yes the problem is that the wrapper starts to initialize itself, when it is added to stage (added to a child’s display list that is on stage). Unfortunately, the initializing steps are done every time the wrapper is added to a display list. So the second time you add it, using addChild method of an DisplayObjectContainer object, the initializing process restarts, but this times it breaks everything.

    I will post soon a new version that takes this into consideration.
    Best regards,
    Ovidiu

  5. Nilesh
    June 3rd, 2009 at 09:58 | #5

    @admin
    Do you have any update on this particular issue ? has this been taken care in (0.7 version)wrapper ?

    Can’t stage be adjusted to probably unload that and reload again ?


    Nilesh

  6. June 3rd, 2009 at 10:07 | #6

    A new update that takes care of the problem will be uploaded by the end of this day because I want to test it thoroughly so that I don’t introduce new problems.
    You shall be notified when the new update is available for download.
    Regards,
    Ovidiu

  7. Nilesh
    June 3rd, 2009 at 10:27 | #7

    @admin
    Thanks Ovidiu !

  8. Scott
    June 3rd, 2009 at 20:15 | #8

    One odd behavior that I’ve noticed is that you cannot play 2 (or 3) instances of the same video until AFTER the video has fully loaded in the first instance. Once the video is fully loaded (100%) all 2 (or 3) instances will play at the same time … and allow you to scrub, etc.

    Ovidiu, do you know of a way to get all 3 to work at the same time … before 100% loaded?

  9. June 3rd, 2009 at 21:24 | #9

    No I haven’t noticed the problem until now. Indeed it’s something strange which i will have to work on it and see what’s causing it.
    However i’ve noticed that seeking (to whatever time in the movie) will cause the player to start playing.
    You can see that in the multiple instances sample page: Youtube AS3 Wrapper – Multiple instance sample
    Thanks for pointing that out.

  10. Scott
    June 3rd, 2009 at 22:06 | #10

    You are right … the seek seems to get things moving … so odd.

  11. June 4th, 2009 at 10:02 | #11

    Hi Scott.
    Did you try opening 2 pages of the youtube site and try playing the same video?
    It’s the same problem there too. You still have to seek to get the second one playing.
    So I’m guessing that it’s some kind of limitation per IP.
    Try opening this page 2 times: http://www.youtube.com/watch?v=bpBDOolcs9g&feature=popular

    Ovidiu

  12. June 4th, 2009 at 10:05 | #12

    Also,
    If the two pages are opened in different browsers, for instance the first one opened in FF and second in IE, they will both work. So it can’t be an IP limitation.

  13. Thomas
    August 20th, 2009 at 08:04 | #13

    Hello Ovidiu. I would be very happy if you would fix the “initialized when added to stage” issue. Can you please initialize without listening for this event, since it kind of put the YouTube player in a fixed box. I e.g. use drag-and-drop and want to be able to drop the player on another clip (and display list), but then the player breaks. Small fixes are much appreciated – maybe you could make a beta version, without through testing? Or even better relasing the source on Google Code an let the community do fixing and you do the developing? Thank you for any help.

  14. September 14th, 2009 at 08:38 | #14

    @Thomas
    what I did was to save the event in a variable. and then I am able to call the listener-activated function by passing the event variable.

  15. jaimeen
    October 15th, 2009 at 08:52 | #15

    hi, wonderful wrapper, to be honest the only one i could figure out how to use, so really simple, i am having one tiny problem, i hope u can help me out, do we have to keep the folder structure as it is, or can i change the package of the two classes given, coz in my project i need to organise the classes in a way that does not allow me to maintain the folder structure as it is, hope i make myself clear, help is appreciated. thanks

  16. October 19th, 2009 at 16:29 | #16

    Hi. I’m glad you find this useful. You can always copy the directory from classes to wherever you want and adjust the Classpath in your fla or flex project.
    Or you can use the swc file (not sure if is included in the latest download package though).
    Let me know how it is going.

  17. November 9th, 2009 at 18:23 | #17

    Hi, first of all, thank you for your work, it´s an excelent wrapper :)
    i´m having a problem but i could not realize if i´m doing something wrong. I´ve the wrapper in a secondary swf; my main swf is main.swf, when i click in a VIDEOS button, i load a new swf inside main.swf (videos.swf) and inside videos.swf, i load the ytPlayer.swf. The first time everything is working well, but when i go to another section of the site (i unload the videos.swf and load another one) and then i try to load again videos.swf, the ytPlayer.swf isn´t loading (the player.addEventListener(YoutubeEvent.PLAYER_READY, onYTPlayerReady) is not dispatched)…i´ve try with the destroy() and reload() methods but it´s not working for me. And also i´ve try unloading the swf with the new unloadAndStop() method of the Loader classs, but nothing happens. Do u know if i am doing something wrong or have u seen this problem before?

    thank you for your time :)

    Mariano

  18. November 9th, 2009 at 20:28 | #18

    hi, it´s me again :)

    i´m still testing what is going on with this problem. i remove all the instances and methods of this wrapper, and just load the ytPlayer…the first time, it´s loaded but when i unload and try to load it again, it does not appear despite the fact that the COMPLETE listener of the contentLoaderInfo is dispatched…¿?.

    I replace the ytPlayer.swf with another swf, and it´s working perfectly, no matter if i unload and load it again many times…

    i don´t really don´t know what´s the problem. :S

    thanks again! :)

  19. November 9th, 2009 at 22:26 | #19

    This is a problem of playing multiple videos in the same time on the same stage, which is taken care of in v0.8m of the wrapper. Please refer to the documentation in order to see how you can play multiple videos like that. Unloading and reloading the wrapper won’t work unfortunately.
    If it’s not too big of a trouble in refactoring your code, you may wish to use the new as3 api from youtube: youtube as3 lib
    Best

  1. March 30th, 2009 at 04:41 | #1
  2. April 1st, 2009 at 21:12 | #2
  3. June 2nd, 2009 at 05:26 | #3