ActionScript: To perform non graphical operations - actionscript-3

As I understand, ActionScript is used mostly to control graphical output on Flash websites: such as Flash based games.
However, I would like ActionScript to perform tasks not related to graphical output. Tasks, which for browser compatibility reasons, are more suitable for ActionScript: such as file upload.
Is it therefore possible to use ActionScript instead of JavaScript or to accomplish tasks that are not possible with JavaScript, such as file upload?
Are the following possible?
Run ActionScript on HTML Button Press?
Send information to ActionScript from HTML/JavaScript?
Process information without any graphical output in ActionScript?
Ouptut information from ActionScript to HTML/JavasScript?
I wish to know, if ActionScript can do what I wish.
I will have a picture of the right functions to call.

ExternalInterface is your friend:
http://help.adobe.com/nl_NL/Flash/CS5/AS3LR/flash/external/ExternalInterface.html
Some tips when using ExternalInterface:
set allowScriptAccess to "always" in the html embed code
make sure the flash has an id in your html code
Some simple examples:
1. Grab a value from javascript to flash
// actionscript 3 code
if (ExternalInterface.available)
{
var url:String = ExternalInterface.call("document.location");
// output to textfield
var t:TextField = new TextField();
addChild(t);
t.text = url;
}
2. Call a function with parameters from flash
// actionscript 3 code
if (ExternalInterface.available)
{
var result:String = "Flash rocks"
ExternalInterface.call("alert", result);
}
3. Call from javascript a function with parameters to Flash:
// javascript
window.onLoad = function()
{
document.getElementById('flashId').doSomething("javascript rocks");
}
.. and
// actionscript 3
if (ExternalInterface.available)
{
ExternalInterface.addCallback("doSomething", handleSomethingFromJavascript);// links js function to as3 function
function handleSomethingFromJavascript(value:String):void
{
// output to textfield
var t:TextField = new TextField();
addChild(t);
t.text = value;
}
}
You can do lots of stuff between flash and javascript, as you can see the intergration is almost painless! The only note is that within flash ExternalInterface is not available, so you have to test in browser. You can make a transparent Flash object using wmode="transparent". You cannot use display:none or visibility (css) because then the flash isnt executed or acts slower. To make sure it keeps running, place it position:fixed (css) on the page in a corner or something. Browsers make flash object run in a sort of sleep mode (slower) when out of screen or when inactive (ie in an inactive tab)

You can't really replace javascript with actionscript, but you can interact with it.
"Run ActionScript on HTML Button Press?" - Yes, this is possible through ExternalInterface.registerCallback. However, many actions (iirc, opening the file browser) can only be done on user interaction in flash, so you would need a flash button for that.
"Send information to ActionScript from HTML/JavaScript?" Also through externalInterface, or flashvars (but only at startup).
"Process information without any graphical output in ActionScript?" - It's a programming language, so sure. What did you have in mind?
"Ouptut information from ActionScript to HTML/JavasScript?" - yes, also through ExternalInterface.

Related

Is there a way to make clicking a button in Adobe Flash open multiple hyperlinks?

Simply put, is there a way to make clicking a button object in Flash Actionscript 3.0 open two hyperlinks in a browser? I've tried messing with the Actionscript and adding multiple functions, to no avail.
Use two different window strings:
var url:URLRequest = new URLRequest("http://stackoverflow.com/questions/35561823/is-there-a-way-to-make-clicking-a-button-in-adobe-flash-open-multiple-hyperlinks");
navigateToURL(url, "_blank");
var url:URLRequest = new URLRequest("http://www.stackoverflow.com");
navigateToURL(url, "_blank2");
Note:
For local content (via file://) running in a browser, navigateToURL will not work unless your html/swf is in the local-trusted security sandbox.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/package.html#navigateToURL()

Recording using Flex/Flash

I know that we can not record/Access anything out of flash player, because of it's security sandbox.
Instead We can record the video while streaming it to server.
like
netStream.publish("YourFileName.flv","record");
But in recorde file, I will get only a video file Published by webcam to server and i want to record entire session.
Is there any way to record it locally, or Can i record the window ??
p.s. : I am not trying to access anything outside of flash player.
Thanks in advance...
ok, so you can record the entire contents of the swf like this:
first, create a container object (anything that extends DisplayObject which implements IBitmapDrawable) then place everything that you want to capture (video view and everything else in your "session") then using an ENTER_FRAME event or Timer (preferable to control capture fps), draw the container to a BitmapData using BitmapData.draw(container). Pass that BitmapData to the FLV encode library found here using it's addFrame() method (docs and examples come with that library... super easy) and that's it! When you are done, you will have an flv video containing a frame by frame "screen capture" of what was going on in your swf! Just make sure EVERYTHING is in the container! That lib also accepts captured audio too if you want.
private function startCapturing():void{
flvEncoder.start(); // see the libs docs and examples
var timer:Timer = new Timer(1000/15); //capture at 15 fps
timer.addEventListener(TimerEvent.Timer, onTimer);
timer.start();
}
private function onTimer(event:TimerEvent):void{
var screenCap:BitmapData = new BitmapData(container.width, container.height);
screenCap.draw(container);
flvEncoder.addFrame(screenCap); // see the libs docs and examples
}

What should i use to load audio in as3 instead of load()?

I have a setup of 4x4 drum pads which are essentially buttons or movie clips with 3 states to show visual feedback (like the lighting up of the pads when they are pressed). I have tested this setup on an android tablet as well as a windows 7 touch-enabled laptop. Obviously the windows 7 laptop is more powerful and thus more responsive.
But not responsive enough.
I am wondering how I should be approaching the loading of audio files which are short drum-kit sample sounds in mp3 format stored in an assets folder next to the swf file.
Is there a better way, such as a way to cache the sounds so that I don't have to reload them each time the sound event is triggered?
Any help on this is greatly appreciated. (I just am not aware of how else, right now, to approach loading sounds other than calling a new sound each time the pad is pressed, thus not really caching the sound)
var kickc_03:Sound=new kickc_03_mp3(); // not sure whether to use Sound() or kickc_03 here..
// or
var kickc_03:kickc_03_mp3=new kickc_03_mp3();
// they will both work because kickc_03_mp3 subclasses Sound.
if i were you i would do something like:
// execute this once
var drumNum:int = 16;
var soundArray:Array = [null];
var C:Class;
init();
function init():void{
for(var i:int=1;i<=drumNum;i++){
C = Class(getDefinitionByName("kickc_"+formatF(i)+"_mp3");
soundArray.push(new C());
}
function formatF(n:int):String{
var s:String=n.toString();
while(s.length<2){
s="0"+s;
}
return s;
}
//////////////////////////////////////////////
now anytime you want to generate a kickc_somenum_mp3 sound, use:
soundArray[somenum].play();

How to properly add "Replay" functionality to a self-preloaded Flash movie?

I made a Flash project in FlashDevelop to create an Ad.
The Preloader is setup by making use of the Additional Compiler argument:
-frame=NameOfLabel,NameOfMainClass
My main class is simply called "Main", at the top / default package level.
So frame #1, being the Preloader portion of the SWF, has:
Very few bitmaps, vector-graphics and text (to stay under 50kb);
A YouTube video player in the center (does not count in the filesize limit);
The frame #2 has everything else (the Main class basically embeds all it's dependencies). This includes:
Assets from precompiled SWF (Bitmaps, Symbols, Fonts, XML data);
All classes imported (this is recursive for every classes importing other classes);
Now my big problem is, my client requested the "replay" functionality long after I've completed 99.9% of the project.
I have the project more-or-less broken into different states (Intro, Ready, SlideMenu, etc.), but I'm not sure how I can easily reset the Flash movie back to the very beginning (where it was preloading and showing the YouTube video).
The easy solution would be to simply call an ExternalInterface JavaScript method that would refresh the Flash container, BUT I don't think I have control over what's going on the HTML / JavaScript side.
Is there an easy way to invoke a replay function from AS3?
Would not simply going back to frame 1 do the trick ?
The following seems to do the trick!
private function onReplayClick(e:MouseEvent):void {
var theStage:Stage = this.stage; //Temporarly store the stage.
//Kill any animations happening:
TweenMax.killAll(); //3rd party, may not be applicable for you :P
//Remove ALL containers / child DisplayObjects
SpriteUtils.recursiveRemove(theStage); //custom-made
// (this object is no longer attached to the stage at this point)
//Nullify any Singleton / Static variables:
Main.INST = null;
// Load the 'bytes' of the current SWF in a new Loader, then...
// add it to the stage
var swf:Loader = new Loader();
swf.loadBytes( theStage.loaderInfo.bytes );
theStage.addChild( swf );
}
By doing a deep recursive cleanup of the DisplayObjects, and any static variables (like Singleton instances), it leaves you with a blank stage.
After that, you can instantiate a new Loader that will load the SWF itself via the current LoaderInfo's bytes property.
Add the Loader to the Stage, and you're up and running again!

Going from Flash 8 to CS3

After many years of using Flash 8, I'm moving to CS3 at work. I know I'll have to learn AS 3.0 so, does anyone have any good references or summaries of the major/most noticeable changes? Also, are there any tips/tricks for the flash environment? After spending a few minutes in CS3, I noticed that you can't directly attach actionscript to a button, which is new to me. Any other such pitfalls to watch over?
I made the total switch just about 3 months ago, here are some things that helped me ramp up rather quickly:
1) Do everything in Class files
A lot of AS3 tutorials out there deal with just code pasted on the timeline (which I can't stand because now you have to hunt for what import you need), but is fine for quick tiny stuff. In the long run it's way better work primarily in Class files. Learning how Classes work opened a huge door for me, it was the same feeling/experience I had when I first discovered Functions in AS2 :)
2) Keep graphics in library and off the workspace
Example, you have a jpg, gif, png file you just imported into your library. Made a movieClip and gave it a class name(MyButton). Now the code below will place the graphic into the workspace for you:
var myButton:MovieClip = new MyButton();
myButton.x = 6;
myButton.y = 22;
myButton.buttonMode = true;
addChild(myButton);
3) Get use to the new button code in AS3
It's something all of us new converts had to deal with painfully, but now it's a piece of cake :)
myButton.addEventListener(MouseEvent.MOUSE_UP, clickThis);
function clickThis(event:MouseEvent):void
{
navigateToURL(new URLRequest("form.html"), "_self");
//navigateToURL(request, '_self');
}
4) Make sure you remove Event Listeners after use
It took me a bit to wrap my around this one... remove em why? Oh they are still running in the background and when I listen again I'll get all kinds of mutated errors.
private function volDown(e:MouseEvent):void
{
masker.width = volControl.mouseX;
userVolume = (masker.width / 100) * 1;
volControl.addEventListener(MouseEvent.MOUSE_MOVE, volMove);
}
private function volUp(e:MouseEvent):void
{
lastVolPoint = masker.width;
setVolume(userVolume);
e.updateAfterEvent();
volControl.removeEventListener(MouseEvent.MOUSE_MOVE, volMove);
}
5) Don't forget to pass Events
I'm not a programmer by trade and this has caused so much grief, I'm glad I'm done with this birthing pain:
myButton.addEventListener(MouseEvent.MOUSE_UP, clickThis);
Since the clickThis function is launched via an Event, you have to pass: event:MouseEvent into it like so:
function clickThis(event:MouseEvent):void
Because the code below will throw the dreaded AS3 "Access of undefined property" error that new AS3 guys will always run into.
function clickThis():void
6) Read and post questions on StackOverflow... a lot!
btw I'm still a noob and originally a designer then AS2 dev, I still don't know why we put :void behind a function name.. if we have similar coding backgrounds I hope all that helps :)
I suggest you to look at the ActionScript language migration page on the Adobe devnet. It offers quite a lot articles about the key changes with ActionScript 3.
To answer your problem with the actions on a button, this no longer works (and was already with ActionScript 2 not the best way to do it). AS3 requires the code to be centralized on the timeline. So for giving a button some action, you'll need to give it an instance name and add an event listener for the CLICK event, like this:
function doSomething ( event:MouseEvent ):void
{
trace( "test" );
}
myButton.addEventListener( MouseEvent.CLICK, doSomething );
Get an Actionscript 3 IDE. Such as Flash Builder, FlashDevlop, or FDT. This will force you to learn really fast.