Archive

Posts Tagged ‘FLEX’

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

MovieMaterial with UIComponent

March 15th, 2009

Papervision3D with FLEX

 

In the next few lines of this post I’ll show how to use MovieMaterial class in PV3D with UIComponents. At a first glance it might look quite challenging and lots of frustration might occur, I had it too until I found this small resolution.

Basically, all that’s needed is that the component that’s passed in as the movieAsset parameter for the MovieMaterial constructor must be on the stage (that is, must be in the display list of a container and displaying).

The code that’s following is using Papervision3D  2.0.883 swc which can be found http://papervision3d.googlecode.com/files/Papervision3D_2.0.883.swc. The flex app is an Air application, so if if you don’t have Air installed, you can just simply change from WindowedApplication to Application

test.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:WindowedApplication applicationComplete=”initPV3D();” xmlns:mx=”http://www.adobe.com/2006/mxml”
layout=”absolute” verticalScrollPolicy=”off” horizontalScrollPolicy=”off“>
<mx:Script>
<![CDATA[
import org.papervision3d.objects.primitives.Plane;
import org.papervision3d.materials.MovieMaterial;
import org.papervision3d.cameras.Camera3D;
import org.papervision3d.scenes.Scene3D;
import org.papervision3d.view.Viewport3D;
import org.papervision3d.render.BasicRenderEngine;

private var scene:Scene3D;
private var camera:Camera3D;
private var material:MovieMaterial;
private var plane:Plane;
private var render : BasicRenderEngine;
private var viewPort : Viewport3D;

private function initPV3D():void

{
// create an instance of our component
// note that the component can be already present, created and displaying
// there's no need to be created now
var testComp1 : testComp = new testComp();

// set it's position to be out of the display area (we canno make it
// invisible nor transparent, as any visual changes would show in 3D)
// if you set the layout other than "absolute" then this might not work
testComp1.x = -1000;

// add it to the display list
this.addChild(testComp1);

// create the scene
scene = new Scene3D();

// create the camera
camera = new Camera3D();

// create the renderer

render = new BasicRenderEngine();

// create the viewport
viewPort = new Viewport3D();

// set the viewport to be interactive so that our UIComponent in 3D is interactive
viewPort.interactive = true;

// add the viewport to the display list
this.rawChildren.addChild(viewPort);

// create our movie material: we make it transparent and <b>animated</b>
// (if it's not animated, we won't see responsiveness on mouse or keyboard
// action nor any changes in display)
material = new MovieMaterial(testComp1, true, true);

// set it to be interactive
material.interactive = true;

// let's set it to be double sided
material.doubleSided = true;

// create the plane that will hold our component
plane = new Plane(material,900,900,5,5);

// rotate the plane a bit to appear 3D
plane.rotationY = 30;

// add the plane to the scene's display list
scene.addChild(plane);

// listen for the ENTER_FRAME event so that you can render our scene
addEventListener(Event.ENTER_FRAME, enterFrameEvent);
}

private function enterFrameEvent(event:Event):void
{
render.renderScene(scene, camera, viewPort);
}
]]>
</mx:Script>
</mx:WindowedApplication>

testComp.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Canvas xmlns:mx=”http://www.adobe.com/2006/mxml”
    width=”250” height=”250” backgroundColor=”#FFEA00“>

    <mx:Button label=”Button” width=”80” x=”85” y=”33” click=”youClicked(‘button’);”/>
    <mx:HSlider x=”10” y=”78” width=”230” change=”youClicked(’slider’);”/>
    <mx:CheckBox x=”10” y=”109” label=”Checkbox” change=”youClicked(‘checkbox’);”/>
    <mx:RadioButton x=”10” y=”155” label=”Radio” change=”youClicked(‘radioButton’);”/>
    <mx:Script>
    <![CDATA[
    private function youClicked(text : String) : void
    {
        trace("youClicked: "+text);
    }
    ]]>
    </mx:Script>
</mx:Canvas>

On test.mxml horizontalScrollPolicy and verticalScrollPolicy are set to “off” because when we move off stage our component scrollBars will appear, and since we want our component to not show, we don’t want to show scrollbars.
however you mai leave them on when you need them.

Actionscript 3.0, Air, FLEX, Papervision3D , , , , , , ,