Archive

Archive for the ‘Youtube’ Category

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

Youtube AS3 Wrapper – Downloads

March 26th, 2009

Here you can download the files

Note: The latest wrapper available for download is at the bottom of this page!

DOWNLOAD WRAPPER v0.6

DOWNLOAD TEST HARNESS SOURCES

EDIT March 29, 2009 @ 3:17

ADDED NEW v0.7 Youtube AS3 Wrapper

DOWNLOAD WRAPPER v0.7

DOWNLOAD TEST HARNESS SOURCES v1.1

EDIT April 21, 2009 @ 23:22

ADDED NEW v0.7.1 Youtube AS3 Wrapper

DOWNLOAD WRAPPER v0.7.1

DOWNLOAD TEST HARNESS – AIR SOURCES v1.0

EDIT June 03, 2009 @ 18:58

ADDED NEW v0.7.2 Youtube AS3 Wrapper

DOWNLOAD WRAPPER v0.7.2

EDIT July 12, 2009 @ 22:48

ADDED NEW v0.8.0m Youtube AS3 Wrapper

DOWNLOAD WRAPPER v0.8.0m

DOWNLOAD Youtube Test Player – Flash sources v1.0

Youtube, Youtube Wrapper , , , , , ,