Skip to content


AS3 YouTube API

This is my simple youTube Player class using their API.
YouTube API for AS3
Thanks to Art Douglas for the video playlist


youTube.as

package com.drpunchlogic
{
	/*	

		YOU MIGHT WANT TO READ THIS FIRST:

http://code.google.com/apis/youtube/flash_api_reference.html

http://code.google.com/apis/youtube/flash_api_reference.html#GettingStarted

http://code.google.com/apis/youtube/flash_api_reference.html#Adding_event_listener

		good to know:

http://code.google.com/apis/youtube/articles/tubeloc.html

		this is based off of the example located at: http://code.google.com/apis/youtube/flash_api_reference.html#loadVideoById

	*/

/*
-------------------------------------------------
	INCLUDE STUFF
-------------------------------------------------
*/
	// security
	import flash.system.Security;
    import flash.system.SecurityPanel;
	import flash.system.LoaderContext;

	// display objects
	import flash.display.MovieClip;
	import flash.display.Loader;
	import flash.geom.Rectangle;

	// standard events
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.events.EventDispatcher;
	import flash.events.KeyboardEvent;

	// error checking
	import flash.events.ErrorEvent;
	import flash.events.IOErrorEvent;
	import flash.errors.IOError;
	import flash.errors.MemoryError;

	// networking
	import flash.net.URLRequest;
	import flash.net.navigateToURL;

	// TweenMax
	import com.greensock.*;
	import com.greensock.easing.*;

	// Custom
	// ---- OOPS (traces out to text box)
	import com.drpunchlogic.oops;
	// ---- XML
	import com.drpunchlogic.youTubeXML;
	// ---- GALLERY
	import com.drpunchlogic.youTubeGallery;

	// -----------------------

	public class youTube extends MovieClip
	{
// START --------------------------

/*
-------------------------------------------------
	SHARED VARIABLES
-------------------------------------------------
*/
		private var loader:Loader;
		private var _youTube:Object; // This will hold the API player instance once it is initialized.

		public var _nowPlaying:uint = 0; // The current video uint

		//public var _file:String = "http://www.youtube.com/v/UA3TLWplbHs"; // the file we want to play
		public var _file:Array = new Array(); // the file we want to play in an array for the XML

		// oops
		private var _log:String = '';

		// player controls
		public var _ctrl:youTubeBtn;
		private var _isFirstPlay:Boolean = true;

		// OOPS
		public var _oops:oops; // TRACE CLASS
		public var _say:Function;

		// XML
		public var _X:youTubeXML; // XML CLASS

		// GALLERY
		public var _G:youTubeGallery; // GALLERY CLASS

/*
-------------------------------------------------
	YOU TUBE!
-------------------------------------------------
*/
		public function youTube() : void
		{
			_oops = new oops();
			_oops.x = 260;
			addChild( _oops );
			_say = _oops.say;

			_say( "\n\n[ testTube! ]" );

			// first thing I am going to do is add security
			sercureDom();

			// after it is secure, INIT the player
			addEventListener( "SEC", init );

		} 

/*
-------------------------------------------------
	SECURE DOMAINS
-------------------------------------------------
*/
		private function sercureDom() : void
		{
			_say( "[ sercureDom ]" );

			/*
			The player SWF file on www.youtube.com needs to communicate with your host SWF file.
			Your code must call Security.allowDomain() to allow this communication.
			*/

			Security.allowDomain("www.youtube.com");

			// ok, let's init
			//dispatchEvent( new Event( "SEC" ) );
			init();
		}

/*
-------------------------------------------------
	INIT
-------------------------------------------------
*/
		public function init( ) : void
		{
			_say( "[ init ]" );

			// we don't need the event listener any longer
			removeEventListener( "SEC", init );

			// add XML
			addEventListener( "XMLFIN" , XMLready ); // <-- Start Movie After XML is finished
			// parse XML
			addXML();

			// normally yes, but today we want the XML to tell us when it is ready.
			/*
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
			loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
			*/

		}
/*
-------------------------------------------------
	XML READY
-------------------------------------------------
*/
		public function XMLready( e:Event ) : void
		{
			_say( "[ XML ready ]\n" );

			// kill listener we don't need
			removeEventListener( "XMLFIN" , XMLready ); 

			// create file array
			for( var i:uint = 0; i < _X._itemArr.length; i++ )
			{
				_file.push( _X._itemArr[i].video );
			}

			// add a gallery
			addGallery(); // not needed for the player

			// start loading movies
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
			loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
		}
/*
-------------------------------------------------
	LOADER
-------------------------------------------------
*/
		private function onLoaderInit(event:Event):void {
			addChild(loader);
			loader.content.addEventListener("onReady", onPlayerReady);
			loader.content.addEventListener("onError", onPlayerError);
			loader.content.addEventListener("onStateChange", onPlayerStateChange);
			loader.content.addEventListener("onPlaybackQualityChange", onVideoPlaybackQualityChange);
		}

/*
-------------------------------------------------
	READY?
-------------------------------------------------
*/
		private function onPlayerReady(e:Event):void {
			// Event.data contains the event parameter, which is the player API ID
			_say("\t{ ready: " + Object(e).data + " }" );

			// Once this event has been dispatched by the player, we can use
			// cueVideoById, loadVideoById, cueVideoByUrl and loadVideoByUrl
			// to load a particular YouTube video.
			_youTube = loader.content;

			// Set appropriate player dimensions for your application
			_youTube.setSize(400, 300);
			// We are playing a movie smaller then 640 so let's not load some big format we won't use:
			_youTube.setPlaybackQuality( "small" );

			// don't allow multiple loads of the video player and controls
			if( _isFirstPlay )
			{
				// lets add the controls
				ctrls();

				// play the first video
				newVideo( _nowPlaying );

				_isFirstPlay = false;
			}
		}
/*
-------------------------------------------------
	ERROR, WTF?
-------------------------------------------------
*/
		private function onPlayerError(e:Event):void {
			// Event.data contains the event parameter, which is the error code
			_say("\t{ error: " +  Object(e).data + " }",1 );
		}
/*
-------------------------------------------------
	MARK CHANGES
-------------------------------------------------
*/
		private function onPlayerStateChange(e:Event):void {
			// Event.data contains the event parameter, which is the new _youTube state
			_say("\t{ state: " + Object(e).data + " }" );
			// send new event to controller
			_ctrl.stateChange( Object(e).data );

			// activate gallery buttons
			if( Object(e).data == 1 ) _G.btnOnOff( true );
			//if( Object(e).data == 5 ) _G.btnOnOff( false );

		}

		private function onVideoPlaybackQualityChange(e:Event):void {
			// Event.data contains the event parameter, which is the new video quality
			_say("\t{ quality: " + Object(e).data + " }" );
		}
/*
-------------------------------------------------
	PLAY THE VIDEO
-------------------------------------------------
*/
		public function newVideo( i:uint ) : void
		{
			_say("\t{ file: " + _file[i] + " }",3 );
			// let's load a movie to play
			_youTube.loadVideoByUrl( _file[i] , 3);

			_nowPlaying = i;
		}
/*
	This next little area is to prep the
	thumbnail gallery section
*/

/*
-------------------------------------------------
	NEXT VIDEO
-------------------------------------------------
*/
	public function prepFile() : void
	{
		// let's get a movie ready to play
		_youTube.cueVideoByUrl( _file[ _nowPlaying ] , 0);

	}
/*
	That is basically everything we need,
	So, I'm going to add the controls now.
*/
/*
-------------------------------------------------
	CONTROLS
-------------------------------------------------
*/
		public function ctrls() : void
		{

			_say( "[ ctrl ]" );

			_ctrl = new youTubeBtn( );
			_ctrl.x = _ctrl.width / 2;
			_ctrl.y = 300;
			_ctrl.name = "ctrl";

			addChild( _ctrl );

			_ctrl.init( _youTube, this );

			// this isn't part of controlls, I just want to show/hide oops
			_ctrl.shbtn.addEventListener( MouseEvent.CLICK, showhideOOPS );

		} 

/*
	Let's add a gallery to the video player
*/
/*
-------------------------------------------------
	ADD XML
-------------------------------------------------
*/
	private function addXML() : void
	{
		// add the XML from the feed
		var feed:String = "http://gdata.youtube.com/feeds/api/playlists/";
		// 43697368FC276DB2 <-- mine
		// DF668B5F247C0CE7 <-- another
		feed += "D7FE57402F99A513"; //<--- playlist id
		feed += "?";
		feed += "&start-index=1";
		//feed += "&max-results=12";
		feed += "&v=2";

		_X = new youTubeXML( this, feed );

	}
/*
-------------------------------------------------
	ADD GALLERY
-------------------------------------------------
*/
	private function addGallery() : void
	{
		// add the gallery thumbnails
		_G = new youTubeGallery( this, _X._itemArr );
		_G.x = 0;
		_G.y = 330;
		addChild( _G );
	}

/*
-------------------------------------------------
	SHOW/HIDE OOPS
-------------------------------------------------
*/
		private function showhideOOPS( e:Event ) : void
		{
			//( _oops.visible ) ? _oops.visible = false : _oops.visible = true;
			( _oops.x == 0 ) ? [ TweenLite.to(_oops, 1, {x:260}) , TweenLite.to(_G, 1, {x:0}) ] : [ TweenLite.to(_oops, 1, {x:0}) ,TweenLite.to(_G, 1, {x:-404}) ];
		}
// END --------------------
	}
}

[ download coming soon ]

Posted in ActionScript. Tagged with , , , , .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.

Powered by WP Hashcash