YouTube in AIR

The YouTube video player is currently written in ActionScript 2.0 and integrating it into an AIR application requires a few additional steps. There are many solutions available that reverse engineer the URL to get access to the source video FLV, however, this breaks the terms of service and is not officially supported by YouTube or the API.

By taking advantage of the HTMLLoader class we are able to load the YouTube Chromeless video player into AIR without breaking the terms of service. It essentially loads up a web page within the AIR application and uses JavaScript to control the video.

Lets start by creating the JavaScript / HTML portion of the application that the HTMLLoader will consume. Resources for this can be found here; YouTube Chromeless Player Example page.

Simplified JavaScript functions for this example (includes Play, Pause and Load):

<script src="js/swfobject.js" type="text/javascript" />
<script type="text/javascript">

    function onYouTubePlayerReady(playerId) {
      ytplayer = document.getElementById("myytplayer");
    }

    // functions for the api calls
    function loadNewVideo(id, startSeconds) {
      if (ytplayer) {
        ytplayer.loadVideoById(id, startSeconds);
      }
    }

    function play() {
      if (ytplayer) {
        ytplayer.playVideo();
      }
    }

    function pause() {
      if (ytplayer) {
        ytplayer.pauseVideo();
      }
    }
    
</script>

Next we will use the SWFObject to load in the YouTube Chromeless video player. Notice the use of wmode: “opaque” in this example. Without this you will not be able to place any display objects above your videos.

<script type="text/javascript">

      // allowScriptAccess must be set to allow the Javascript from one 
      // domain to access the swf on the youtube domain
      var params = { allowScriptAccess: "always", bgcolor: "#cccccc", wmode: "opaque" };
      // this sets the id of the object or embed tag to 'myytplayer'.
      // You then use this id to access the swf and make calls to the player's API
      var atts = { id: "myytplayer" };
      swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer", 
                         "ytapiplayer", "400", "300", "8", null, null, params, atts);

</script>

ActionScript Used to Load and Control the Video:

package com.sb.util
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.html.HTMLLoader;
	import flash.net.URLRequest;
	
	public class JSVideoPlayer extends Sprite
	{
	
		private var _html:HTMLLoader;
		private var _ready:Boolean = false;
		
		public function JSVideoPlayer()
		{
			_html = new HTMLLoader();
			_html.paintsDefaultBackground = false;
			_html.width = 400;
			_html.height = 300;
			_html.addEventListener(Event.COMPLETE, 
                              onComplete);
			
			loadHTMLcontent()

			this.addChild( _html );
		}
		public function loadNewVideo(videoID:String):void
		{
			if(_ready){
				_html.window.loadNewVideo(videoID);
			}
		}
		
		public function playVideo():void
		{
			if(_ready){
				_html.window.play();
			}
		}

		public function pauseVideo():void
		{
			if(_ready){
				_html.window.pause();
			}
		}
		
		private function onComplete (e:Event):void
		{
			_ready = true;
		}
		
		public function loadHTMLcontent():void
		{
			_html.load(new URLRequest('test.html'));
		}
	
	}
}
YouTube in AIR

YouTube in AIR

One of the limitations of using the HTMLLoader class is the inability to set the opacity of the video. For example you if wanted to fade the video out you would have to capture the current state of the video and replace it with a bitmap image that would then be faded out (download the zip file to see an example of this).

Source Files (ZIP)

Enjoy!

Sources:

  • Creating JavaScript functions within an ActionScript class in AIR, Marco Casario link
  • YouTube Chromeless Player Example page google.api

PS: This example is only for AIR and may not work for Flex applications deployed on web sites. Please visit ‘YouTube in Flex applications’ (On The Other Hand) for an example of how to do this in Flex.

Mash up applications with Adobe AIR

When doing some research on integrating YouTube videos into Adobe AIR applications I came across this presentation. Marco Casario talks about the design patterns and technologies that can be used to aggregate social media networks in AIR. The Adobe AIR Cookbook will be out in November 2008 and will have more information on these topics.

http://casario.blogs.com/mmworld/2008/10/developing-mash.html

I will be posting soon with an example Flex and AIR application that can play YouTube videos (without breaking the terms of service). Many people today are reconstructing the URL to the source FLV which is against the terms of service. Between this presentation and another blog entry about YouTube in Flex applications (On The Other Hand) I should be able to post an example for both.

FlexFeed: Twitter RSS Feeds in Flex

Using Flex and PHP it is possible to integrate Twitter RSS feeds into a Flex web page. Twitters cross domain policy (which is used by Flash) does not allow external resources to access feeds. Using PHP as a medium to the data, Flex can access the feed and display all contents. This technique can be used to access any xml data that Flex may not have access to.

Let’s start by creating an HTTPService:

<mx:HTTPService 
	id="rssParse" 
	url="http://twitter.com/statuses/user_timeline/16584421.rss" 
	result="processResult(event)"
	resultFormat="e4x" />

Next we will create the function to process the results:

[as]
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;

[Bindable]
private var _rssResults:ArrayCollection;

// Define and use atom namespace.
private namespace atom = “http://www.w3.org/2005/Atom”;
use namespace atom;

private function processResult(event:ResultEvent):void
{
var xmlList:XMLList = event.result.channel.item as XMLList;
for each(var item:XML in xmlList){
var myDate:String = item.pubDate;
myDate = myDate.slice(0,22);
_rssResults.addItem({title: item.title, date: myDate});
}
}

private function init():void
{
_rssResults = new ArrayCollection();
rssParse.send();
}
[/as]

Now lets add the mxml to display the content:

<mx:VBox width="400" height="600" horizontalAlign="center">	
	<mx:Label styleName="subTitleText" text="Twitter Feed:" fontWeight="bold" fontSize="16"/>
	<mx:VBox height="500" width="400" verticalScrollPolicy="auto" horizontalScrollPolicy="off" horizontalAlign="center">
		<mx:Repeater id="twitter" dataProvider="{_rssResults}">
			<mx:Text textAlign="center" width="300" text="{twitter.currentItem.date}"/>
			<mx:Text textAlign="center" width="300" text="{twitter.currentItem.title}"/>
		</mx:Repeater>			
	</mx:VBox>	
</mx:VBox>	

After testing the application locally everything works great! But wait… what about the PHP code? Well first export a release build of the application and upload it to a web server for testing.

Here is the error that you should recieve:
[RPC Fault faultString=”Security error accessing url” faultCode=”Channel.Security.Error” faultDetail=”Destination: DefaultHTTP”]

To get around this let’s create a php file that collects the twitter data:

$twitter_feed = 'http://twitter.com/statuses/user_timeline/16584421.rss';
$rawfeed = @file_get_contents($twitter_feed);
print $rawfeed;

Now we need to update our HTTPService request to pull from the new php file:

<mx:HTTPService 
	id="rssParse" 
	url="php/twitter.php" 
	result="processResult(event)"
	resultFormat="e4x" />

Now everything works great!

Check out this link to view a functional example:
http://www.blackcj.com/FlexFeed/index.html

And the source files:
http://www.blackcj.com/FlexFeed/srcview/index.html

Please leave a comment if you have any questions, comments, or suggestions. Thanks!