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

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();

Related

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
}

ActionScript: To perform non graphical operations

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.

unload dynamically loaded swf after displaying it AS3

I am doing a presentation on which I need to use a lot of video clips. I load all these videos dynamically using Loader. I use a code snippet like this:
var req:URLRequest = new URLRequest("video.swf");
var a:Loader = new Loader();
a.load(req);
stage.addChild(a);
a
Now the issue is: When I get to say the 7th one, it starts lagging. I do not know why, but I think it is because everything is loaded to memory. Is there a way I can erase a video from memory after displaying it? Or is there another solution to this?
If you just load a new video each time and add it to the stage, you will have a rather big hierarchy of movies sitting on top of each other; all kept on stage and in memory.
If you keep a reference to the previously loaded movie, you can just remove it from the stage when the 'next' movie is loaded. Haven't tested this properly, but just to give you an idea of what the code might look like:
var oldLoader:Loader = null;
var a:Loader = new Loader();
a.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete);
a.load(<your url>);
function loader_complete(e:Event):void {
var newLoader:Loader = e.currentTarget.loader as Loader;
stage.addChild(newLoader);
if(oldLoader != null) {
stage.removeChild(oldLoader);
oldLoader = null;
}
oldLoader = newLoader;
}
I think I found the solution. If you use removeChild, it only stops displaying, but the whole thing is still in memory (cache). So the more you load the videos, the more you fill up the cache. What we need is something that completely clears the cache before loading another video.
I used unloadAndStop() and it seem to have completely done the trick, unless someone has something against it.
Thanks 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.

Audio of a specific video swf doesn't stop when I load another URLRequest

I am trying to stop the audio of the video swf and I can't get it to stop. Here is my code for loading the file:
var myLoader:Loader= new Loader();
myLoader.x=420;
myLoader.y=200;
// boolean variable set for use below in our function
var screenCheck:Boolean = false;
//These three linces keep stafe elements the same size, so they don't distort
var swfStage:Stage = this.stage;
video_btn.addEventListener(MouseEvent.CLICK,contentvideo);
function contentvideo (event:MouseEvent):void{
myLoader.load(new URLRequest("prevideo.swf"));
addChild(myLoader);
movie_btn.stop();
movie_btn.visible=false;
}
Now I have other functions that load different URLRequest and when they are loading, the audio keeps playing. Do I have to add a line of code to them? I also have an MP3 player and tried SoundMixer.stopAll(). I still need the mp3 player to keep playing.
I'm not familiar with what you're doing but just looking at the code and given the problem you're experiencing I wonder if that
addChild(myLoader);
has anything to do with it. It seems like the kind of thing that could easily create multiple child objects which is why you continue to experience the sound play back. Is there a removeChild[0] option or something?
A shot in the dark I know but I thought I'd offer the possibility anyway.