Tag Archives: AS3

Play videos with a simple < video > tag in your html text field

Play videos with a simple < video > tag in your html text field

 

There are many flash video players around which you can embed into your html webpage and use it to play flv or YouTube videos. But what would you do if you are working on a full AS3 project (mobile or desktop) and you need to have a video player inside your TextField? Check the demo below to see how the player has been loaded inside the text field:

You know that flash.text.TextField loads external content with the < img > tag only, right? In the following 30 minutes, you will learn everything you need about how you can play videos inside your text content with the new < video > tag, like this:


videoPlayer/01.jpg

onPlay()
onPause()
onStop()
onFullScreen()
onEnded()
onVolumeChange()
onSeeking()


 

Step1) Create a new Project

Regardless of what IDE you’re using, create a new project and initialize TextArea in it. To learn more about TextArea you may read here http://active.tutsplus.com/tutorials/tools-tips/easily-create-souped-up-flash-text-fields-with-textarea and download it from here: http://doitflash.com/

Ok, I’m using FlashDevelop and my document class looks like below. Yours may be a little different though if you’re using Flex builder or CS IDE.


package
{
import flash.display.Sprite;
import flash.events.Event;

/**
* ...
* @author Hadi Tavakoli - 2/19/2012 5:27 PM
*/
public class Main extends Sprite
{

public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}

private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point

}

}
}

To initialize TextArea, first you need to import the required classes.


import com.doitflash.text.TextArea;
import com.doitflash.text.events.TextInLineEvent;

Then create a new variable which will hold an instance of the TextArea.


private var _textArea:TextArea;

Now create a function where the instance will be initialized and added to stage.


private function initTxt():void
{
_textArea = new TextArea();
_textArea.condenseWhite = true;
_textArea.embedFonts = false;
_textArea.border = true;
_textArea.multiline = true;
_textArea.wordWrap = true;
_textArea.width = 500;
_textArea.height = 500;

_textArea.fmlText = "some content in your text field...";
this.addChild(_textArea);
}

Up to here, your document class should look like below.


package
{
import flash.display.Sprite;
import flash.events.Event;
import com.doitflash.text.TextArea;
import com.doitflash.text.events.TextInLineEvent;

/**
* ...
* @author Hadi Tavakoli - 2/19/2012 5:27 PM
*/
public class Main extends Sprite
{
private var _textArea:TextArea;

public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}

private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point

initTxt();
}

private function initTxt():void
{
_textArea = new TextArea();
_textArea.condenseWhite = true;
_textArea.embedFonts = false;
_textArea.border = true;
_textArea.multiline = true;
_textArea.wordWrap = true;
_textArea.width = 500;
_textArea.height = 500;

_textArea.fmlText = "some content in your text field...";
this.addChild(_textArea);
}

}
}

And if you run your project, you must see a 500 X 500 pixel text field with a black border with some sample script in it. If you have noticed, initializing TextArea is similar to the original TextField class. It’s important to remember that if you want to use the new html tags in your project, like how we’ll be using < video > tag in the rest of this tutorial, you need to use the fmlText property for TextArea rather than htmlText introduced in TextField.

Step2) Setup the assets

If you have tested the project till here, a swf file must have been generated. Go to where the published swf file is located and extract the content of this zip file to it. http://doitflash.com/downloads/tuts/videoTagTut.zip

Now you must have two new folders, assets and videoPlayer where your project is published. To get you out of the dark and tell you what you have downloaded, I must say that you have just setup the video player skin and a sample .mp4 file to help you see something real with your project. After we successfully played the .mp4 I will talk about how you can also play YouTube videos!

For the sake of this tutorial, don’t change the skin and button designs and leave everything as is. Yet, it’s worthy to mention that you can easily change the location of button designs from this xml file: videoPlayer/videoPlayer.xml

Feel free to explore this xml file and play with values there to create your own custom designed player.

There is also another important thing to mention about this xml file and it’s about the timer field of the player where you have the following:



Arimo

0xFFFFFF 10

As you see, we have used the font “Arimo” for the timer field of the player. If you want to use other font types, you may change it from here. Regardless of what font you’re using, you must remember to embed it in your project. We’ll do so in the next step.

Step2) Embed fonts

Choose your font .ttf files and put them in a folder named “fonts” where you have your project document class .as file. I suggest using Arimo though, it looks great in AS3 projects and its license is ok also. Just Google “Arimo font” and you’ll find where to download the .ttf files.

Then embed them all like below in your document class.


[Embed(source="fonts/Arimo-Regular.ttf", embedAsCFF="false", fontFamily="Arimo", mimeType="application/x-font-truetype")]
private var arimoRegular:Class;

[Embed(source="fonts/Arimo-Bold.ttf", embedAsCFF="false", fontFamily="Arimo", fontWeight="Bold", mimeType="application/x-font-truetype")]
private var arimoBold:Class;

[Embed(source="fonts/Arimo-Italic.ttf", embedAsCFF="false", fontFamily="Arimo", fontStyle="Italic", mimeType="application/x-font-truetype")]
private var arimoItalic:Class;

[Embed(source="fonts/Arimo-BoldItalic.ttf", embedAsCFF="false", fontFamily="Arimo", fontWeight="Bold", fontStyle="Italic", mimeType="application/x-font-truetype")]
private var arimoBoldItalic:Class;

You’re not done with the font embedding step yet! For the player skin to be able to access these fonts that you just embedded, you need to register them. So, import the following class:


import flash.text.Font;

And then put the following in the constructor function of your document class.


Font.registerFont(arimoRegular);
Font.registerFont(arimoBold);
Font.registerFont(arimoItalic);
Font.registerFont(arimoBoldItalic);

Now that we have embedded some fonts, it should be a good idea to change the embedFonts property of our TextArea instance to true and make some visual enhancements to it.


_textArea.antiAliasType = "advanced";
_textArea.embedFonts = true;
_textArea.fmlText = "some content in your text field...";

You’re document class should look like this by now:


package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.text.Font;
import com.doitflash.text.TextArea;
import com.doitflash.text.events.TextInLineEvent;

/**
* ...
* @author Hadi Tavakoli - 2/19/2012 5:27 PM
*/
public class Main extends Sprite
{
private var _textArea:TextArea;

[Embed(source="fonts/Arimo-Regular.ttf", embedAsCFF="false", fontFamily="Arimo", mimeType="application/x-font-truetype")]
private var arimoRegular:Class;

[Embed(source="fonts/Arimo-Bold.ttf", embedAsCFF="false", fontFamily="Arimo", fontWeight="Bold", mimeType="application/x-font-truetype")]
private var arimoBold:Class;

[Embed(source="fonts/Arimo-Italic.ttf", embedAsCFF="false", fontFamily="Arimo", fontStyle="Italic", mimeType="application/x-font-truetype")]
private var arimoItalic:Class;

[Embed(source="fonts/Arimo-BoldItalic.ttf", embedAsCFF="false", fontFamily="Arimo", fontWeight="Bold", fontStyle="Italic", mimeType="application/x-font-truetype")]
private var arimoBoldItalic:Class;

public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);

Font.registerFont(arimoRegular);
Font.registerFont(arimoBold);
Font.registerFont(arimoItalic);
Font.registerFont(arimoBoldItalic);
}

private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point

initTxt();
}

private function initTxt():void
{
_textArea = new TextArea();
_textArea.antiAliasType = "advanced";
_textArea.condenseWhite = true;
_textArea.embedFonts = true;
_textArea.border = true;
_textArea.multiline = true;
_textArea.wordWrap = true;
_textArea.width = 500;
_textArea.height = 500;

_textArea.fmlText = "some content in your text field...";
this.addChild(_textArea);
}

}
}

Step3) Setup TextArea for the new html tags

In this tutorial, you’ll learn about < video > tag, but there are more tags for you to explore on doitflash.com. I’m saying this, because in order to work with the new html tags, you need to setup your TextArea instance. Modify the initTxt() function like this.


private function initTxt():void
{
_textArea = new TextArea();
_textArea.antiAliasType = "advanced";
_textArea.condenseWhite = true;
_textArea.embedFonts = true;
_textArea.border = true;
_textArea.multiline = true;
_textArea.wordWrap = true;
_textArea.width = 500;
_textArea.height = 500;

_textArea.holder = this;
_textArea.client = this;
_textArea.assetsPath = "assets/";
_textArea.funcSecurity = false;
_textArea.addEventListener(TextInLineEvent.MODULE_LOADED, onModuleLoaded);

_textArea.fmlText = "some content in your text field...";
this.addChild(_textArea);
}

The property holder, saves a reference to the class which has initialized the TextArea instance. This property is mainly used for TextArea internal works so I’m not explaining what it does here!

The property client, is a reference to where you will put functions which your TextArea instance will call. Let me explain this a bit more. You see, later in this tutorial, you will learn that you can create functions in your project which will interact with your video player. For example when the fullscreen button on the player is clicked, you want to do something special on your project, right? So you will write a function to handle the work. I will later tell you more about these dispatches from the video tag, but what you should know is that your will use the client property of TextField to let it know where these functions will be. For the sake of this tutorial we’ll set it to this. So we don’t have to create other classes for our functions and will put all the functions required by the video player dispatches in our document class.

The property assetsPath, will let TextArea know about the assets folder that you downloaded in previous steps.

The property funcSecurity, is helpful when you want to make sure your code is secure! When you are feeding the TextArea instance from external sources, for example an external xml file, it will be possible to hack into and call some other functions in your project just by changing the strings in the xml file! To stop this, set the value of funcSecurity to true and then use the following method to introduce the allowed functions!


_textArea.funcSecurity = true;
_textArea.allowedFunctions(func1, func2, func3);

This will make sure that only the above three functions are allowed to be called from external sources.

There is also a listener:


TextInLineEvent.MODULE_LOADED

Which is for TextArea which will be dispatched as soon as a module, or better to say, a tag, is loaded. As we are trying to load a video player, it is worthy to be able to know when it’s loaded inside the TextArea instance. So, we have set the listener to call onModuleLoaded(). When the player is loaded, it will call this function. Checkout the trace calls to see what information you’ll receive from this dispatch.


private function onModuleLoaded(e:TextInLineEvent):void
{
trace("reference to the loaded module: "+ e.param.module);
trace("id of the loaded tag: "+ e.param.id);
trace("name of the tag: "+ e.param.tagName);
}

Step4) Add the < video > tag into your html content

Just change the value of _textArea.fmlText to this and test your project! The player will work now and plays the sample video you had previously downloaded.


_textArea.fmlText = "some content in your text field..." +
"" +
"
";

For this tutorial to be as easy as possible to follow, I did not try to feed the text area with external data, but you will enjoy the < video > tag more when you can load it from a simple .txt or .xml file!

If you have a look at the < video > structure, you will understand what they mean and I don’t think it would be necessary to explain what each tag does. Let me just give you a hint though, if you want the player not to auto play the video, remove the whole autoplay line and it will stop at the beginning.

Step5) Make it play YouTube videos

To play YouTube videos, all you have to do is to set the video type to YouTube and pass the video id. Change the source part to below and test your project.


"" +
"hfcd1Nlpwgs" +
"youtube" +
"ratio" +
"autoplay" +
"loop" +
"" +

Step6) Listen to events

In previous steps, I mentioned that each tag module has its own events which you can set some functions to receive them. The video module has the following events to listen to. Change of _textArea.fmlText to following.


_textArea.fmlText = "some content in your text field..." +
"" +
"
";

The names of the events are self-explanatory but what you should know is that every event that is dispatched will send an object with itself in which you will find some useful information about the event. Let’s build the functions and I will show you all the possible data that you may receive for each event. Notice that these functions are all “public” and must be where set the textArea.client property.


public function onPlay($obj:Object=null):void
{
trace("on play clicked");
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);
trace("--------------------------------------");
}

public function onPause($obj:Object=null):void
{
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);
trace("--------------------------------------");
}

public function onStop($obj:Object=null):void
{
trace("on stop clicked");
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);
trace("--------------------------------------");
}

public function onEnded($obj:Object=null):void
{
trace("Video finished");
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);
trace("--------------------------------------");
}

public function onFullScreen($obj:Object=null):void
{
trace("on fullscreen clicked");
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);
trace("--------------------------------------");
}

public function onVolumeChange($obj:Object=null):void
{
trace("on volume clicked");
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);
trace("video volume: " + $obj.volume);
trace("--------------------------------------");
}

public function onSeeking($obj:Object=null):void
{
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);

if ($obj.target.youtube)
{
trace("YouTube current time: " + $obj.currentTime);
trace("YouTube video duration: " + $obj.duration);
}
else
{
trace("video position: " + $obj.position);
trace("video length: " + $obj.length);
}
trace("--------------------------------------")
}

It’s not like you would need all of these events in your every project, you may just remove the whole < event > tag and build your project without them, but it’s good to know how to interact with them, right?

To make sure you have set your document class correctly, here’s the whole document class for your reference.


package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.text.Font;
import com.doitflash.text.TextArea;
import com.doitflash.text.events.TextInLineEvent;

/**
* ...
* @author Hadi Tavakoli - 2/19/2012 5:27 PM
*/
public class Main extends Sprite
{
private var _textArea:TextArea;

[Embed(source="fonts/Arimo-Regular.ttf", embedAsCFF="false", fontFamily="Arimo", mimeType="application/x-font-truetype")]
private var arimoRegular:Class;

[Embed(source="fonts/Arimo-Bold.ttf", embedAsCFF="false", fontFamily="Arimo", fontWeight="Bold", mimeType="application/x-font-truetype")]
private var arimoBold:Class;

[Embed(source="fonts/Arimo-Italic.ttf", embedAsCFF="false", fontFamily="Arimo", fontStyle="Italic", mimeType="application/x-font-truetype")]
private var arimoItalic:Class;

[Embed(source="fonts/Arimo-BoldItalic.ttf", embedAsCFF="false", fontFamily="Arimo", fontWeight="Bold", fontStyle="Italic", mimeType="application/x-font-truetype")]
private var arimoBoldItalic:Class;

public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);

Font.registerFont(arimoRegular);
Font.registerFont(arimoBold);
Font.registerFont(arimoItalic);
Font.registerFont(arimoBoldItalic);
}

private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point

initTxt();
}

private function initTxt():void
{
_textArea = new TextArea();
_textArea.antiAliasType = "advanced";
_textArea.condenseWhite = true;
_textArea.embedFonts = true;
_textArea.border = true;
_textArea.multiline = true;
_textArea.wordWrap = true;
_textArea.width = 500;
_textArea.height = 500;

_textArea.holder = this;
_textArea.client = this;
_textArea.assetsPath = "assets/";
_textArea.funcSecurity = false;
_textArea.addEventListener(TextInLineEvent.MODULE_LOADED, onModuleLoaded);

_textArea.fmlText = "some content in your text field..." +
"" +
"
";
this.addChild(_textArea);
}

private function onModuleLoaded(e:TextInLineEvent):void
{
trace("reference to the loaded module: "+ e.param.module);
trace("id of the loaded tag: "+ e.param.id);
trace("name of the tag: " + e.param.tagName);
trace("--------------------------------------");
}

public function onPlay($obj:Object=null):void
{
trace("on play clicked");
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);
trace("--------------------------------------");
}

public function onPause($obj:Object=null):void
{
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);
trace("--------------------------------------");
}

public function onStop($obj:Object=null):void
{
trace("on stop clicked");
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);
trace("--------------------------------------");
}

public function onEnded($obj:Object=null):void
{
trace("Video finished");
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);
trace("--------------------------------------");
}

public function onFullScreen($obj:Object=null):void
{
trace("on fullscreen clicked");
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);
trace("--------------------------------------");
}

public function onVolumeChange($obj:Object=null):void
{
trace("on volume clicked");
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);
trace("video volume: " + $obj.volume);
trace("--------------------------------------");
}

public function onSeeking($obj:Object=null):void
{
trace("event type: " + $obj.type);
trace("reference to module: " + $obj.target);

if ($obj.target.youtube)
{
trace("YouTube current time: " + $obj.currentTime);
trace("YouTube video duration: " + $obj.duration);
}
else
{
trace("video position: " + $obj.position);
trace("video length: " + $obj.length);
}
trace("--------------------------------------")
}

}
}

Conclusion

In this tutorial you learned how to load a video player inside your text field using a simple < video > tag in your html texts. Adobe supports only basic html tags in TextField but using TextArea as an alternative to TextField, you will be able to do more with texts in your AS3 projects. In future tutorials, I’ll talk about other custom tags and then I will also tell you how you can create your own custom tag and use it in TextArea! That’s all for now. I hope you have enjoyed it.

Leave a comment

Convert string to function!

Convert string to function!

It’s Sunday night and few hours ago I was sitting in front of the TV watching some silly shows that I thought maybe I can write a short article about how you can convert a string into a function call! A little class that I had written a while ago when I was working on the TextArea project is named DynamicFunc. You may download it from here (it’s inside the TextArea package). com.doitflash.tools.DynamicFunc

Don’t look inside of it as it’s full of complex and nonsense RegExp commands that even I can’t remember what they mean! You see, I love RegExp because of the great power it has in parsing strings. Actually with the help of it, I was able to build a semi-xml parser and it was a great experience but I hate the bastard as much as I love it! Simply because I can never memories the commands and whenever I want to create a new pattern, I have to get back to all possible references in my books and online.

Anyway, what you’ll be able to do in the next 5 minutes is to convert the following string into a real function call! “myFunc(value,value2,[arr1,arr2,arr3],{var1:value1,var2:value2,var3:value3})”. As you see, it seems like a function call which you’re passing arguments in 3 different formats, simple strings, arrays and objects.

You can think of many occasions that you would need this. Imagine you’re working with external data in your database or just a simple xml file and from there you want to be able to control how a function in your AS3 project is called, then what will you do?

If you don’t know how to work with RegExp, you may think of many different hacks around this, just like how I used to do few years back. I’m not going to talk about those hacks as I believe, the DynamicFunc solution, is the best.

So, basically, DynamicFunc will grab the string and reads each character and understands what type of parameters you’re passing. If you have your string in a variable like this:


var myString:String = "myFunc(value,value2,[arr1,arr2,arr3],{var1:value1,var2:value2,var3:value3})";

Then all you have to do is to initialize DynamicFunc and feed it with the string like this:
var df:DynamicFunc = new DynamicFunc(myString);

Maybe you have the function in your AS3 code like below:
function myFunc($str1:String, $str2:String, $arr:Array, $obj:Object):void
{
trace($str1);
trace($str2);
trace($arr);
trace($obj);
}

After sending the string into DynamicFunc, then it will be easy to call the function, like below:


this[df.funcName].apply(null, df.inputs);

Cool, right?
Hadi

2 Comments

Easily Create Souped-Up Flash Text Fields With TextArea

Easily Create Souped-Up Flash Text Fields With TextArea

In this tutorial I’ll walk you through the steps required to install and use the TextArea component as an alternative to Flash’s native TextField class, and show you how to detect mouse roll over/out events on hyperlinks. I’ll also talk about how you can call custom functions and pass different data types as arguments.

Background

The native TextField class was the first to support text scripts in Flash projects. With TextField, you could support dynamic and static text, as well as the input type to allow user interactivity. It also supported a (very limited) selection of HTML tags for styling your scripts – but when comparing this narrow availability of HTML support in TextField to what is possible with regular HTML files being used within browsers, Flash developers felt the extreme lack of flexibility when dealing with text.

In 2009 when TLFTextField was introduced, developers were hoping to see some solutions – but these didn’t appear. Today, with the TextArea class, you can do what you always wanted with your text blocks. Functionalities like detecting roll over/out on href links, calling custom functions from text blocks, creating anchor links, loading custom created tags like video players, slideshow, and buttons: these are all now possible with TextArea.

Click to see the full tutorial on active.tutsplus.com
Leave a comment

Custom Event Listener

Custom Event Listener

When writing your AS3 projects, you will need events. The main thing that events do is to help you make a bridge between your instances of classes. take the adobe’s MouseEvent as an example. you add a MouseEvent.CLICK listener to a movieclip so that when you click on a movieclip instance it will dispatch the “CLICK” event. it works like below as you know.


import flash.events.MouseEvent;
mc.addEventListener(MouseEvent.CLICK, onClick);
function onClick(e:MouseEvent):void
{
trace("mc is clicked")
}

this is all good, you have used an event being built by adobe (there are many other premade events by flash if you just check the package flash.events) Continue reading

Leave a comment

Unload an externally loaded swf file

Unload an externally loaded swf file

How to remove or unload an externally loaded swf file from your project?

It happenes a lot that you try to load an external SWF file into your project. maybe in your portfolio or some swf movies or sound files. The problem I am going to talk about here is about the common problem of unloading the swf files!

you see, if you have loaded an swf file which has some music on it playing constantly, when you try to unload/remove that swf, the sound keeps playing! (not just sounds, maybe some Event.ENTER_FRAME or other listeners are still working)

to avoid this problem, the best solution I can think of is to add a REMOVED_FROM_STAGE listener in your external swf file so it can listen to when it’s removed from the stage so it can kill the running processes inside itself.

simply add it like this:

[cc lang="php" line_numbers="true" nowrap="false" width="100%"]
import flash.events.Event;
this.addEventListener(Event.REMOVED_FROM_STAGE, onStageRemoved);
function onStageRemoved(e:Event):void
{
// kill all listeneres and running processes here.
}
[/cc]

4 Comments
Contact UsContact Us
Contact MyFlashLab Team?

Feel free to drop us an email if you have any question regarding the TextArea class or the tag modules.

* required
Send Message