Change the event category in the GTrack OSMF plugin (dynamically)

This is somewhat a spin-off from the Media Player Anatomy series of tutorials that I’m working on, but since there is nothing to be found out there I thought to post this in case it helps anyone.
From a series of emails that I had with a representative of the RealEyes Media the only way to change the event category that is being send to the server is by changing the config.xml file.
It seemed rather insane to have a single config.xml for each category so I thought to create one on the fly as it only needs to be xml (file or build with as3 makes no difference).
FYI this is the reops tutorial on the GTrack plugin (a really nice plugin and one of the few left for free nowadays…)
GTrack Plugin Tutorial

We assume that the initial load has been done and now we want to change the category into “music”
we declare an XML template:
[cc lang=”Actionscript”]
public var xmlTemplate:XML =
UA-26485023-1
UA-24092711-1
http://www.netgfx.com/trunk/samplePlayer/sample.html








true
250
;
[/cc]

And then we change it:
[cc lang=”Actionscript”]
public function createXMLConfig(cat:String = ‘music’):XML
{
var attr:XML = new XML(xmlTemplate);

var arr:XMLList = new XMLList();
arr = attr.event;
for(var i:Number=0;i {
attr.event[i].@category = cat;
}

return attr;
}
[/cc]

This can be then loaded as follows:
[cc lang=”Actionscript”]
var customPluginConfigXML:XML = createXMLConfig();
pluginResource.addMetadataValue( “http://www.realeyes.com/osmf/plugins/tracking/google”, customPluginConfigXML );
[/cc]

At this point you might want to remove the previous MetadataValue before assigning the new one.

Enjoy!

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Simple Loader with AS3 and TweenMax

This a loader that I created for my OSMF-based player. This is lightweight and simple to use.
Colors and shapes can easily be customized, text could also be included and event animated to match blocks.

The creation function, simple drawing.

[cc lang=”actionscript”]public function createLoader(bgColor:uint=0x2e2e2e):void
{
this.x = 0;
this.y = 0;
bg = new Sprite();
bg.graphics.beginFill(bgColor,1);
bg.graphics.lineStyle(3,0xf7f7f7,1,true);
bg.graphics.drawRoundRectComplex(0,0,200,100,5,5,5,5);
bg.graphics.endFill();
var gap:Number = 45;
var block:Sprite;

for(var i:int = 0;i<6;i++){ block = new Sprite(); block.graphics.beginFill(0xffffff,1); block.graphics.lineStyle(1,0x7e7e7e,1,false); block.graphics.drawRect(gap+(20*i),40,9,22); block.graphics.endFill(); bg.addChild(block); } this.addChild(bg); tint(); [/cc] And the function that handles the animation, it applies colorization to each block in order then calls it self with the index increased by one. [cc lang="actionscript"] private function tint(value:Number=0):void { var length:Number = bg.numChildren; var indexItem:Number; for(var i:int = 0;ilength-1) { indexItem = 0; } else { indexItem = value; } TweenMax.to(bg.getChildAt(indexItem), .2, {colorMatrixFilter:{colorize:0x3399ff, amount:1.2, contrast:1, brightness:1, saturation:1, hue:50}, onComplete:function(){ TweenMax.to(bg.getChildAt(indexItem), .6, {colorMatrixFilter:{colorize:0xffffff, amount:1}, ease:Quad.easeInOut}); tint(indexItem+1); }}); }[/cc] The release version is a mere 20kb file. Download the source here: UILoader

View Example here: UILoader-Demo

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Create a button with font-icon and pure actionscript 3

As I see that the font-icon technique is becoming very popular, and I personally like it very much I decided to post some code of how to create a simple button with an Icon using only AS3 as it is lighter and much faster on mobile devices.

We will create a class that will hold our button, as you will see I have embedded the signify font, (signify is a font which has icons corresponding to letters and numbers):

[cc lang=”Actionscript”]
package
{
import flash.display.GradientType;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Matrix;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.getQualifiedClassName;

public class UIButton extends Sprite
{
[Embed(source=”fonts/signify-webfont.ttf”, fontFamily=”Signify”, embedAsCFF=”false”)]
public static var signify:String;

private var myShape:Shape;
private var gradientBoxMatrix:Matrix;
private var masterWidth:Number;
private var masterHeight:Number;

private var radius:Number = 10;

public function UIButton()
{
super();
}
}
}
[/cc]

Next we will create the main function that draws the button:

[cc lang=”Actionscript”]
public function createButton(gradientColor_:Array = null, width:Number=120, height:Number=60, x:Number=10, y:Number=10, _text:String = ‘E’)
{

}
[/cc]

First we draw the matrix for the gradients and the rectangle:

[cc lang=”Actionscript”]
myShape = new Shape();
gradientBoxMatrix = new Matrix();
gradientBoxMatrix.createGradientBox(width, height, Math.PI/2, 0, 0);
myShape.graphics.beginGradientFill(GradientType.LINEAR, gradientColor_, [1,1,1], [0,128,255],gradientBoxMatrix);
myShape.graphics.lineStyle(2, 0x1e1e1e);
myShape.graphics.drawRoundRect(0,0,width,height,radius);
myShape.graphics.endFill();
[/cc]

And now we create the icon:

[cc lang=”Actionscript”]
var tfl:TextField = new TextField();
tfl.text = _text;
tfl.width = width/2;
tfl.height = height/2;
tfl.textColor = 0x0e0e0e;
tfl.embedFonts = true;
var tf:TextFormat = new TextFormat(‘Signify’,38,0x0e0e0e); //here we define the embedded font
tfl.setTextFormat(tf);
tfl.selectable = false;

tfl.x = width/2 – tfl.textWidth+19;
tfl.y = -10;
[/cc]

finally we add them to the display object:

[cc lang=”Actionscript”]
this.addChild(myShape);
this.addChild(tfl);
[/cc]

we can easily call this class by doing:

[cc lang=”Actionscript”]
var button:UIButton = new UIButton();
button.createButton([0xffffff,0xf1f1f1,0xf8f8f8]);
addChild(button);
[/cc]

View an example here: MobileUI

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Flex Preloader with Greensock TweenLite and TweenMax

In this tutorial we will create a preloader for a Flex application that will place a tint over a set of images coloring them as the loading process continues.

Note that this tutorial also applies for Flex 4.x and 3.x

First we create a new Actionscript file.

We name it “Preloader.as”, and we place it in a package named: “Preloader_”

Then we import it in our Flex Application like this:

<s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009″ 

xmlns:s=”library://ns.adobe.com/flex/spark             xmlns:mx=”library://ns.adobe.com/flex/mx”              preloader=”Preloader_.Preloader”>

 

Main Code

In the Preloader Class we place an extend definition like this:

public class Preloader extends DownloadProgressBar

This means that can override and extend the DownloadProgressBar methods.

Now let’s import our images (here I used three but you’ll find a hint inside the source of how to apply this effect into more images)

 

[Embed(source=“/assets/NET.png”)]

private var FlashPreloaderSymbol1:Class;

 

[Embed(source=“/assets/GFX.png”)]

private var FlashPreloaderSymbol2:Class;

 

[Embed(source=“/assets/COM.png”)]

private var FlashPreloaderSymbol3:Class;

 

private var clip;

private var clip2;

private var clip3;

 

On the constructor now we will add the code to actually import the images onto the stage:

public function Preloader() 

{

super();

//getting the images into the loader

clip = new FlashPreloaderSymbol1();

clip2 = new FlashPreloaderSymbol2();

clip3 = new FlashPreloaderSymbol3();

 

//Adding images to stage

addChild(clip);

addChild(clip2);

addChild(clip3);

}

 

And now that we have the images properly set, we continue to the most important part, the method that will monitor the completion events of each portion of the application (RSLs, Swf, framework files).

public override function set preloader(preloader:Sprite):void 

{

//Center the images

centerPreloader();

// runtime shared library

preloader.addEventListener( RSLEvent.RSL_PROGRESS, onRSLDownloadProgress );

preloader.addEventListener( RSLEvent.RSL_COMPLETE, onRSLDownloadComplete );

preloader.addEventListener( RSLEvent.RSL_ERROR, onRSLError );

 

// application

preloader.addEventListener( ProgressEvent.PROGRESS, onSWFDownloadProgress );

preloader.addEventListener( Event.COMPLETE, onSWFDownloadComplete );

 

// initialization

preloader.addEventListener( FlexEvent.INIT_PROGRESS, onFlexInitProgress );

preloader.addEventListener( FlexEvent.INIT_COMPLETE, onFlexInitComplete );

}

 

As we can see an event will fire in every stage of the loading procedure.

Now let’s see each individual event listener

private function onRSLDownloadProgress( event:ProgressEvent ):void 

{

isRslDownloading = true;

 

rslBytesTotal = event.bytesTotal;

rslBytesLoaded = event.bytesLoaded;

rslPercent = Math.round( (rslBytesLoaded / rslBytesTotal) * 100);

//trace(“onRSLDownloadProgress: rslBytesLoaded ” + rslBytesLoaded);

//trace(“onRSLDownloadProgress: rslBytesTotal ” + rslBytesTotal);

//trace(“onRSLDownloadProgress: ” + rslPercent + “%”);

 

updateProgress();

}

The RSL loading handler

 

private function onRSLDownloadComplete( event:RSLEvent ):void 

{

// We tween the color of the first image into an green tint, also adding a little blur to make it more impressive

TweenMax.to(clip, 2, {tint:0xA3F40E, glowFilter:{color:0xA3F40E, alpha:1, blurX:10, blurY:10}});

rslPercent = 100;

}

 

This is where the magic takes place, when each part has finished loading one of the images will slowly change color, the images where originally a shade of grey, but when the first part of the loading stage completes the loading images will look like this:

private function onSWFDownloadProgress( event:ProgressEvent ):void 

{

swfBytesTotal = event.bytesTotal;

swfBytesLoaded = event.bytesLoaded;

 

if ( isRslDownloading ) {

// as soon as RSL starts downloading the SWF data are added by the RSL values

swfBytesTotal -= rslBytesTotal;

swfBytesLoaded -= rslBytesLoaded;

}

swfPercent = Math.round( (swfBytesLoaded / swfBytesTotal) * 100);

//trace(“onSWFDownloadProgress: ” + swfPercent + “%”);

//trace(“onSWFDownloadProgress: swfBytesLoaded ” + swfBytesLoaded);

//trace(“onSWFDownloadProgress: swfBytesTotal ” + swfBytesTotal);

 

updateProgress();

}

The swf loading handler

 

private function onSWFDownloadComplete( event:Event ):void 

{

//Now tweening the second image (remember we can have as much as we want)

TweenMax.to(clip2, 2, {tint:0xA3F40E, glowFilter:{color:0xA3F40E, alpha:1, blurX:10, blurY:10}});

 

swfPercent = 100;

}

 

When the second part of the loading stage completes we will have something like this:

private function onFlexInitComplete( event:FlexEvent ):void 

{

//Tweening the last image and onComplete we launch the application, we do this to make sure it the effect will play

var myTween:TweenMax = TweenMax.to(clip3, 1, {tint:0xA3F40E, glowFilter:{color:0xA3F40E, alpha:1, blurX:10, blurY:10}});

myTween.addEventListener(Event.COMPLETE,onDoneAnimating);

}

 

As stated in the comment inside the code, here we tween the last of our images but we also include a callBack function in order to allow the tween to complete gracefully and not be interrupted.

This is our last result of the effects:

After the tween finishes the following code will run and the Flex application will initialize:

private function onDoneAnimating(e):void 

{

// The final event is dispatched. The application will now load.

dispatchEvent( new Event( Event.COMPLETE ) );

}

 

You can view a DEMO (make sure you clear cache and refresh if you need to see the preloader again)

Download the source/project files here: Greensock-Tutorial-Flex-Preloader

Thanks for reading I hope this will enable you to create even more fancy preloaders.

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Flex 4.5 add Icon to Buttons with AS3

This has changed since the pre-release and I thought I should mention it, because Icons on buttons are awesome.
So if you have set your button with mxml the property icon is right there, however if you want to dynamically create a button with an Icon with AS3 script you will have to declare it like this:


var Btn = new Button();
Btn.setStyle("icon","assets/icon.png");

As you see Icon property is now a style rather than a property.

Enjoy!

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Components Factory from XML/AS3

In this post we will create Video and Image components by using only an XML file and AS3 code. Finally we will place all these Components into a Grid Gallery.

This approach has many benefits as it will render more smoothly in mobile devices and tablets as mxml code is a bit heavy even with the latest Flex Hero build.

This is the XML structure that we will use:

<main>
<items>
<item target=”assets/img.jpg” type=”image”/>
<item target=”http://pseudo01.hddn.com/vod/demo.flowplayervod/flowplayer-960.mp4″ type=”video”/>
<item target=”http://pseudo01.hddn.com/vod/demo.flowplayervod/flowplayer-960.mp4″ type=”video”/>
<item target=”http://pseudo01.hddn.com/vod/demo.flowplayervod/flowplayer-960.mp4″ type=”video”/>
<item target=”http://pseudo01.hddn.com/vod/demo.flowplayervod/flowplayer-960.mp4″ type=”video”/>
<item target=”assets/img.jpg” type=”image”/>
<item target=”assets/img.jpg” type=”image”/>
<item target=”assets/img.jpg” type=”image”/>
</items>
</main>

The MXML Tile component (this could also be AS3 code)

<s:TileGroup id=”grid” x=”0″ y=”0″  creationComplete=”buildItemsFromXML()”>
</s:TileGroup>

Now some AS3 code:

we will create the loader function

[cc lang=”actionscript”]

private function buildItemsFromXML()
{
var xmlCall:XMLService = new XMLService();
xmlCall.makeCall(XMLSource);
xmlCall.service.addEventListener(ResultEvent.RESULT,resultResponse);
xmlCall.service.addEventListener(FaultEvent.FAULT,faultResponse);
}

//The magic happens into the success response function

function resultResponse(evt:ResultEvent)
{
itemArray = new Array();
var result = evt.result as XML;
var xml = result.items.elements(“*”);
for each(var item in xml) //Parse all elements of the XML
{
//trace(item.@type+”::”+item.@target);
if(String(item.@type).toLowerCase()==”video”) // Create a VideoDisplayComponent
{
var vid:VideoDisplay = new VideoDisplay();
vid.source = String(item.@target);
vid.autoPlay = false;
vid.scaleMode = “stretch”;
vid.width = itemsWidth;
vid.height = itemsHeight;
vid.verticalCenter = 0;
vid.horizontalCenter = 0;
vid.validateNow();
vid.invalidateDisplayList();
itemArray.push(vid);
}
else if(String(item.@type).toLowerCase()==”image”) //Create a spark Image component
{
var img:Image = new Image();
img.source = String(item.@target);
img.width = itemsWidth;
img.height = itemsHeight;
img.verticalCenter = 0;
img.horizontalCenter = 0;
img.validateNow();
img.invalidateDisplayList();
itemArray.push(img);
}
else if(String(item.@type).toLowerCase()==”videoplayer”)  // Create a VideoPlayer component
{
var vidp:VideoPlayer = new VideoPlayer();
vidp.source = String(item.@target);
vidp.autoPlay = false;
vidp.scaleMode = “stretch”;
vidp.width = itemsWidth;
vidp.height = itemsHeight;
vidp.verticalCenter = 0;
vidp.horizontalCenter = 0;
vidp.validateNow();
vidp.invalidateDisplayList();
itemArray.push(vidp);
}
}

placeItems(); // The next function that will place the items into the grid
}

[/cc]

Now we place all elements into the Tile Gallery

[cc lang=”actionscript”]
function placeItems()
{
//add all elements into the grid,
for each(var item in itemArray)
{
var grp = new Group(); //We prefer the Group component because it makes it easy to position elements inside
grp.addElement(item);
grid.addElement(grp);
grid.validateNow();
grid.invalidateDisplayList();
}
}
[/cc]
 

And we are done! Now you have your own components factory build only by XML and AS3 code.

View an Example Here: http://www.netgfx.com/GridGallery/

Enjoy!

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

OSMF Strobe Media Player into Flex Mobile Project (Hero)

I have worked with Strobe media player before and it is a nice player with many features and allows a great level of customization if done properly.

So I’ll explain how to import the Strobe Media player into your Mobile Flex builder Projects successfully and create a dynamic Stream with it.

First Download Strobe Media Player: http://sourceforge.net/projects/smp.adobe/files/ (currently I work with 1.5.1)

Export the contents into a folder.

Create a new Mobile Project on Flash/Flex Builder

Copy from the Strobe Media player folder the “src/player/StrobeMediaPlayback/src” and from the same folder the “/assets” folder

Also copy from “/StrobeMediaPlayback_1.5.1-full/src/framework” the OSMF.swc

and place them on the src folder of your project. Refresh the folder tree from Flash/Flex builder.

Place the OSMF.swc into your lib folder.

Now on to some Configurations:

On the Project/Properties

On Build Path/Library Path add the assets.swc from the assets folder

On Compiler arguments add: -define CONFIG::LOGGING false -define CONFIG::FLASH_10_1 true

 

At last Coding time!

Create a new View component, open a fx:Script tag and enter the following:
[cc lang=”actionscript” width=”480″ height=”500″]
import mx.core.UIComponent;

import spark.components.Button;
import spark.components.Group;

public var $playerInstance:StrobeMediaPlayback;
var grp:Group = new Group();
protected function init(event:Event):void
{

_stage = systemManager.stage;
_stage.align = StageAlign.TOP_LEFT;
_parameters  =
{
src:”http://osmf.org/dev/videos/cathy1_SD.mp4″
, controlBarMode:”docked”
, controlBarAutoHide: true
, autoPlay: true
, playButtonOverlay:true
, showVideoInfoOverlayOnStartUp: true
};

var playerInstance:StrobeMediaPlayback = new StrobeMediaPlayback();
playerInstance.initialize(_parameters, _stage, systemManager.loaderInfo, null);
$playerInstance = playerInstance;

var ui:UIComponent = new UIComponent();
ui.addChild($playerInstance as DisplayObject);

grp.percentWidth = 100;
grp.percentHeight = 100;
addElement(grp);
grp.addElement(ui);

}

private var urlLoader:URLLoader;
private var urlRequest:URLRequest;
private var loader:Loader;
private var _stage:Stage;
private var _parameters:Object;
/* static */
private static const ALLOW_LOAD_BYTES_CODE_EXECUTION:String = “allowLoadBytesCodeExecution”;

function emptyCache()
{
$playerInstance.player.pause();
grp.removeAllElements();
this.destructionPolicy = “auto”;
}
[/cc]
Note!

Make sure to call init() on ViewActivate, or CreationComplete event. Also I recoment to assign on ViewDeactivate the emptyCache() function otherwize the sound of the video might keep on playing…

As a side note here, its better to create components in Actionscript even spark ones, than in mxml at least at this point where Flex Hero framework is still in Beta.

So thats it, now you have Strobe Media Player in your Mobile Application, especially now with 10.2 and stage video that focuses on low CPU consumption its essential for any mobile application with a video player.

!Important: In case you are not viewing a controlBar there is a chance that the default ActionBar is pushing the ControlBar downwards, so if that is the case try a different percentage for grp.percent=90, or disable the ActionBar -> set actionBarVisible = false in the View component properties.

Enjoy!

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Flex audio player with Flowplayer core

I’ll present a simple task that allows to implement the power of the flex framework and flash graphics to a equally powerful core player such as the Flowplayer, bridged with JQuery.

First of all let’s create the graphics for the player, lets assume you have some basic images for the buttons and the background:

<s:Group width=”338″ height=”39″>
<s:Image source=”assets/playerBack.png” smooth=”true” width=”338″ height=”39″/>
<s:Image source=”assets/play.png” smooth=”true” left=”20″ top=”10″ click=”goPlay()” useHandCursor=”true” buttonMode=”true”/>
<s:Image source=”assets/pause.png” smooth=”true” left=”50″ top=”10″ click=”goStop();” useHandCursor=”true” buttonMode=”true”/>

<s:HSlider horizontalCenter=”20″ top=”10″ width=”178″ maximum=”1″ minimum=”0″ showDataTip=”false” stepSize=”0.1″ skinClass=”Skinz.VolumeSkinClass”/>
</s:Group>

!Note: make the <s:Application/> slightly bigger and opaque (height=”45″ width=”360″ backgroundAlpha=”0.0″)

!Note:make sure to include Jquery to your HTML file, I created this with JQuery.1.5.min.js

now a little bit of AS3 script to trigger the Javascript

private function goPlay()
{
ExternalInterface.call(“goPlay”);
}

private function goStop()
{
ExternalInterface.call(“goStop”);
}

Now export a release build and copy the .swf file in your HTML Project folder.

Our Flowplayer lives on a <div/>

<div id=”audiosecure” style=”display:block;” href=”http://releases.flowplayer.org/data/fake_empire.mp3″></div>

!Note: placing it on a div without size makes it invisible but still functional. cool huh!?

Create the flowplayer:

// install flowplayer into container
$f(“audiosecure”, “flowplayer/flowplayer.commercial-3.2.5.swf”, {

// fullscreen button not needed here
plugins: {
controls: {
fullscreen: false,
height: 30,
autoHide: false
}
},
clip: {
autoPlay: false,

// optional: when playback starts close the first audio playback
onBeforeBegin: function() {
$f(“audiosecure”).close();
}
}
});

Our SexyPlayer :

<div id=”sexyPlayer”>
<object width=”360″ height=”45″ wmode=”transparent”>
<param name=”movie” value=”css/assets/player/Action24Player.swf”>
<embed src=”css/assets/player/Action24Player.swf” wmode=”transparent” width=”360″ height=”45″>
</embed>
</object>
</div>

Some CSS:

#audiosecure
{
position:absolute;
left:150px;
top:100px;
}

#sexyPlayer
{
position:absolute;
left:150px;
top:10px;
z-index:9999;
}

!Note: make sure to place the Flowplayer lower than sexyPlayer

Throw in a couple of JS functions and you’re good to go:

function goPlay(){
$f(1).stop();
$f(0).play();
}

function goStop(){
$f(1).stop();
$f(0).stop();
}

Enjoy!

feel free to comment if you found this helpful.

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

How to make Combobox with hours of day (quarters)

This is an algorithm which produces the hours of day for every quarter (00:00, 00:15, 00:30, 00:45) and inserts them in a combobox, I used this in my ToDo application which I will soon post and I thought it might be useful to someone.

/*ActionScript*/

var model:Array = [];

var entry:Number = 0;
var entryHour:Number = 0;
var entryMinutes:Number = 0;
var result:String;

//The main loop runs 4*24 times cause we want all hours from 00:00 – 24:00 to be set
//
for (var j:int = 0; j<4*24; j++) { if (j==0)
{

model.push(result=(entryHour=entryHour).toString()+”0″+”:”+”00″);
}
else if (entry<3)
{
if(entryHour<10)
{

//if time < 10 adds a 0 so it will look like 09:00 and not 9:00
model.push(result = “0”+(entryHour).toString()+”:”+(entryMinutes=entryMinutes+15).toString());
}
else
{
model.push(
result = (entryHour).toString()+”:”+(entryMinutes=entryMinutes+15).toString());
}

entry++;

}
else
{
if(entryHour<9)
{
model.push(result= “0”+(entryHour=entryHour+1).toString()+”:”+”00″);
}
else
{
model.push(result=(entryHour=entryHour+1).toString()+”:”+”00″);
}

//reset the vars
entry=0;
entryMinutes=0;

}
}

return model;
}

Facebooktwittergoogle_pluspinterestlinkedin
linkedin