Create a YouTube Player for Android using Flash Builder 4.5
In this tutorial I will show you how to use the YouTube ActionScript 3.0 Player API to create a chromeless video player for Android devices using Flash Builder 4.5 and AIR.
Furthermore we’ll also see how to create a Flex View-Based application, how to pass data between views and how to customize the ActionBar icons, all new interesting features of the mobile development process available from Flex 4.5.
Software Requirements: Flash Builder 4.5
Hardware: Android 2.2+ with Adobe Air support
Watch the video with the result:
CREATE A FLEX MOBILE PROJECT
Open Flash Builder 4.5 and create a new Flex Mobile Project
Define the Project’s Name and its location. Be sure to use the Flex SDK 4.5 version.

Click the Next button and select the View-Based Application template.
This template simply the process to create a mobile application with multiple views.
Click on the Finish button.

Flash Builder creates a new project folder that should contains two mxml files:
1) the main application file : Player.mxml
2) The first default view: PlayerHomeView.mxml
The project folder contains the xml descriptor file too, used in every Air for Android application to set a lot of application properties and permissions.

NOTE: I have renamed the PlayerHomeView file in HomeView (I didn’t like the original name ; )
Naturally you can avoid to do this.
THE MAIN APPLICATION FILE
The Main MXML file contains following code:
<?xml version="1.0" encoding="utf-8"?> <s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" firstView="views.HomeView" > </s:ViewNavigatorApplication>
The firstView property allow you to set the first View (in other words an mxml component) that will be automatically loaded when the application starts.
Set this property to views.HomeView.
CREATE THE DEFAULT VIEW: HomeView.mxml
The default view, HomeView, is automatically loaded when the application starts and it will simply contains two buttons to load two different YouTube videos.
When this view is created it is almost empty but naturally you can add your own logic, as following:
<?xml version="1.0" encoding="utf-8"?> <s:View xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" title="AIR for Android YouTube Player"> <fx:Script> <![CDATA[ /** * Play a video */ protected function playVideo(id:String):void { // Open the YouTube Player view passing the video id navigator.pushView(views.YouTubePlayer, id); } ]]> </fx:Script> <s:layout> <s:VerticalLayout horizontalAlign="center" verticalAlign="middle" /> </s:layout> <s:Button label="View Video 1" click="playVideo('abV2pNH2TyI')" /> <s:Button label="View Video 2" click="playVideo('9CogpacFjRU')" /> </s:View>
The output of this view:

When users click one of these buttons, a new view (in other words a new page) is opened using the pushView method. In addition to the view you open(views.YouTubePlayer), this method allows you to pass a parameter, so we’ll also pass the videoID to play.
CREATE THE YOUTUBE PLAYER: YouTubePlayer.mxml
In this view we’ll create the YouTube chromeless video player .
First of all create a new MXML component into the views folder (use right-click mouse button on views folder):

Set the component name to YouTubePlayer and the “Based On:” property to spark.components.View.
This step will generate a new mxml file called YouTubePlayer.mxml into your views folder.

Following the default source code of YouTubePlayer.mxml generated by Flash Builder:
<?xml version="1.0" encoding="utf-8"?> <s:View xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" title="YouTubePlayer"> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> </s:View>
Now, add the listeners for the viewActivate and viewDeactivate events.
These events are automatically fired when a view is opened (activated) or closed (deactivated).
<?xml version="1.0" encoding="utf-8"?> <s:View xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" title="Player" viewActivate="init()" viewDeactivate="backToHome()">
The init() method will start to load the youtube player.
The backToHome() method is called every time the user exits from the current view (and we’ll see later how to do it)
CREATE THE YOUTUBE PLAYER IN AS3
Now add following ActionScript 3 code to the YouTubePlayer view.
The source code is full-commented and you should not have problems to understand it.
It could be seem complex but I have simply followed the official ActionScript 3.0 Library for YouTube Data API guidelines, modifying the official sample using an SWFLoader to properly work in Flex 4.0.
I also added a dispose() method helping garbage collector to clean the memory and I have also added other useful methods to play and pause the video and demonstrate the AS3 YouTube API usage.
Furthermore, in the onPlayerReady event handler we use the data property to get the video id that we have previously passed from the HomeView.
<?xml version="1.0" encoding="utf-8"?> <s:View xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" title="Player" viewActivate="init()" viewDeactivate="backToHome()"> <fx:Script> <![CDATA[ import mx.controls.SWFLoader; import mx.core.FlexGlobals; protected var loader:Loader; protected var player:Object; private var swfLoader:SWFLoader; /** * Init */ public function init():void { // Prevents the system from dropping into an idle mode. NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE; // Load a chromeless YouTubePlayer player // More info: http://code.google.com/apis/youtube/flash_api_reference.html#GettingStarted loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit); loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3")); } /** * Player init event handler */ protected function onLoaderInit(event:Event):void { // Set the YouTube Player listeners // More info: http://code.google.com/apis/youtube/flash_api_reference.html#Events loader.content.addEventListener("onReady", onPlayerReady); loader.content.addEventListener("onError", onPlayerError); loader.content.addEventListener("onStateChange", onPlayerStateChange); } /** * On Player Ready * This event is fired when the player is loaded and initialized, meaning it is ready to receive API calls. */ protected function onPlayerReady(event:Event):void { player = loader.content; // Set the Player size player.setSize(this.stage.stageWidth, this.stage.stageHeight - FlexGlobals.topLevelApplication.actionBar.height ); // Display the YouTubePlayer into an SWFLoader swfLoader = new SWFLoader(); swfLoader.autoLoad = true; swfLoader.setStyle("backgroundColor", 0x333333) swfLoader.scaleContent = true; swfLoader.maintainAspectRatio = true; addElement(swfLoader) swfLoader.load(player); // Play the Video // The property 'data' contains the video ID passed // from the HomeView (i.e. "LDfM5c0ZKOw") playVideo(data as String); } /** * Video Player Stage Change * This event is fired whenever the player's state changes. * Possible values are unstarted (-1), ended (0), playing (1), * paused (2), buffering (3), video cued (5). * When the SWF is first loaded it will broadcast an unstarted (-1) event. * When the video is cued and ready to play it will broadcast a video cued event (5). */ protected function onPlayerStateChange(event:Event):void { trace("Player state changed:", Object(event).data); switch (Object(event).data) { // STOP case -1: // do nothing break; // end case 0: // do nothing break; // play case 1: // do nothing break; // PAUSED case 2: // do nothing break; // BUFFERING case 3: // do nothing break; } } /** * Video Player Error event handler * This event is fired when an error in the player occurs. */ protected function onPlayerError(event:Event):void { trace("Player error:", Object(event).data); } /** * Play Video * @param videoID The YouTube video ID to play */ public function playVideo(videoID:String) : void { // Loads the specified video's thumbnail // and prepares the player to play the video player.cueVideoById(videoID); // You can also use: // loadVideoById // cueVideoByUrl // More info: // http://code.google.com/apis/youtube/flash_api_reference.html#Functions } /** * Dispose * Help garbage collector to remove everything from memory */ public function dispose():void { loader.contentLoaderInfo.removeEventListener(Event.INIT, onLoaderInit); loader.content.removeEventListener("onReady", onPlayerReady); loader.content.removeEventListener("onError", onPlayerError); loader.content.removeEventListener("onStateChange", onPlayerStateChange); try { player.stopVideo(); // More info: http://code.google.com/apis/youtube/flash_api_reference.html#SpecialFunctions player.destroy(); } catch (e:Error) { trace("error")} removeElement(swfLoader) swfLoader = null; player = null; loader.unload(); loader = null; } /** * Back To Home */ private function backToHome():void { dispose(); // Enable the system to dropping into an idle mode. NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.NORMAL; } ]]> </fx:Script> </s:View>
ACTION BAR BUTTONS
Just after the View declaration of the YouTubePlayer view, add the following MXML code:
<?xml version="1.0" encoding="utf-8"?> <s:View xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" title="Player" viewActivate="init()" viewDeactivate="backToHome()"> <!--BACK TO HOME ICON: ACTIONBAR/LEFT SIDE--> <s:navigationContent > <s:Button icon="@Embed(source='assets/buttons/Back.png')" click="navigator.popView()"/> </s:navigationContent> <!--VIDEO PLAYER ICON: ACTIONBAR/RIGHT SIDE (Play, Pause)--> <s:actionContent > <s:Button icon="@Embed(source='assets/buttons/Play.png')" click="player.playVideo();"/> <s:Button icon="@Embed(source='assets/buttons/Pause.png')" click="player.pauseVideo();"/> </s:actionContent> <fx:Script> <![CDATA[ [....]
Inside the navigationContent tag we specify the Back button - on the left side of the action bar - useful to come back to the previous view (in this case it will be always the HomeView).
When user comes back to the previous View the deactivate event is automatically fired.
Instead, the actionContent property allows us to specify the icons on the right side of the ActionBar, used to play and pause the current video.
Check the YouTube AS3 Reference for more details about these features.
THE XML DESCRIPTOR FILE
Every AIR for Android application, created in both, Flex and Flash, uses an xml descriptor to set a lot of application properties and permission.
You don’t need to change anything but in this sample I have modified two stuff:
1) I have enabled the fullscreen
<fullScreen>true</fullScreen>
2) and I have enabled following permissions too, necessary to use the SystemIdleMode.KEEP_AWAKE property.
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/> <uses-permission android:name="android.permission.WAKE_LOCK"/>

That’s all. You can now play YouTube videos on your desktop and on your Android 2.2+ device.
TEST THE APPLICATION
To test the script you can use the Run -> Run Configuration menu

and select “on desktop” if you want to test it on your computer, or “on Device” to upload it on your connected Android device.

The project structure should look like this:

Soon I will write a tutorial to show you how to get videos from YouTube playlists, YouTube channels and how to get info about played videos. So check my blog ; )
RELATED LINKS
Flash Developer Planet - Free App for Android










This tutorial works very well. Thank you.
Questions:
1. Can you embed videos on the project?
2. How do you play them?
3. What is the max .apk size android can accommodate?
4. What if you have, say 500MB of videos that you want to
add to the app, how is this implemented?
Thank you in advanced. Can’t wait to see more videos from
you.
The tutorial is great…it’s really smooth on a Galaxy S. Is there a way to play videos that aren’t on youtube or does something like that need a completely different approach?
@RomV: to play embed videos you can use the same tecniques you use for a web application. You can use AS3, NetStream and netConnection classes, and so on… or you may also use the FLVPlayBack component(but it could have some performance issues… i never tried it).
If I remember, the max apk size was 50Mb. Now it should be 100mb but I’m not really sure about it.
If you have 500mb of videos I think you should think to load them externally avoid to embedding them : )
@Hugo: thanx… i’m happy it works well on GalaxyS.
As I wrote to RomV, to play other videos (FLV, mp4…) you can use for example the progressive download technique or Flash Media Server, just like you do (more or less) in a web flash application.
Great tutorial. Thanks !
I have on question though.
How do you manage the player when the mobile is rotated ?
Currently when i rotate the device the player isn’t resized.
I’ve added a VGroup to my mobile screen and added the swfloader to it but i didn’t work
Do you have an idea on how to do that ?
Cheers
I have tried this solution but it didn’t work for me too.
The only way I found was managing the device rotation (with OrientationEvents, accellerometer or other ways) and force the youtube player to get new dimensions using following sintax:
player.setSize(new_stage_width, new_stage_height)
HOnestly I don’t remember if it already works without any modification or if I have destroyed and re-created the player after every orientation change, saving the player position (time) and using the seek method to start playing from the previous position.
I should check but let’me know if these ideas can help you : )
@Fabio
I figured out an orientation fix based on a post i’d seen from Igor Costa Hacking Google Maps…Flex 4.5/Air Mobile.
I found the post searching for “stagewebview” (which i would not recommend using btw, its clunky and has the dreaded iframe flash of unstyled content “FOUC” - if you know how to stop this white flash pls share here!).
Now the reason i tell you all this is because when i used this fix with stagewebview framerate dropped quite badly when the rotation occured, i haven’t checked the framerate (stats) with your youtube example but it works good so far and i think i may have implemented it wrong in my seperate test (trying to push flex hard at the time)…nevertheless enjoy!
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
if (player) {
var point:Point = localToGlobal(new Point()); player.setSize(stage.stageWidth,stage.stageHeight - FlexGlobals.topLevelApplication.actionBar.height);
}
}
And Fabio keep these good examples flowing my friend and ty for share.
Leave your response!
Archives
Categories
Blogs
3D ActionScript Adobe AIR AIR for Android android Arduino Binding burrito hero 4.5 TabbedMobileApplication Chat Chrome Cocomo code optimization components custom/generic components custom components DataList developer central Emitter FLARToolkit Flash Flash Builder Flex HTTPService illustrator Infrared Interactions itemRenderer Joystick Loader mobile Papervision PHP Rss Servo singleton Skin Skinning Transitions Tween URLLoader URLRequest Vertical Scrollbar VScrollbar youtube
WP Cumulus Flash tag cloud by Roy Tanck requires Flash Player 9 or better.
Recent Posts
Develop Mobile apps with Catalyst?
Code optimization
TextInput Component
Interactions and Transitions
Most Commented
Recent Comments
how to call methods between swf files