Archive

Archive for the ‘Actionscript 3.0’ Category

Youtube AS3 Wrapper v0.7.1

April 21st, 2009

A new version of Youtube AS3 Wrapper is available: v0.7.1

This new version adds Adobe AIR support.

The new version is available for download Youtube AS3 Wrapper – Downloads

Also, a new test harness player sources have been added, which makes use of the new wrapper and it’s AIR capabillities.
You can download the sources for the new Test Harness Player at the same link above.
Enjoy!

Actionscript 3.0, Youtube, Youtube Wrapper , ,

AS3 – Object Oriented Programming – Part1

April 16th, 2009

We talked a lot about classes and objects in the introductory part, now let’s look how we can create a class.

In AS3, a class must be created in a separate .as file, with the name of the class being the name of the file.
Also, a class must be contained in a package. We’ll discuss in the next part more about packages.

To define a class in actionscript we have the keyword class.

To write our first class, named Apple, create a file named Apple.as, open it in a text editor and paste in the next code (make sure you edit with a text editor and not a word processor like MS Word):

package {
  public class Apple {
  }
}

There it our first class, however is quite empty; it has no functionality.
Notice that i’ve used the keyword package. That way I defined the package for the Apple class. But more on packages in the next part of this tutorial.
Also notice another keyword introduced: public. This is an access specifier.
An access specifier sets the visibility for a class, method, property or namespace.

A method is a function defined inside a class.
A property or member is a variable defined inside a class.
A namespace is like a package, controls the visibility of definitions, but it’s not directly related to classes, so it won’t be discussed in this tutorial.

In our case, the public specifier sets the class to be visible and accessible anywhere. Without specifying public, the class would be visible only inside the package, because the default access is internal.
A class can only be defined public or internal, however there are 2 other access specifiers: private and protected.
Private means that the property or method is only visible and accesible inside the class. About protected we’ll talk a bit later.

With this said, let’s add a method and a property to our class:

package {
  public class Apple {
    private var stones:uint = 4;

    public function Apple() {
    }
  }
}

Now our Apple class has a property of type uint, named stones, which is declared private (this means that only methods of the class Apple can access this property) and has a default value of 4.
It also has a method, declared public, named Apple. Notice the name of this method is exactly the name of the class. A method with the same name as its class is named constructor.
In actionscript 3.0 a constructor can only be declared public. Also a constructor cannot have a return type (cannot return a value).
It is named “constructor” because when an object is created this method will be called. So it is a good place to put here any initializing code.

With these being said we can construct our first object of the class Apple, but first some words about the import statement.
Before we can use our class, we must import it where we want to use it. For that, we have the “import” statement, so we can use it like this:

import Apple;

Ok. Now we’re ready.
Open the Flash IDE, create a new Flash Actionscript 3.0 File, save it to a name of your choice and copy the Apple.as file in the same directory as your .fla file.
On the timeline, select the first keyframe and open the Actions window (Windows->Actions or press F9), and write the next lines:

import Apple;
var myApple : Apple = new Apple();

That’s it! Your first object is created out of your first class! You can test your file now, but really there isn’t much to see…
Notice the new keyword: it is used to construct new objects.

So let’s add something so that we can see what’s going on.
Add a trace action inside our constructor.
Our class should look like this:

package {
  public class Apple {
    private var stones:uint = 4;

    public function Apple() {
      trace("A new apple is constructed!");
    }
  }
}

Now run again your movie and you should see “A new apple is constructed!” in the Output window. That’s because when we construct our object using the new statement, the constructor of our class is called, thus the trace method is called.
If you would construct more objects, you will see that the message is outputted once for every object.

Next, let’s say we would like to know how many stones has our apple object. But the stones property is private, which means we can’t access it from outside the class. So, to access it let’s add a new method, named “getStones”, that will return the number of stones, and make it public.

package {
  public class Apple {
    private var stones:uint = 4;

    public function Apple() {
      trace("A new apple is constructed!");
    }

    public function getStones() : uint {
      return this.stones;
    }
  }
}

Make note of this keyword. “this” refers to the “current object”.

Now we can call the new method on our object like this:

myApple.getStones()

In Flash, change the code with this one:

import Apple;
var myApple : Apple = new Apple();
trace("myApple has "+myApple.getStones()+" stones.");

When you run your movie you should see in the output 2 lines.

That’s about all on this first part of the tutorial.
In the next part we’ll discuss more about packages.

Actionscript 3.0, Object Oriented Programming , , , , , , ,

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.

Youtube, Youtube Wrapper , , , ,

Youtube AS3 Wrapper v0.7

March 29th, 2009

A new version of Youtube AS3 Wrapper is available: v0.7

This new version fixes the volume and mute methods thus making the use of destroyAndReload method obsolete. This means you no longer have to destroy and reload the player in Internet Explorer.

The new version is available for download Youtube AS3 Wrapper – Downloads

Also, the test harness player has been update to use the new wrapper. The code that’s not needed, due to deprecation of destroyAndReload method, is commented out.
You can download the sources for the new Test Harness Player at the same link above.
Enjoy!

Youtube, Youtube Wrapper , , ,

Youtube AS3 Wrapper – Documentation

March 27th, 2009

The IYoutube Interface

This actually represents the playground for Youtube AS3 Wrapper: all the methods needed to handle youtube videos are methods of this interface.

So let’s go through each of the methods.

EventDispatcher related:

function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void;
function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void;

Use addEventListener to listen to the events dispatched by IYoutube:
YoutubeEvent.PLAYER_READY: dispatched when the player is loaded and ready to receive method calls
YoutubeEvent.PlAYER_ERROR: dispatched when the player receives an error
Possible error codes: 100 – video not found; 101, 150 – video not available in user area or cannot be played in chromeless player
YoutubeEvent.PlAYER_STATE_CHANGE: dispatched when the player has changed state

Always check if the player is ready to receive function call (after a YoutubeEvent.PLAYER_READY event the player is ready) before calling any function (exception functions are those described above and: destroy(), reload() and destroyAndReload() which will be discussed later).
Use isPlayerReady() to check if the player is ready:

        /**
         * check to see if player is ready; always check if it's ready before calling any method
         * @return Boolean true if player is ready, false otherwise
         */

        function isPlayerReady():Boolean;

Loading videos methods:

                /**
         * loads a video
         * @param id String youtube id or youtube url
         * @param startSeconds Number seconds from where to start the video
         */

        function loadVideo(id:String, startSeconds:Number = 0):void;
        /**
         * cue a video
         * @param id String youtube id or youtube url
         * @param startSeconds Number seconds from where to start the video
         */

        function cueVideo(id:String, startSeconds:Number = 0):void;

Use loadVideo when you want the playback to start as soon as the video is loaded. If loadVideo is used, there’s no need to call playVideo method, as playback starts automatically.
Use cueVideo when you don’t want the playback to start automatically. When this method is used, the player sends a Cue Video state (5) when the video is ready to play. Then playVideo method can be called.
On both methods, information about the video is available only after the playback has started ( a Playing state is entered (1)).

Video playback control:

        /**
         * Play or resume a paused video
         */

        function playVideo():void;
        /**
         * Pauses a playing video
         */

        function pauseVideo():void;
        /**
         * Stops the current video; after this method is called, the clip cannot be played anymore; the video must be loaded again
         */

        function stopVideo():void;

If stopVideo method is called, the clip that was playing cannot be played again. In order to do that, that video must be reloaded, using one of the loading methods described above.

To clear the remnant picture of a stopped video (stopped by using stopVideo()):

        /**
         * Clears a remnant video after stopVideo() was called
         */

        function clearVideo():void;
        /**
         * A merge between stopVideo() and clearVideo(); should be used instead of calling stopVideo() then clearVideo()
         */

        function stopAndClearVideo() : void;

Use clearVideo to clear a video from display. However, instead of calling stopVideo() and then clearVideo(), call only stopAndClearVideo(). This is a better way because it uses only one LocalConnection call, instead of 2 (1 for stopVideo and 1 for clearVideo).

To resize the video:

/**
         * set the player size
         * @param width Number
         * @param height Number
         */

        function setSize(width:Number, height:Number):void;

Always use this method instead of setting width and height parameters on IYoutube object directly. By using this method, the youtube logo will keep it’s current size, otherwise scaling will occur both on the video picture and the logo (which is unwanted).

Methods to check if the player has any errors. However remember that when an error occurs, a YoutubeEvent.PLAYER_ERROR event is dispatched.

        /**
         * check to see if player has any error; if true, getPlayerError() returns the current error
         * @return Boolean true if has error false otherwise
         */

        function playerHasError():Boolean;
        /**
         * @return int the current error if exists, 0 if no error exists
         */

        function getPlayerError():int;

After an YoutubeEvent.PLAYER_ERROR event is dispatched, getPlayerError() returns the current error. Also playerHasError will return true.
The error is cleared when a new video is loaded or cued, or the current video is stopped or cleared.

Audio control functions:

        /**
         * Mute the video
         */

        function mute():void;
        /**
         * Unmute the video
         */

        function unmute():void;
        /**
         * @return Boolean true if the video is muted false otherwise
         */

        function isMute():Boolean;
        /**
         * Set the volume of the video
         * @param volume Number the volume to be set [0-100]
         */

        function setVolume(volume:Number):void;
        /**
         * Return the current volume of the video
         * @return Number volume [0-100]
         */

        function getVolume():Number;

The volume is a Number between 0 and 100.

Details about loading:

        /**
         * Returns the current bytes loaded
         * @return Number the current bytes loaded
         */

        function getVideoBytesLoaded():Number;
        /**
         * Return the total bytes of the video, or a negative number until the total bytes of the video is known
         * @return Number the total video bytes
         */

        function getVideoBytesTotal():Number;

Notice that getVideoBytesTotal will return a negative Number until the details about the current video are loaded (which happens when a Playing (1) state is entered). So you should always check to see if the returned Number is greater than 0 before using it in calculations.
Also getVideoBytesLoaded returns 0 until any bytes are downloaded.

Details about playback and video length in seconds:

        /**
         * Returns the current time where the playback is
         * @return Number
         */

        function getCurrentTime():Number;
        /**
         * Return the total time (duration) of the current clip if known, a negative Number until the duration is loaded
         * @return Number
         */

        function getDuration():Number;

Both values are in seconds. Notice that getDuration will return a negative Number until the duration of the clip is found (after a Playing (1) state is entered). getCurrentTime will return 0 until the playback head changes. You should always check to see if getDuration returns a Number greater than 0 before using it.

Method to change the playhead:

        /**
         * Seek the video to a certain position in time
         * @param seconds Number the second the seek to
         * @param allowSeekAhead Boolean whether to seek past the loaded bytes
         */

        function seekTo(seconds:Number, allowSeekAhead:Boolean = false):void;

Method to determine the current playing state the player is in. Should be used when a YoutubeEvent.PLAYER_STATE_CHANGE event occurs:

        /**
         * Returns the players state
         * @return int returns the current player stat
         */

        function getPlayerState():int;

This method returns the current state that player has: -1=Video is Unstarted, 0=Video has Ended, 1=Video is Playing, 2=Video is Paused, 3=Buffering Video, 5=Video is Cued (received when cueVideo method is used to load a video; after this event is received, playVideo method can be used to start playback).
Use this method to know the current state of the player.

Link and embed code of current video:

        /**
         * Return the url of the video
         * @return String
         */

        function getVideoUrl():String;
        /**
         * Return the Video embed code
         * @return String
         */

        function getVideoEmbedCode():String;

Note that the url and the embed code are those related to Youtube site, and not related to the current player!

The next method, recently introduced by youtube api, returns the bytes where the video has started playing (if appropriate):

/**
         * Return the current bytes the video has started from
         * @return uint video start bytes
         */

        function getVideoStartBytes() : uint;

And saved the best for the last. This methods help destroying and reloading the player without the need to reload the entire wrapper.

        /**
         * Destroy the player; no other action, other than reload() can occur on the player after this call
         */

        function destroy() : void;
        /**
         * Reloads the player; YoutubeEvent.PLAYER_READY event will be dispatched when the player is loaded and ready to receive action
         */

        function reload() : void;
        /**
         * A merge of destroy() and reload(); it should be used instead of calling destroy() and then reload()
         */

        function destroyAndReload() : void;

As you can see there are these three methods: destroy, reload and destroyAndReload.
If you need to call destroy, then reload, use destroyAndReload instead.
You might be wondering why would you ever need to destroy and reload the player, and you’re right. In most of the cases you won’t need to destroy and reload it. However in Internet Explorer, after a few, or after every clip, has played, on another clip volume and mute will not work anymore. So when this happens, you can call destroyAndReload(), wait for Youtube.PLAYER_READY event, and then you’re good to play another clip, with volume and mute, and everything else supported. Note that this only happens in Internet Explorer, so before destroying and reloading the player check what browser is the embedding the player.
This method is used in the test harness player v1.0, so you can download the sources of the test harness player v1.0 (v1.1 uses the new Youtube AS3 Wrapper) and look through the code for more details on this is use.

The YoutubeEvent class

The only important here are these 3 constants:

        public static const PLAYER_READY:String        = "playerReady";
        public static const PLAYER_ERROR:String        = "playerError";
        public static const PLAYER_STATE_CHANGE:String = "playerStateChange";

Use these constants when you add event listeners to the IYoutube object.
Example:

var ytPlayer : IYoutube;
....
ytPlayer.addEventListener(YoutubeEvent.PLAYER_READY, onYTPlayerReady);

function onYTPlayerReady(event : YoutubeEvent) : void {
          // code here
}

Youtube, Youtube Wrapper , , , ,

Youtube AS3 Wrapper – Multiple instances sample

March 27th, 2009

The test video player is a flex application using Youtube AS3 Wrapper.
You can download the latest files for both the wrapper and the test player HERE.

This player demonstrates the latest wrapper’s capabilities, that to play multiple videos in the same time on the same stage.

Alternative content

Get Adobe Flash player


To start playing a video, click one title on the right playlist or copy and paste a youtube video id (or entire link) in the Custom youtube input text field and click Load.
Here is one instance of the test harness:

You need javascript enabled!

Here is another instance of the harness player:

You need javascript enabled!

And yet another one if you wish:

You need javascript enabled!

Youtube, Youtube 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!

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